npm package: @ripp/operander
Description: JSON Serializable operands with the ability to resolve against a given object or callback method
Author: Charly Rippenkroeger
Latest version: 1.0.2

# Operander

JSON Serializable operands with the ability to resolve against a given object or callback method.
Of course without the use of `eval`!

Designed to read and flow as a natural if-statement and allow extendability where needed.

An interactive demo and RuleSet builder are available in the `ui/` app (see `ui/README.md`), as well as more operators.

## Quick Start

```javascript
import { process } from '@ripp/operander';

// Template: ["value or $.ref", "operator", "value or $.ref"]
const rule = ['$.age', '>', 18];
const data = { age: 25 };

process(rule, data); // true
```

## Examples

```javascript
import { process, extractVariables } from '@ripp/operander';

let obj = {
  "example": "value",
  "deep": {
    "value": "neat!"
  }
}

// Simple rules
let simpleRule1 = ["$.example", "===", "value"];
let simpleRule2 = ["$.deep.value", "===", "neat!"];

process(simpleRule1, obj); // true
process(simpleRule2, obj); // true

// Complex rule with AND
let complexRule = [["$.example", "===", "value"], "AND", ["$.deep.value", "===", "neat!"]];
process(complexRule, obj); // true

// Nested rules with AND/OR
let moarComplexRule = [
  ["$.example", "===", "value"], 
  "AND", 
  [
    ["$.deep.value", "===", "neat!"], 
    "OR", 
    [true, '===', 'false']
  ]
];
process(moarComplexRule, obj); // true

// Using a resolver function instead of an object
let resolver = key => (key === 'yay') ? 'Example!' : 'ehhh...';
process(["$.yay", "===", "Example!"], resolver);  // True
process(["$.test", "===", "Example!"], resolver); // False

// Extract variable references from rules
const vars = extractVariables(simpleRule1); // { example: null }
const varsWithValues = extractVariables(simpleRule1, obj); // { example: "value" }
```

## Use Cases

### 1. Dynamic Access Control & Authorization

**Problem:** You need to implement fine-grained access control where permission rules can be stored in a database, modified by administrators without code changes, and evaluated at runtime. 
Hard-coding permission checks in your application makes it difficult to adapt to changing business requirements.

**Solution:** Store authorization rules as JSON-serializable operander statements in your database, then evaluate them against user data at runtime.

```javascript
import { process } from '@ripp/operander';

// Rules stored in database
const adminAccessRule = [
  ['$.user.role', '===', 'admin'],
  'OR',
  [['$.user.role', '===', 'moderator'], 'AND', ['$.user.verified', '===', true]]
];

const resourceAccessRule = [
  ['$.user.id', '===', '$.resource.ownerId'],
  'OR',
  [['$.resource.public', '===', true], 'AND', ['$.user.subscribed', '===', true]]
];

// Evaluate at runtime
const user = { role: 'moderator', verified: true, id: '123', subscribed: true };
const resource = { ownerId: '456', public: true };

const canAccessAdmin = process(adminAccessRule, { user }); // true
const canAccessResource = process(resourceAccessRule, { user, resource }); // true
```

### 2. Configurable Form Validation Rules

**Problem:** You're building a form builder or need to validate user input based on rules that may change frequently. 
Hard-coding validation logic requires redeploying your application for every rule change, and different forms may need different validation criteria.

**Solution:** Define validation rules as operander statements that can be stored in configuration files or a database, allowing non-developers to modify validation logic without touching code.

This could also act as a solution to dynamic validation rules, such as a website that performs differently based on the user, group, product, or branding path the app is accessed by.

```javascript
import { process, extractVariables } from '@ripp/operander';

// Validation rules defined in configuration
const emailValidation = [
  ['$.email', '!==', ''],
  'AND',
  [['$.email', 'in', ['admin@example.com', 'user@example.com']], 'OR', ['$.email', 'in', ['$.allowedDomains']]]
];

const ageValidation = [
  ['$.age', '>=', 18],
  'AND',
  ['$.age', '<=', 100]
];

const passwordValidation = [
  ['$.password.length', '>=', 8],
  'AND',
  ['$.password.length', '<=', 128]
];

// Validate form data
const formData = { email: 'user@example.com', age: 25, password: { length: 12 } };
const isValid = process([
  [emailValidation, 'AND', ageValidation, 'AND', passwordValidation]
], formData); // true

// Extract required fields for dynamic form generation
const requiredFields = extractVariables([emailValidation, ageValidation, passwordValidation]);
// { email: null, age: null, 'password.length': null }
```

