lite-rules
v0.2.0
Published
A simple yet powerful rule engine
Downloads
3
Readme
🌟 lite-rules
A high-performance, lightweight, and extensible JavaScript rule engine library that supports configurable, combinable rule judgment and execution processes.
📦 Installation
npm install lite-rulesOr using pnpm / yarn:
pnpm add lite-rules
yarn add lite-rules🚀 Quick Start
import { Rule, RuleEngine } from 'lite-rules';
const rule1 = new Rule(
'Large Order',
(ctx) => ctx.amount > 1000,
() => 'Offer 9% off'
);
const rule2 = new Rule(
'VIP User',
(ctx) => ctx.isVip === true,
() => 'Give 100 points'
);
const engine = new RuleEngine();
engine.addRule(rule1);
engine.addRule(rule2);
const result = engine.run({ amount: 1200, isVip: true });
console.log(result);
/*
[
{ name: 'Large Order', result: 'Offer 9% off' },
{ name: 'VIP User', result: 'Give 100 points' }
]
*/🔄 Loading Rules from JSON (v0.2.0+)
You can now load rules from JSON configuration:
import { RuleEngine, loadRulesFromJson } from 'lite-rules';
// Define rules in configuration
const ruleConfigs = [
{
name: "Large Order",
condition: "context.amount > 1000",
action: "'Offer 9% off'"
},
{
name: "VIP User",
condition: "context.isVip === true",
action: "'Give 100 points'"
}
];
// Load rules from configuration
const rules = loadRulesFromJson(ruleConfigs);
// Create engine and add rules
const engine = new RuleEngine();
rules.forEach(rule => engine.addRule(rule));
// Run the engine with context
const result = engine.run({ amount: 1200, isVip: true });
console.log(result);You can also load rules directly from a JSON file:
import { RuleEngine, loadRulesFromFile } from 'lite-rules';
async function main() {
// Load rules from a JSON file
const rules = await loadRulesFromFile('./rules.json');
const engine = new RuleEngine();
rules.forEach(rule => engine.addRule(rule));
const result = engine.run({ amount: 1200, isVip: true });
console.log(result);
}
main().catch(console.error);🔒 Security Features (v0.2.0+)
lite-rules includes robust security features to prevent malicious code injection:
Syntax Validation
import { validateExpression } from 'lite-rules';
const result = validateExpression('context.amount > 1000');
if (result.valid) {
console.log('Expression syntax is valid');
} else {
console.error('Syntax error:', result.error);
}Safety Checks
import { checkSafeExpression } from 'lite-rules';
const result = checkSafeExpression('Math.max(a, b)');
if (result.safe) {
console.log('Expression is safe');
} else {
console.error('Security risk:', result.reason);
}Sandbox Environment
Rules are executed in a restricted sandbox environment that only allows access to whitelisted objects:
import { allowedGlobals } from 'lite-rules';
// View allowed objects and functions
console.log(Object.keys(allowedGlobals));Skipping Safety Checks
In trusted environments, you can skip safety checks for better performance:
import { loadRulesFromJson } from 'lite-rules';
const rules = loadRulesFromJson(configs, { skipSafetyChecks: true });🧱 API Documentation
Rule
Represents a rule, consisting of three parts:
new Rule(
name: string,
condition: (context) => boolean,
action: (context) => any
)name:Rule namecondition:Condition function, returns a boolean valueaction:Function executed when the condition is true, returns the result
RuleEngine
The core engine, supporting the addition of rules and execution.
addRule(rule: Rule): void
Registers a rule.
run(context: Record<string, any>): RuleResult[]
Runs all rules on the input data, returning the list of all successful matches.
loadRulesFromJson(configs: RuleConfig[], options?: LoadOptions): Rule[]
Loads rules from JSON configuration objects.
loadRulesFromFile(filePath: string): Promise<Rule[]>
Loads rules from a JSON file.
✅ Feature Overview
- 🧠 Rules as functions, clear logic
- 📦 Modular design, easy to extend
- 📄 Supports configurable rules from JSON
- 🔒 Built-in security features
- ⚙️ Can be integrated with mid-backend configuration platforms
- 🧪 Supports unit testing and custom plugin mechanisms
📚 Example Scenarios
- E-commerce marketing rule matching (e.g., full reduction, VIP)
- Form field validation system
- Approval workflow judgment
- User label hit strategy
- Risk control rule filter
🛣️ Development Plan
| Version | Functionality | |------|------| | ✅ v0.1 | Supports JS functional rule execution | | ✅ v0.2 | Supports JSON rule configuration loading and security features | | ⏳ v0.3 | Conditional expression DSL support | | ⏳ v0.4 | Rule grouping, priority, and disable | | ⏳ v0.5 | Plugin mechanism and asynchronous rules |
🧑💻 Development and Building
pnpm build # Build the project
pnpm test # Run unit tests
pnpm example # Run the example📄 License
❤️ To Developers
This project aims to provide a lightweight but scalable rule system framework, suitable for use in mid-backend business systems, automation control, and visual rule configuration platforms. Welcome to Star, Issue, and PR!
