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

ruls

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ruls

Typesafe rules engine with JSON encoding

  • 1.2.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

📏 Ruls

Typesafe rules engine with JSON encoding

License NPM Downloads

Features

  • Intuitive interface
  • JSON-encodable rules
  • Compatible with all type validation libraries

Setup

Install ruls with your package manager of choice:

npmnpm install ruls
Yarnyarn add ruls
pnpmpnpm add ruls

Once complete, you can import it with:

import {rule, signal} from 'ruls';

Also, bring your favorite validation library (e.g. zod):

import {z} from 'zod';

Usage

type Context = {
  user: {
    age: number;
    isActive: boolean;
    username: string;
    hobbies: Array<string>;
  };
};

const signals = {
  age: signal.type(z.number()).value<Context>(({user}) => user.age),
  isActive: signal.type(z.boolean()).value<Context>(({user}) => user.isActive),
  username: signal.type(z.string()).value<Context>(({user}) => user.username),
  hobbies: signal
    .type(z.array(z.string()))
    .value<Context>(({user}) => user.hobbies),
};

const programmers = rule.every([
  signals.age.greaterThanOrEquals(18),
  signals.isActive.isTrue(),
  signals.username.startsWith('user'),
  signals.hobbies.contains('programming'),
]);

const isEligible = await programmers.evaluate({
  user: {
    age: 25,
    isActive: true,
    username: 'user123',
    hobbies: ['reading', 'programming', 'traveling'],
  },
});

Context

The contextual data or state relevant for evaluating rules. It encapsulates the necessary information required by signals to make decisions and determine the outcome of rules.

Example
type Context = {
  user: {
    age: number;
    isActive: boolean;
    username: string;
    hobbies: Array<string>;
  };
};

Signal

A specific piece of information used to make decisions and evaluate rules. It acts as a building block for defining conditions and comparisons in the rule expressions. Signals encapsulate the logic and operations associated with specific data types, allowing you to perform comparisons, apply operators, and define rules based on the values they represent.

Example
const signals = {
  age: signal.type(z.number()).value<Context>(({user}) => user.age),
  isActive: signal.type(z.boolean()).value<Context>(({user}) => user.isActive),
  username: signal.type(z.string()).value<Context>(({user}) => user.username),
  hobbies: signal
    .type(z.array(z.string()))
    .value<Context>(({user}) => user.hobbies),
};

These modifiers and operators apply to all signal types:

ModifierDescriptionEncoded
notInverts the operator result{$not: rule}
OperatorDescriptionEncoded
equalsMatches the exact value{$eq: value}
inMatches if the value in the list{$in: [...values]}

string type

OperatorDescriptionEncoded
includesMatches if the string includes a specific value{$inc: value}
startsWithMatches if the string starts with a specific value{$pfx: value}
endsWithMatches if the string ends with a specific value{$sfx: value}
matchesMatches the string using a regular expression{$rx: regex}

number type

OperatorDescriptionEncoded
lessThanMatches if the number is less than a specific value{$lt: value}
lessThanOrEqualsMatches if the number is less than or equal to a specific value{$lte: value}
greaterThanMatches if the number is greater than a specific value{$gt: value}
greaterThanOrEqualsMatches if the number is greater than or equal to a specific value{$gte: value}

boolean type

OperatorDescriptionEncoded
isTrueMatches if the boolean is true{$eq: true}
isFalseMatches if the boolean is false{$eq: false}

Array type

OperatorDescriptionEncoded
everyMatches if all of the array elements passes the rule{$and: [rule]}
someMatches if at least one of the array elements passes the rule{$or: [rule]}
containsMatches if the array contains the specific value{$all: [value]}
containsEveryMatches if array contains all of the specific values{$all: [...values]}
containsSomeMatches if array contains at least one of the specific values{$any: [...values]}

Rule

Allows you to define complex conditions and criteria for decision-making. It consists of one or more signals, which can be combined using logical operators to create intricate structures.

Example
const programmers = rule.every([
  signals.age.greaterThanOrEquals(18),
  signals.isActive.isTrue(),
  signals.username.startsWith('user'),
  signals.hobbies.contains('programming'),
]);

Combination

OperatorDescriptionEncoded
everyMatches if all of the rules pass{$and: [...rules]}
someMatches if at least one of the rules pass{$or: [...rules]}
noneMatches if none of the rules pass{$not: {$or: [...rules]}}

Encoding

Rules can be encoded into objects and/or JSON. That makes it possible to store them on a database for runtime retrieval.

const check = rule.every([
  signals.sampleString.matches(/3$/g),
  signals.sampleArray.not.contains(246),
]);

// Encoding
const encodedCheck = check.encode(signals);
expect(encodedCheck).toEqual({
  $and: [{sampleString: {$rx: '/3$/g'}}, {$not: {sampleArray: {$all: [246]}}}],
});
expect(JSON.stringify(encodedCheck)).toEqual(
  '{"$and":[{"sampleString":{"$rx":"/3$/g"}},{"$not":{"sampleArray":{"$all":[246]}}}]}',
);

// Decoding
const parsedCheck = await rule.parse(encodedCheck, signals);
expect(parsedCheck.encode(signals)).toEqual(encodedCheck);

Keywords

FAQs

Package last updated on 21 Jul 2023

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

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