### 3. Business Rules Engine for E-commerce

**Problem:** Your e-commerce platform needs to apply complex discount eligibility rules, shipping restrictions, and product visibility rules that change frequently based on promotions, inventory levels, and customer segments.
Hard-coding these rules creates maintenance nightmares and slows down business agility.
Upkeeping rules in a well-structured table is too strict for the fast-paced market and flexibility of various products, discounts, or rules.

**Solution:** Store business rules as operander statements, allowing business analysts to define and modify rules through a UI that stores JSON, while developers focus on the rule evaluation engine.

```javascript
import { process } from '@ripp/operander';

// Discount eligibility rule stored in database
const discountEligibility = [
  [
    ['$.customer.tier', '===', 'premium'],
    'OR',
    [['$.order.total', '>=', 100], 'AND', ['$.customer.loyaltyPoints', '>=', 500]]
  ],
  'AND',
  ['$.product.category', '!in', ['excluded-categories']],
  'AND',
  ['$.inventory.stock', '>', 0]
];

// Shipping restriction rule
const shippingRestriction = [
  ['$.order.weight', '<=', 50],
  'AND',
  [
    ['$.shipping.country', '===', 'US'],
    'OR',
    [['$.shipping.country', 'in', ['$.allowedCountries']], 'AND', ['$.order.value', '>=', 25]]
  ]
];

// Product visibility rule
const productVisibility = [
  ['$.product.status', '===', 'active'],
  'AND',
  [
    ['$.product.public', '===', true],
    'OR',
    [['$.user.role', '===', 'admin'], 'OR', ['$.user.id', '===', '$.product.sellerId']]
  ]
];

// Evaluate rules at runtime
const context = {
  customer: { tier: 'premium', loyaltyPoints: 600 },
  order: { total: 150, weight: 30, value: 150 },
  product: { category: 'electronics', status: 'active', public: true, sellerId: 'seller123' },
  inventory: { stock: 10 },
  shipping: { country: 'US' },
  user: { role: 'customer', id: 'user456' },
  allowedCountries: ['US', 'CA', 'MX']
};

const eligibleForDiscount = process(discountEligibility, context); // true
const canShip = process(shippingRestriction, context); // true
const isVisible = process(productVisibility, context); // true
```

## Install

```sh
npm i @ripp/operander --save

yarn add @ripp/operander
```


## Basic Use

