🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@janus-validator/dsl

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@janus-validator/dsl

Concise DSL for Janus Validator - short aliases for all combinators

latest
npmnpm
Version
0.6.0
Version published
Maintainers
1
Created
Source

@janus-validator/dsl

Concise DSL for Janus Validator - short aliases for all validators and combinators.

The DSL is “just syntax”: it builds validators from @janus-validator/core, so you still get:

  • Forward validation: validate(unknown)
  • 🎲 Backwards generation: new Generator(rng).generate(validator)

Installation

npm install @janus-validator/dsl @janus-validator/core

Quick Start

import { B, U, S, I, N, L, R, O, Bytes, Or, Seq, optional, oneOrMore } from '@janus-validator/dsl';
import { Generator } from '@janus-validator/core';

// Define validators with concise syntax
const userValidator = O({
  name: U(1, 100),
  age: I(0, 150),
  email: R(/^[\w.]+@[\w.]+\.\w+$/),
  active: B(),
  role: Or('admin', 'user', 'guest'),  // Primitives auto-wrapped
  version: 1,                           // Also auto-wrapped
});

// Validate data
const result = userValidator.validate({
  name: 'Alice',
  age: 30,
  email: 'alice@example.com',
  active: true,
  role: 'admin',
  version: 1,
});

// Generate test data
const generator = new Generator({ random: Math.random });
const testUser = generator.generate(userValidator);

Why this is powerful

The same validator definition can be used:

  • In production (validate API requests / config / events)
  • In tests (generate fixtures that must satisfy the same constraints)
import { Generator } from '@janus-validator/core';
import { O, U, I } from '@janus-validator/dsl';

const User = O({ name: U(1, 50), age: I(0, 150) });
const generator = new Generator({ random: Math.random });

const fixture = generator.generate(User);
const roundTrip = User.validate(fixture);
// roundTrip.valid === true

DSL Reference

Primitive Validators

FunctionDescriptionExample
B()BooleanB()
U(min?, max?)Unicode string with length rangeU(1, 100)
S(...parts)Compound string from partsS(digits(4), '-', digits(2))
I(min?, max?)Integer in rangeI(0, 150)
N(min?, max?)Float in rangeN(-273.15, 1000)
L(min?, max?)64-bit BigIntL(0n, 1000n)
R(pattern)Regex patternR(/^\d{3}-\d{4}$/)
Bytes(min?, max?)Binary data (Uint8Array)Bytes(16, 32)

Object & Special Values

FunctionDescriptionExample
O(schema, strict?)Object/struct validatorO({ name: U(), age: I() })
C(value)Constant valueC(42), C('hello')
Null()Matches nullNull()
Undefined()Matches undefinedUndefined()
Inf()Positive infinityInf()
NInf()Negative infinityNInf()
NaN()Not-a-NumberNaN()
Enum(enumObj)TypeScript enumEnum(Status)

Combinators

FunctionDescriptionExample
Or(...validators)Union/alternationOr(U(), I(), Null())
Seq(...validators)Tuple/sequenceSeq(U(), I(), B())

Character Sets (for S())

FunctionShortDescription
digits(n)D(n)Digits (0-9)
lower(n)Lowercase (a-z)
upper(n)Uppercase (A-Z)
letters(n)Letters (a-zA-Z)
alphanumeric(n)A(n)Alphanumeric
hex(n)H(n)Hex (0-9a-f)
hexUpper(n)Hex (0-9A-F)
chars(set, n)Custom char set

Quantifiers

FunctionDescriptionExample
zeroOrMore(v)0+ elementszeroOrMore(I())
oneOrMore(v)1+ elementsoneOrMore(U())
optional(v)0 or 1 elementoptional(U())
exactly(v, n)Exactly n elementsexactly(I(), 3)
atLeast(v, n)n+ elementsatLeast(U(), 2)
between(v, min, max)min-max elementsbetween(I(), 1, 5)

Type Assertion

interface User { name: string; age: number; }

const userValidator = Typed<User>()(O({
  name: U(1, 100),
  age: I(0, 150),
}));
// Or use As<User>() as an alias

Capture & Reference

const { capture, ref, context } = createCaptureGroup();

const form = O({
  password: capture('pwd', U(8, 100)),
  confirmPassword: ref('pwd'),
});

String Modifiers

// Case-insensitive matching
const hexColor = caseInsensitive(S('#', hex(6)));
hexColor.validate('#AABBCC'); // valid
hexColor.validate('#aabbcc'); // valid

Recipes

1) Nested objects (strict vs non-strict)

import { O, U, I } from '@janus-validator/dsl';

const User = O({
  name: U(1, 100),
  age: I(0, 150),
});

const StrictUser = O({ name: U(1, 100), age: I(0, 150) }, true);

2) “Enum-like” values (auto-wrapping)

import { Or } from '@janus-validator/dsl';

const Status = Or('pending', 'active', 'complete');
// Type is: Validator<'pending' | 'active' | 'complete'>

3) Formatted strings without regex

import { S, D, H } from '@janus-validator/dsl';

const ISODate = S(D(4), '-', D(2), '-', D(2));      // YYYY-MM-DD
const UUID = S(H(8), '-', H(4), '-', H(4), '-', H(4), '-', H(12));

4) Capture & reference (e.g. password confirmation)

import { O, U, createCaptureGroup } from '@janus-validator/dsl';

const { capture, ref, context } = createCaptureGroup();

const Signup = O({
  password: capture('pwd', U(8, 100)),
  confirmPassword: ref('pwd'),
});

// If reusing between validations, clear captures
context.clear();

Auto-Wrapping

The Or, Seq, and O combinators automatically wrap primitive values and enums:

// Primitives auto-wrapped in Constant
const protocol = Or('http', 'https', 'ws');  // No need for C()
const config = O({ version: 1, env: 'prod' });

// Enums auto-wrapped
enum Status { Active = 'active', Inactive = 'inactive' }
const task = O({
  status: Status,  // Automatically creates Or('active', 'inactive')
});

License

MIT

Keywords

validator

FAQs

Package last updated on 12 Dec 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts