Skip to content

Latest commit

 

History

History
617 lines (460 loc) · 10.5 KB

api-reference.md

File metadata and controls

617 lines (460 loc) · 10.5 KB

API Reference

Complete API documentation for @usex/rule-engine.

Table of Contents

RuleEngine Class

The main class for rule evaluation and management.

Constructor

new RuleEngine(options?: RuleEngineOptions)

Options

Property Type Default Description
logger Logger console Custom logger implementation
cache boolean true Enable/disable mutation caching
mutations Map<string, MutationFunction> new Map() Initial mutations

Instance Methods

evaluate

Evaluates a rule against criteria.

async evaluate<R = any>(
  rule: RuleType<R>,
  criteria: any | any[],
  trustRule?: boolean
): Promise<EvaluationResult<R> | EvaluationResult<R>[]>

Parameters:

  • rule: The rule to evaluate
  • criteria: Single object or array of objects to evaluate against
  • trustRule: Skip rule validation if true (default: false)

Returns:

  • Single EvaluationResult for single criteria
  • Array of EvaluationResult for array criteria

Example:

const engine = new RuleEngine();
const result = await engine.evaluate(rule, { age: 25 });
// { value: true, isPassed: true }

checkIsPassed

Simple boolean check if rule passes.

async checkIsPassed(
  rule: RuleType<any>,
  criteria: any | any[],
  trustRule?: boolean
): Promise<boolean>

Parameters:

  • Same as evaluate

Returns:

  • true if rule passes, false otherwise

Example:

const passed = await engine.checkIsPassed(rule, { age: 25 });
// true

getEvaluateResult

Get only result values without evaluation metadata.

async getEvaluateResult<R = any>(
  rule: RuleType<R>,
  criteria: any | any[],
  trustRule?: boolean
): Promise<R | R[]>

Parameters:

  • Same as evaluate

Returns:

  • Result value(s) only, without isPassed flag

Example:

const result = await engine.getEvaluateResult(rule, data);
// { discount: 0.15, message: "15% off" }

evaluateMany

Evaluate multiple rules against same criteria.

async evaluateMany<R = any>(
  rules: RuleType<R>[],
  criteria: any,
  trustRule?: boolean
): Promise<EvaluationResult<R>[]>

Parameters:

  • rules: Array of rules to evaluate
  • criteria: Single criteria object
  • trustRule: Skip validation for all rules

Returns:

  • Array of evaluation results

Example:

const results = await engine.evaluateMany([rule1, rule2], data);
// [{ value: true, isPassed: true }, { value: false, isPassed: false }]

validate

Validates rule structure.

validate(rule: RuleType<any>): ValidationResult

Parameters:

  • rule: Rule to validate

Returns:

interface ValidationResult {
  isValid: boolean;
  error?: {
    message: string;
    path?: string;
    details?: any;
  };
}

Example:

const validation = engine.validate(rule);
if (!validation.isValid) {
  console.error(validation.error.message);
}

introspect

Analyzes rule for possible input ranges.

introspect(rule: RuleType<any>): IntrospectionResult

Parameters:

  • rule: Rule to analyze

Returns:

interface IntrospectionResult {
  possibleCriteria: any[];
  fields: string[];
  operators: string[];
  constraints: ConstraintInfo[];
}

Example:

const analysis = engine.introspect(rule);
console.log(analysis.fields); // ["age", "country"]

builder

Get a new rule builder instance.

builder(): RuleBuilder

Returns:

  • New RuleBuilder instance

Example:

const builder = engine.builder();
const rule = builder
  .add({ and: [...] })
  .default({ value: false })
  .build();

Mutation Methods

addMutation

Add a criteria preprocessor.

addMutation(name: string, fn: MutationFunction): void

Parameters:

  • name: Unique mutation name
  • fn: Function that transforms criteria

Example:

engine.addMutation('normalize', (criteria) => {
  if (criteria.email) {
    criteria.email = criteria.email.toLowerCase();
  }
  return criteria;
});

removeMutation

Remove a mutation by name.

removeMutation(name: string): boolean

Parameters:

  • name: Mutation name to remove

Returns:

  • true if removed, false if not found

clearMutationCache

Clear mutation result cache.

clearMutationCache(name?: string): void

Parameters:

  • name: Optional specific mutation to clear (clears all if omitted)

Static Methods

All instance methods are available as static methods on the RuleEngine class:

RuleEngine.evaluate(rule, criteria, trustRule?)
RuleEngine.checkIsPassed(rule, criteria, trustRule?)
RuleEngine.getEvaluateResult(rule, criteria, trustRule?)
RuleEngine.evaluateMany(rules, criteria, trustRule?)
RuleEngine.validate(rule)
RuleEngine.introspect(rule)
RuleEngine.builder()