This concept is basically made up of:
* [Statements](#statements) ( `[ Left Operand, operator, Right Operand ]` )
* [Statement Chaining](#chaining) ( `"AND"` and `"OR"` )

```
       Operator            Chaining
          |               /
         \'/             /
[ [ X,  "===",   Y ], "AND", [ I, "!==" Z ] ]
    ^            ^
    |            |
    `- Operands -`
```

### Statements

The 2nd entry in a rule is always the 'operator', telling which function to call to utilize the two values on either side of it.
See [available operators](#available-operators) below.

Operands can either be solid values or references.
Solid values (true, 123, 'cool strings', etc..) are treated as the value to test against.

References are strings and identified by a `$.` prefix.
If providing an object to `process`, this reference can be a period-delimited string into the object.
A safe getting (`safeGet`) function is used and returns `undefined` if an intermediate object doesn't exist as to avoid "null pointers".

If providing a resolver function instead of an object, the `$.` prefix is used to identify to call the resolver.
Resolver will receive the key without the `$.` prefix, which allows you to use it however you please, such as complex selectors.

> Note that the resolver must be synchronous.
> If looking to collect data from a remote resource, see [Extracting Variables](#extracting-variables).


#### Available Operators

**Equality**

| Operator | Description                | Example(s) (true results) |
| :------: | :------------------------- | :------------------------ |
| `==`     | Equals (loose)            | `[ [true, "==", 1], "AND", [1, "==", "1"] ]` |
| `===`    | Equals (strict)           | `[ [1, "===", 1], "AND", ["1", "===", "1"] ]` |
| `!=`     | Not equals (loose)        | `[ [true, "!=", false], "AND", [1, "!=", "2"] ]` |
| `!==`    | Not equals (strict)       | `[ [true, "!==", false], "AND", [1, "!==", "1"] ]` |

**Comparison**

| Operator | Description                | Example(s) (true results) |
| :------: | :------------------------- | :------------------------ |
| `<`      | Less than                  | `[1, "<", 5]` |
| `<=`     | Less than or equal         | `[ [1, "<=", 5], "AND", [5, "<=", 5] ]` |
| `>`      | Greater than               | `[5, ">", 1]` |
| `>=`     | Greater than or equal      | `[ [5, ">=", 1], "AND", [5, ">=", 5] ]` |

**Length**

| Operator | Description                              | Example(s) (true results) |
| :------: | :--------------------------------------- | :------------------------ |
| `len=`   | Length equals                            | `[ ["abcd", "len=", 4], "AND", [[1,2,3], "len=", 3] ]` |
| `len!=`  | Length not equals                        | `[ ["abcd", "len!=", 3], "AND", [[1,2,3], "len!=", 2] ]` |
| `len<`   | Length less than                         | `[ ["ab", "len<", 5], "AND", [[1,2], "len<", 3] ]` |
| `len<=`  | Length less than or equal                | `[ ["abc", "len<=", 3], "AND", [[1,2], "len<=", 2] ]` |
| `len>`   | Length greater than                      | `[ ["hello", "len>", 3], "AND", [[1,2,3,4], "len>", 3] ]` |
| `len>=`  | Length greater than or equal             | `[ ["hello", "len>=", 5], "AND", [[1,2,3], "len>=", 3] ]` |
| `len<>`  | Length between two numbers (exclusive)   | `[ ["hello", "len<>", [3, 7]], "AND", [[1,2,3,4], "len<>", [2, 6]] ]` |
| `len<=>` | Length between two numbers (inclusive)   | `[ ["hello", "len<=>", [5, 10]], "AND", [[1,2,3], "len<=>", [3, 5]] ]` |

**Array / String**

| Operator | Description                              | Example(s) (true results) |
| :------: | :--------------------------------------- | :------------------------ |
| `in`     | Value in array / substring in string     | `[ [2, "in", [1,2,3]], "AND", ["world", "in", "Hello World"] ]` |
| `!in`    | Value not in array / not in string       | `[ [5, "!in", [1,2,3]], "AND", ["xyz", "!in", "Hello World"] ]` |
| `has`    | Array has value / string contains value  | `[ [[1,2,3], "has", 2], "AND", ["Hello World", "has", "world"] ]` |
| `!has`   | Array does not have value / string not contains | `[ [[1,2,3], "!has", 5], "AND", ["Hello World", "!has", "xyz"] ]` |

**Range**

| Operator   | Description                              | Example(s) (true results) |
| :--------: | :--------------------------------------- | :------------------------ |
| `between`  | Number between two numbers (exclusive)   | `[5, "between", [1, 10]]` |
| `in-range` | Number between two numbers (inclusive)   | `[ [5, "in-range", [1, 10] ], "AND", [1, "in-range", [1, 10] ], "AND", [10, "in-range", [1, 10]] ]` |

**String**

| Operator      | Description                           | Example(s) (true results) |
| :-----------: | :------------------------------------ | :------------------------ |
| `starts-with` | String starts with prefix (case-insensitive) | `[ ["Hello World", "starts-with", "hello"] ]` |
| `ends-with`   | String ends with suffix (case-insensitive)   | `[ ["Hello World", "ends-with", "WORLD"] ]` |
| `matches`     | String matches regex pattern          | `[ ["abc123", "matches", "^[a-z]+\\d+$"] ]` |

**Type Checking**

| Operator       | Description                                      | Example(s) (true results) |
| :------------: | :----------------------------------------------- | :------------------------ |
| `is-number`    | Value is / is not a number                       | `[ [42, "is-number", true], "AND", ["hello", "is-number", false] ]` |
| `is-string`    | Value is / is not a string                       | `[ ["test", "is-string", true], "AND", [123, "is-string", false] ]` |
| `is-array`     | Value is / is not an array                       | `[ [[1,2], "is-array", true], "AND", ["test", "is-array", false] ]` |
| `is-object`    | Value is / is not a plain object (not array/null)| `[ [{}, "is-object", true], "AND", [[], "is-object", false] ]` |
| `is-null`      | Value is / is not null                           | `[ [null, "is-null", true], "AND", ["test", "is-null", false] ]` |
| `is-undefined` | Value is / is not undefined                      | `[ [undefined, "is-undefined", true], "AND", ["test", "is-undefined", false] ]` |

Custom Operators can be created using the `createOperators` function:
```javascript
import { createOperators, process } from '@ripp/operander';

const customOperators = createOperators({
  'abs-equals': (v1, v2) => {
    return typeof v1 === 'number' && typeof v2 === 'number' && Math.abs(v1) === Math.abs(v2);
  }
});

// Use custom operators
const rule = [-5, 'abs-equals', 5];
process(rule, {}, customOperators); // true
```

Built-in operators can also be used directly:
```javascript
import { OPERATORS } from '@ripp/operander';

OPERATORS['<'](1, 10); // true
OPERATORS['in']('a', ['a', 'b', 'c']); // true
```

### Chaining

As any if-statement would have, [statements](#Statements) can be chained and grouped together with `AND` and `OR`, as well as array nesting.
Imagine the `[` and `]` are `(` and `)` in an if statement and you really like encapsulating each assertion.

```JavaScript
// If statement in comparison to a Operander statement
if ( true   ===   true    and    false   ===   false )
   [[true, "===", true], "AND", [false, "===", false]]

if ( ( true   ===   true    or    true   ===   false )   and   ( false   ===   false    or    false   ===   true ))
   [ [[true, "===", true], "OR", [true, "===", false]], "AND", [[false, "===", false], "OR", [false, "===", true]]]
```


## Extracting Variables

In some cases, the data you want to assert against isn't nicely organized into a single object (yet).
Some of the data may be on a remote resource and require asynchronous functions to gather it.

`extractVariables` allows you to retrieve all variables that would need to be resolved.
It returns an object with keys being each `$.` prefixed rule value found.
If given an object, the values will be populated as found.

By gathering what variables you need, requests can be shipped off to gather the data into an object for use with Operander.
Especially handy if looking to dynamically form GraphQL queries/mutations.

```javascript
import { extractVariables, process } from '@ripp/operander';

const rule = [['$.user.age', '>', 18], 'AND', ['$.user.country', '===', 'US']];

// Get variable names
const vars = extractVariables(rule);
// { 'user.age': null, 'user.country': null }

// Fetch data asynchronously based on required variables
const data = await fetchUserData(Object.keys(vars));

// Now process the rule with complete data
const result = process(rule, data);
```

> Note the keys returned are in period-delimited format.
> Open for feedback if an exploded object makes more sense.

## API Reference

### Core Functions

- **`process(rules, obj, operators?)`** - Process rules against data
- **`evaluate(rule, obj, operators?)`** - Evaluate a single statement
- **`extractVariables(rules, obj?)`** - Extract variable references from rules
- **`resolveVariable(key, obj)`** - Resolve a variable reference
- **`safeGet(obj, path)`** - Safely navigate nested objects

### Operators

- **`OPERATORS`** - Built-in operators (readonly)
- **`createOperators(custom)`** - Create custom operator set
- **`isValidOperator(name)`** - Check if operator exists

### Types

- **`OperanderStatement`** - Single statement type
- **`OperanderStatementSet`** - Statement set with chaining
- **`OperanderChainCmd`** - 'AND' | 'OR'
- **`OperanderResolver`** - Object or resolver function
- **`OperanderOperatorMap`** - Operator map interface