ObjectDiscovery Service

Utilities for working with objects and JSONPath expressions.

resolveProperty

Resolves a property value from an object using path or JSONPath.

static resolveProperty(
  path: string,
  json: any
): any

Parameters:

  • path: Property path or JSONPath expression
  • json: Object to resolve from

Returns:

  • Resolved value or undefined

Example:

const value = ObjectDiscovery.resolveProperty("$.user.profile.age", data);
// 25

updateProperty

Updates a property value in an object.

static updateProperty(
  path: string,
  json: any,
  value: any
): void

Parameters:

  • path: Property path or JSONPath expression
  • json: Object to update
  • value: New value to set

Example:

ObjectDiscovery.updateProperty("$.user.age", data, 26);

resolveTextPathExpressions

Resolves JSONPath expressions in template strings.

static resolveTextPathExpressions(
  text: string,
  criteria: any
): string

Parameters:

  • text: Template string with JSONPath expressions
  • criteria: Data object for resolution

Returns:

  • Resolved string

Example:

const result = ObjectDiscovery.resolveTextPathExpressions(
  "Hello $.user.name, you have $.points points",
  { user: { name: "John" }, points: 100 }
);
// "Hello John, you have 100 points"

Type Guards

isCondition

Check if object is a valid condition.

static isCondition(obj: any): obj is Condition

Example:

if (ObjectDiscovery.isCondition(obj)) {
  // obj is typed as Condition
}

isConstraint

Check if object is a valid constraint.

static isConstraint(obj: any): obj is Constraint

Example:

if (ObjectDiscovery.isConstraint(obj)) {
  // obj is typed as Constraint
}

isGranular

Check if rule has result values.

static isGranular(rule: RuleType<any>): boolean

Example:

if (ObjectDiscovery.isGranular(rule)) {
  // Rule has result values in conditions
}

Builder API

Fluent API for constructing rules programmatically.

Methods

add

Add a condition to the rule.

add(condition: Condition<R>): RuleBuilder<R>

Example:

builder.add({
  and: [
    { field: "age", operator: "greater-than", value: 18 }
  ],
  result: { allowed: true }
})

default

Set default result.

default(result: R): RuleBuilder<R>

Example:

builder.default({ allowed: false })

build

Build the final rule.

build(validate?: boolean): RuleType<R>

Parameters:

  • validate: Validate rule before returning (default: false)

Returns:

  • Complete rule object

Example:

const rule = builder.build(true); // Validates before returning

Complete Example

const rule = RuleEngine.builder()
  .add({
    and: [
      { field: "age", operator: "greater-than", value: 21 },
      { field: "country", operator: "equals", value: "US" }
    ],
    result: { canDrink: true }
  })
  .add({
    and: [
      { field: "age", operator: "greater-than", value: 18 },
      { field: "country", operator: "not-equals", value: "US" }
    ],
    result: { canDrink: true }
  })
  .default({ canDrink: false })
  .build(true);

Types & Interfaces

RuleType

Main rule structure.

interface RuleType<R = any> {
  conditions: Condition<R> | Condition<R>[];
  default?: R;
}

Condition

Logical grouping of constraints.

interface Condition<R = any> {
  or?: Array<Constraint | Condition<R>>;
  and?: Array<Constraint | Condition<R>>;
  none?: Array<Constraint | Condition<R>>;
  result?: R;
}

Constraint

Basic evaluation unit.

interface Constraint {
  field: string;
  operator: string;
  value: any;
  message?: string;
}

EvaluationResult

Result of rule evaluation.

interface EvaluationResult<T = any> {
  value: T;
  isPassed: boolean;
  message?: string;
}

ValidationResult

Result of rule validation.

interface ValidationResult {
  isValid: boolean;
  error?: {
    message: string;
    path?: string;
    details?: any;
  };
}

IntrospectionResult

Result of rule introspection.

interface IntrospectionResult {
  possibleCriteria: any[];
  fields: string[];
  operators: string[];
  constraints: Array<{
    field: string;
    operator: string;
    value: any;
    path: string;
  }>;
}

Enums

ConditionType

enum ConditionType {
  Or = "or",
  And = "and",
  None = "none"
}

Operators

See Operators Documentation for complete list.

Utilities

Error Handling

class RuleEngineError extends Error {
  constructor(message: string, public code?: string, public details?: any)
}

Date Utilities

// Parse various date formats
parseDate(value: any): Date

// Format date to ISO string
formatDate(date: Date): string

// Check if valid date
isValidDate(value: any): boolean

Type Checking

// Check if value is object
isObject(value: any): boolean

// Check if value is empty
isEmpty(value: any): boolean

// Deep clone object
deepClone<T>(obj: T): T

For more information, see the main documentation.