nestjs-business-engine 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Kamil Mysliwiec
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,277 @@
1
+ # nestjs-business-engine
2
+
3
+ [![npm version](https://img.shields.io/npm/v/nestjs-business-engine)](https://www.npmjs.com/package/nestjs-business-engine)
4
+ [![CI](https://github.com/pedrosodre/nestjs-business-engine/actions/workflows/release.yml/badge.svg)](https://github.com/pedrosodre/nestjs-business-engine/actions/workflows/release.yml)
5
+ [![license](https://img.shields.io/npm/l/nestjs-business-engine)](LICENSE)
6
+ [![downloads](https://img.shields.io/npm/dm/nestjs-business-engine)](https://www.npmjs.com/package/nestjs-business-engine)
7
+
8
+ Business rules engine for [NestJS](https://nestjs.com). Rules are plain data (JSON you can store in a database or edit in an admin UI): each rule **transforms** the payload with [JSONata](https://jsonata.org), checks a MongoDB-style **condition** with [sift](https://github.com/crcn/sift.js), and **produces** a result.
9
+
10
+ ```ts
11
+ const { results } = await engine.run(rules, order);
12
+ // { 'vip-discount': 12.5, 'free-shipping': true }
13
+ ```
14
+
15
+ - Rules as data: no code deploys to change a discount, a fee or an eligibility check.
16
+ - Safe for rules you don't fully trust: no JavaScript execution, formula timeouts and prototype-pollution checks.
17
+ - Validation for rule editors (`validateRules()`, also a [Standard Schema](https://standardschema.dev)).
18
+ - Custom functions, per-run options, module-wide defaults, a debug trace and typed errors.
19
+ - CommonJS and ESM, typed, no dependencies besides JSONata and sift.
20
+
21
+ ## Compatibility
22
+
23
+ | nestjs-business-engine | Node.js | NestJS | TypeScript (for consumers) |
24
+ | ---------------------- | ---------- | ---------- | -------------------------- |
25
+ | 1.x | >= 22.12.0 | 11.x, 12.x | >= 5.0 |
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ npm install nestjs-business-engine
31
+ ```
32
+
33
+ `@nestjs/common` and `reflect-metadata` are peer dependencies (every Nest application already has them).
34
+
35
+ ## Getting started
36
+
37
+ Import the module:
38
+
39
+ ```ts
40
+ import { Module } from '@nestjs/common';
41
+ import { BusinessEngineModule } from 'nestjs-business-engine';
42
+
43
+ @Module({
44
+ imports: [BusinessEngineModule],
45
+ })
46
+ export class AppModule {}
47
+ ```
48
+
49
+ Inject `BusinessEngineService` and run rules against a payload:
50
+
51
+ ```ts
52
+ import { Injectable } from '@nestjs/common';
53
+ import { BusinessEngineService, Rule } from 'nestjs-business-engine';
54
+
55
+ const rules: Rule[] = [
56
+ {
57
+ id: 'vip-discount',
58
+ group: 'pricing',
59
+ transform: [{ key: 'total', formula: '$sum(items.(price * quantity))' }],
60
+ when: { total: { $gte: 100 }, 'customer.tier': 'vip' },
61
+ produce: { default: 0, formula: '$round(total * 0.1, 2)' },
62
+ },
63
+ {
64
+ id: 'free-shipping',
65
+ group: 'shipping',
66
+ when: { 'address.country': { $in: ['PT', 'ES'] } },
67
+ produce: { default: false, formula: 'true' },
68
+ },
69
+ ];
70
+
71
+ @Injectable()
72
+ export class CheckoutService {
73
+ constructor(private readonly engine: BusinessEngineService) {}
74
+
75
+ async quote(order: Record<string, unknown>) {
76
+ const { results } = await this.engine.run(rules, order);
77
+ return results; // { 'vip-discount': 12.5, 'free-shipping': true }
78
+ }
79
+ }
80
+ ```
81
+
82
+ In a real application, rules usually come from a database. Validate them when they are saved (see [Validating rules](#validating-rules)).
83
+
84
+ ## How a rule works
85
+
86
+ Every rule runs independently against a copy of the payload, in three steps:
87
+
88
+ 1. **`transform`** (optional): a list of `{ key, formula }`. Each JSONata formula is evaluated against the payload and its value is stored under `key`. Later transforms can use earlier ones.
89
+ 2. **`when`** (optional): a MongoDB-style query (`$gt`, `$in`, `$elemMatch`, `$and`, `$regex`, dot paths, ...) tested against the transformed payload. A missing `when` always matches.
90
+ 3. **`produce`**: if the condition matches, the JSONata `formula` is evaluated and becomes the rule's result. Otherwise (or when the formula yields nothing) the result is `default`.
91
+
92
+ | Field | Type | Required | Description |
93
+ | ----------------- | ------------------------------------ | -------- | -------------------------------------------------------------- |
94
+ | `id` | `string` | yes | Unique id. Results are keyed by it. |
95
+ | `group` | `string` | no | Used to run a subset of rules with the `group` option. |
96
+ | `enabled` | `boolean` | no | `false` skips the rule. Defaults to `true`. |
97
+ | `transform` | `{ key: string; formula: string }[]` | no | Derived values, computed in order. |
98
+ | `when` | `object` | no | MongoDB-style condition. Defaults to `{}` (always matches). |
99
+ | `produce.formula` | `string` | yes | JSONata expression that computes the result. |
100
+ | `produce.default` | `unknown` | no | Result when the condition fails or the formula yields nothing. |
101
+
102
+ Rules never see each other's results. To chain decisions, run the engine again with the results merged into the payload.
103
+
104
+ ## Running rules
105
+
106
+ ```ts
107
+ const { executionId, results, matched, errors, debug } = await engine.run(
108
+ rules,
109
+ payload,
110
+ {
111
+ group: 'pricing',
112
+ bindings: { vat: 0.23 },
113
+ timeout: 100,
114
+ continueOnError: true,
115
+ debug: true,
116
+ },
117
+ );
118
+ ```
119
+
120
+ ### Options
121
+
122
+ | Option | Type | Default | Description |
123
+ | ----------------- | ------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
124
+ | `group` | `string \| string[]` | - | Only run rules of this group (or these groups). |
125
+ | `bindings` | `Record<string, unknown>` | `{}` | Variables and functions available to every formula as `$name`. Merged over module bindings. |
126
+ | `timeout` | `number` (ms) | none | Maximum duration of each formula. A slower formula fails with code `TIMEOUT`. `0` means no limit; a value that is not a non-negative number makes `run()` throw a `TypeError`. See [Security](#security) for its limits. |
127
+ | `continueOnError` | `boolean` | `false` | A failing rule keeps its default and its error goes to `errors` instead of rejecting the whole run. |
128
+ | `debug` | `boolean` | `false` | Return a step-by-step trace in `debug`. |
129
+
130
+ ### Result
131
+
132
+ | Field | Type | Description |
133
+ | ------------- | ------------------------- | --------------------------------------------------- |
134
+ | `executionId` | `string` | Unique id (UUID) of this run. |
135
+ | `results` | `Record<string, unknown>` | Result of every rule that ran, keyed by rule id. |
136
+ | `matched` | `string[]` | Ids of the rules whose condition matched, in order. |
137
+ | `errors` | `RuleEvaluationError[]` | Failed rules (only filled with `continueOnError`). |
138
+ | `debug` | `DebugStep[]` | Only with `debug: true`. |
139
+
140
+ Type the results with a generic:
141
+
142
+ ```ts
143
+ const { results } = await engine.run<{ 'vip-discount': number }>(rules, order);
144
+ results['vip-discount'].toFixed(2);
145
+ ```
146
+
147
+ ### Custom functions
148
+
149
+ Bindings make your own code available to formulas. Functions can be async:
150
+
151
+ ```ts
152
+ await engine.run(rules, order, {
153
+ bindings: {
154
+ vat: 0.23,
155
+ fx: async (currency: string) => rates.get(currency),
156
+ },
157
+ });
158
+ // formula: '$round(total * (1 + $vat) * $fx(currency), 2)'
159
+ ```
160
+
161
+ JSONata's [built-in functions](https://docs.jsonata.org/overview) (`$sum`, `$round`, `$map`, `$filter`, `$now`, ...) are always available.
162
+
163
+ ## Module configuration
164
+
165
+ Use `forRoot()` to set defaults for every run. Per-run options override them.
166
+
167
+ ```ts
168
+ BusinessEngineModule.forRoot({
169
+ isGlobal: true,
170
+ bindings: { vat: 0.23 },
171
+ timeout: 100,
172
+ continueOnError: false,
173
+ cacheSize: 500,
174
+ });
175
+ ```
176
+
177
+ Or `forRootAsync()` to build them from other providers:
178
+
179
+ ```ts
180
+ BusinessEngineModule.forRootAsync({
181
+ isGlobal: true,
182
+ imports: [RatesModule],
183
+ inject: [RatesService],
184
+ useFactory: (rates: RatesService) => ({
185
+ bindings: { fx: (currency: string) => rates.get(currency) },
186
+ timeout: 100,
187
+ }),
188
+ });
189
+ ```
190
+
191
+ | Option | Type | Default | Description |
192
+ | ----------------- | ------------------------- | ------- | ------------------------------------------------------------------------------------------- |
193
+ | `isGlobal` | `boolean` | `false` | Register the module globally. |
194
+ | `bindings` | `Record<string, unknown>` | `{}` | Default bindings for every run. |
195
+ | `timeout` | `number` (ms) | none | Default `timeout`. |
196
+ | `continueOnError` | `boolean` | `false` | Default `continueOnError`. |
197
+ | `cacheSize` | `number` | `500` | Compiled formulas kept in memory (least recently used are evicted). `0` disables the cache. |
198
+
199
+ Outside Nest, `new BusinessEngineService()` works too.
200
+
201
+ ## Validating rules
202
+
203
+ Check rules when they are created or edited, before they reach `run()`:
204
+
205
+ ```ts
206
+ import { validateRules } from 'nestjs-business-engine';
207
+
208
+ const issues = validateRules(input);
209
+ // [{ ruleId: 'vip', path: [0, 'produce', 'formula'], message: 'Rule "vip": produce formula is invalid at position 5: ...' }]
210
+ ```
211
+
212
+ It reports structural problems, missing or duplicate ids, forbidden keys, JSONata syntax errors and unsupported operators. `rulesSchema` exposes the same checks as a [Standard Schema](https://standardschema.dev), so it works with any library that accepts one:
213
+
214
+ ```ts
215
+ import { rulesSchema } from 'nestjs-business-engine';
216
+
217
+ const result = await rulesSchema['~standard'].validate(input);
218
+ if (result.issues) throw new BadRequestException(result.issues);
219
+ ```
220
+
221
+ `run()` always checks the structure of the rules and rejects with an `InvalidRuleError` before evaluating anything.
222
+
223
+ ## Errors
224
+
225
+ All errors extend `BusinessEngineError`:
226
+
227
+ | Error | When | Useful fields |
228
+ | --------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
229
+ | `InvalidRuleError` | Malformed or unsafe rules (before anything runs). | `issues`, `ruleId` |
230
+ | `RuleEvaluationError` | A formula or condition failed while running. | `ruleId`, `stage` (`transform`/`when`/`produce`), `key`, `code`, `position`, `cause` |
231
+ | `FormulaTimeoutError` | The `cause` of a `RuleEvaluationError` when a formula exceeded `timeout` (`code: 'TIMEOUT'`). | `timeout` |
232
+
233
+ ```ts
234
+ try {
235
+ await engine.run(rules, payload);
236
+ } catch (error) {
237
+ if (error instanceof RuleEvaluationError) {
238
+ logger.warn(`Rule ${error.ruleId} failed at ${error.stage}: ${error.code}`);
239
+ }
240
+ throw error;
241
+ }
242
+ ```
243
+
244
+ ## Security
245
+
246
+ Rules are data that may be written by people who should not be able to run code on your servers. The engine is designed for that:
247
+
248
+ - **No JavaScript execution.** JSONata is a sandboxed expression language, and sift's `$where` operator (which compiles strings with `new Function`) is disabled.
249
+ - **Formula timeouts.** JSONata optimizes tail calls, so a recursive formula can run forever. Set `timeout` when rules come from outside your code. The timeout is checked between the steps of a formula, so it cannot interrupt a single slow operation: a regular expression with catastrophic backtracking (in a formula or a `$regex` condition, which is not time-limited at all) or `$sort` on a very large array runs to completion and blocks the event loop meanwhile. If rule authors are not trusted, also run the engine where you can stop it, for example in a worker thread or a separate process with its own time limit.
250
+ - **Prototype pollution.** `__proto__`, `constructor` and `prototype` are rejected as rule ids and transform keys.
251
+ - **No changes to your objects.** JSONata's transform operator copies objects with `$clone`, so formulas cannot redefine `$clone` (which would let them modify your payload or bindings) or use `$eval` (whose formula cannot be checked in advance). Such formulas fail with code `UNSAFE_FORMULA` and are reported by `validateRules()`.
252
+ - **Bindings are trusted code.** Only expose functions you would let rule authors call.
253
+
254
+ Report vulnerabilities privately, see [SECURITY.md](SECURITY.md).
255
+
256
+ ## Debugging
257
+
258
+ With `debug: true`, `run()` returns every step with its context (rules, payloads, condition outcome and result):
259
+
260
+ ```ts
261
+ const { debug } = await engine.run(rules, payload, { debug: true });
262
+ // [{ message: 'Starting the business engine', context: { ... } }, { message: 'Running a single rule', ... }, ...]
263
+ ```
264
+
265
+ The trace contains payload values. Don't log it in production if payloads are sensitive.
266
+
267
+ ## AI assistants
268
+
269
+ The package ships an [`llms.txt`](llms.txt) with a compact API summary for AI coding assistants (`node_modules/nestjs-business-engine/llms.txt`).
270
+
271
+ ## Contributing
272
+
273
+ Contributions are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT.md). Release notes are on the [GitHub releases page](https://github.com/pedrosodre/nestjs-business-engine/releases).
274
+
275
+ ## License
276
+
277
+ [MIT](LICENSE) © Pedro Sodré
@@ -0,0 +1,10 @@
1
+ import { DynamicModule } from '@nestjs/common';
2
+ import { BusinessEngineModuleAsyncOptions, BusinessEngineModuleOptions } from './business-engine.options';
3
+ /**
4
+ * Provides `BusinessEngineService`. Import it as is for the defaults, or with
5
+ * `forRoot()` / `forRootAsync()` to configure every run.
6
+ */
7
+ export declare class BusinessEngineModule {
8
+ static forRoot(options?: BusinessEngineModuleOptions): DynamicModule;
9
+ static forRootAsync(options: BusinessEngineModuleAsyncOptions): DynamicModule;
10
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var BusinessEngineModule_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.BusinessEngineModule = void 0;
11
+ const common_1 = require("@nestjs/common");
12
+ const business_engine_options_1 = require("./business-engine.options");
13
+ const business_engine_service_1 = require("./business-engine.service");
14
+ /**
15
+ * Provides `BusinessEngineService`. Import it as is for the defaults, or with
16
+ * `forRoot()` / `forRootAsync()` to configure every run.
17
+ */
18
+ let BusinessEngineModule = BusinessEngineModule_1 = class BusinessEngineModule {
19
+ static forRoot(options = {}) {
20
+ const { isGlobal, ...engineOptions } = options;
21
+ return {
22
+ module: BusinessEngineModule_1,
23
+ global: isGlobal,
24
+ providers: [
25
+ { provide: business_engine_options_1.BUSINESS_ENGINE_OPTIONS, useValue: engineOptions },
26
+ business_engine_service_1.BusinessEngineService,
27
+ ],
28
+ exports: [business_engine_service_1.BusinessEngineService],
29
+ };
30
+ }
31
+ static forRootAsync(options) {
32
+ return {
33
+ module: BusinessEngineModule_1,
34
+ global: options.isGlobal,
35
+ imports: options.imports ?? [],
36
+ providers: [
37
+ {
38
+ provide: business_engine_options_1.BUSINESS_ENGINE_OPTIONS,
39
+ useFactory: options.useFactory,
40
+ inject: options.inject ?? [],
41
+ },
42
+ business_engine_service_1.BusinessEngineService,
43
+ ],
44
+ exports: [business_engine_service_1.BusinessEngineService],
45
+ };
46
+ }
47
+ };
48
+ exports.BusinessEngineModule = BusinessEngineModule;
49
+ exports.BusinessEngineModule = BusinessEngineModule = BusinessEngineModule_1 = __decorate([
50
+ (0, common_1.Module)({
51
+ providers: [business_engine_service_1.BusinessEngineService],
52
+ exports: [business_engine_service_1.BusinessEngineService],
53
+ })
54
+ ], BusinessEngineModule);
@@ -0,0 +1,31 @@
1
+ import type { InjectionToken, ModuleMetadata, OptionalFactoryDependency } from '@nestjs/common';
2
+ /** Injection token of the module options. */
3
+ export declare const BUSINESS_ENGINE_OPTIONS = "BUSINESS_ENGINE_OPTIONS";
4
+ /** Defaults applied to every `run()` of the service. */
5
+ export interface BusinessEngineOptions {
6
+ /**
7
+ * Variables and functions available to every formula as `$name`. Merged
8
+ * with (and overridden by) `RunOptions.bindings`.
9
+ */
10
+ bindings?: Record<string, unknown>;
11
+ /** Default `RunOptions.timeout`, in milliseconds. */
12
+ timeout?: number;
13
+ /** Default `RunOptions.continueOnError`. */
14
+ continueOnError?: boolean;
15
+ /** Number of compiled formulas kept in memory (LRU). `0` disables the cache. Defaults to 500. */
16
+ cacheSize?: number;
17
+ }
18
+ /** Options of `BusinessEngineModule.forRoot()`. */
19
+ export interface BusinessEngineModuleOptions extends BusinessEngineOptions {
20
+ /** Register the module globally. Defaults to `false`. */
21
+ isGlobal?: boolean;
22
+ }
23
+ /** Options of `BusinessEngineModule.forRootAsync()`. */
24
+ export interface BusinessEngineModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
25
+ /** Register the module globally. Defaults to `false`. */
26
+ isGlobal?: boolean;
27
+ /** Providers injected into `useFactory`. */
28
+ inject?: Array<InjectionToken | OptionalFactoryDependency>;
29
+ /** Returns the options, possibly asynchronously. */
30
+ useFactory: (...args: any[]) => BusinessEngineOptions | Promise<BusinessEngineOptions>;
31
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BUSINESS_ENGINE_OPTIONS = void 0;
4
+ /** Injection token of the module options. */
5
+ exports.BUSINESS_ENGINE_OPTIONS = 'BUSINESS_ENGINE_OPTIONS';
@@ -0,0 +1,23 @@
1
+ import { BusinessEngineOptions } from './business-engine.options';
2
+ import { Rule, RunOptions, RunResult } from './types';
3
+ import { RuleIssue } from './validation';
4
+ export declare class BusinessEngineService {
5
+ private readonly defaults;
6
+ private readonly formulas;
7
+ constructor(defaults?: BusinessEngineOptions);
8
+ /**
9
+ * Runs the rules against a payload, in order, and returns the result of
10
+ * each rule keyed by its id. Rules never see each other's results.
11
+ */
12
+ run<TResults extends Record<string, unknown> = Record<string, unknown>>(rules: readonly Rule[], initialPayload: Record<string, unknown>, runOptions?: RunOptions): Promise<RunResult<TResults>>;
13
+ /**
14
+ * Checks rules without running them. Same as the standalone
15
+ * `validateRules()`; returns an empty array when the rules are valid.
16
+ */
17
+ validate(rules: unknown): RuleIssue[];
18
+ private runRule;
19
+ private step;
20
+ private transform;
21
+ private evaluate;
22
+ private produce;
23
+ }
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.BusinessEngineService = void 0;
19
+ const common_1 = require("@nestjs/common");
20
+ const node_crypto_1 = require("node:crypto");
21
+ const sift_1 = __importDefault(require("sift"));
22
+ const business_engine_options_1 = require("./business-engine.options");
23
+ const errors_1 = require("./errors");
24
+ const formula_util_1 = require("./util/formula.util");
25
+ const normalize_util_1 = require("./util/normalize.util");
26
+ const validation_1 = require("./validation");
27
+ /**
28
+ * sift compiles string `$where` conditions with `new Function`, which would let
29
+ * anyone who can write a rule run arbitrary code. Rules are data (often stored
30
+ * in a database), so the operator is disabled.
31
+ */
32
+ const SAFE_SIFT_OPERATIONS = {
33
+ $where: () => {
34
+ throw new Error('The $where operator is not supported in rule conditions');
35
+ },
36
+ };
37
+ /**
38
+ * Copies a rule's default so callers that mutate a result do not change the
39
+ * rule itself. Values that cannot be cloned (functions, class instances with
40
+ * private state) are returned as is.
41
+ */
42
+ function cloneDefault(value) {
43
+ if (value === null || typeof value !== 'object') {
44
+ return value;
45
+ }
46
+ try {
47
+ return structuredClone(value);
48
+ }
49
+ catch {
50
+ return value;
51
+ }
52
+ }
53
+ let BusinessEngineService = class BusinessEngineService {
54
+ defaults;
55
+ formulas;
56
+ constructor(defaults = {}) {
57
+ this.defaults = defaults;
58
+ this.formulas = new formula_util_1.FormulaCache(defaults.cacheSize);
59
+ }
60
+ /**
61
+ * Runs the rules against a payload, in order, and returns the result of
62
+ * each rule keyed by its id. Rules never see each other's results.
63
+ */
64
+ async run(rules, initialPayload, runOptions = {}) {
65
+ const options = {
66
+ ...runOptions,
67
+ timeout: runOptions.timeout ?? this.defaults.timeout,
68
+ continueOnError: runOptions.continueOnError ?? this.defaults.continueOnError,
69
+ bindings: { ...this.defaults.bindings, ...runOptions.bindings },
70
+ };
71
+ const { timeout } = options;
72
+ if (timeout !== undefined &&
73
+ (typeof timeout !== 'number' || !Number.isFinite(timeout) || timeout < 0)) {
74
+ // A string such as '100' (from an environment variable, say) would
75
+ // otherwise silently disable the timeout.
76
+ throw new TypeError(`timeout must be a non-negative number of milliseconds, got ${String(timeout)}`);
77
+ }
78
+ const issues = (0, validation_1.checkRules)(rules, { deep: false });
79
+ if (issues.length > 0) {
80
+ throw new errors_1.InvalidRuleError(issues);
81
+ }
82
+ const executionId = (0, node_crypto_1.randomUUID)();
83
+ const context = {
84
+ trace: options.debug ? [] : undefined,
85
+ bindings: options.bindings,
86
+ timeout: options.timeout,
87
+ };
88
+ const groups = options.group === undefined
89
+ ? undefined
90
+ : new Set(typeof options.group === 'string' ? [options.group] : options.group);
91
+ this.step(context, 'Starting the business engine', {
92
+ rules,
93
+ initialPayload,
94
+ });
95
+ const results = {};
96
+ const matched = [];
97
+ const errors = [];
98
+ for (const rule of rules) {
99
+ if (rule.enabled === false || (groups && !groups.has(rule.group))) {
100
+ continue;
101
+ }
102
+ this.step(context, 'Running a single rule', {
103
+ ruleId: rule.id,
104
+ rule,
105
+ });
106
+ results[rule.id] = cloneDefault(rule.produce.default);
107
+ try {
108
+ const outcome = await this.runRule(rule, initialPayload, context);
109
+ if (outcome.matched) {
110
+ matched.push(rule.id);
111
+ // JSONata returns undefined when a path matches nothing.
112
+ if (outcome.result !== undefined) {
113
+ results[rule.id] = outcome.result;
114
+ }
115
+ }
116
+ }
117
+ catch (error) {
118
+ if (!options.continueOnError ||
119
+ !(error instanceof errors_1.RuleEvaluationError)) {
120
+ throw error;
121
+ }
122
+ errors.push(error);
123
+ this.step(context, 'Rule failed, keeping its default', {
124
+ ruleId: rule.id,
125
+ error: error.message,
126
+ });
127
+ }
128
+ }
129
+ this.step(context, 'Returning all results', {
130
+ results,
131
+ executionId,
132
+ });
133
+ const output = {
134
+ executionId,
135
+ results: results,
136
+ matched,
137
+ errors,
138
+ };
139
+ if (context.trace) {
140
+ output.debug = context.trace;
141
+ }
142
+ return output;
143
+ }
144
+ /**
145
+ * Checks rules without running them. Same as the standalone
146
+ * `validateRules()`; returns an empty array when the rules are valid.
147
+ */
148
+ validate(rules) {
149
+ return (0, validation_1.validateRules)(rules);
150
+ }
151
+ async runRule(rule, initialPayload, context) {
152
+ const payload = await this.transform(rule, initialPayload, context);
153
+ if (!this.evaluate(rule, payload, context)) {
154
+ return { matched: false };
155
+ }
156
+ return {
157
+ matched: true,
158
+ result: await this.produce(rule, payload, context),
159
+ };
160
+ }
161
+ step(context, message, data) {
162
+ context.trace?.push({ message, context: data });
163
+ }
164
+ async transform(rule, initialPayload, context) {
165
+ const payload = { ...initialPayload };
166
+ for (const transform of rule.transform ?? []) {
167
+ try {
168
+ payload[transform.key] = (0, normalize_util_1.toPlainValue)(await this.formulas.evaluate(transform.formula, payload, context));
169
+ }
170
+ catch (error) {
171
+ throw new errors_1.RuleEvaluationError(rule.id, 'transform', error, transform.key);
172
+ }
173
+ }
174
+ this.step(context, 'Transforming initial payload', {
175
+ ruleId: rule.id,
176
+ transform: rule.transform,
177
+ initialPayload,
178
+ payload,
179
+ });
180
+ return payload;
181
+ }
182
+ evaluate(rule, payload, context) {
183
+ let shouldProduce;
184
+ try {
185
+ shouldProduce = (0, sift_1.default)(rule.when ?? {}, {
186
+ operations: SAFE_SIFT_OPERATIONS,
187
+ })(payload);
188
+ }
189
+ catch (error) {
190
+ throw new errors_1.RuleEvaluationError(rule.id, 'when', error);
191
+ }
192
+ this.step(context, 'Evaluating a rule', {
193
+ ruleId: rule.id,
194
+ when: rule.when,
195
+ payload,
196
+ shouldProduce,
197
+ });
198
+ return shouldProduce;
199
+ }
200
+ async produce(rule, payload, context) {
201
+ let result;
202
+ try {
203
+ result = (0, normalize_util_1.toPlainValue)(await this.formulas.evaluate(rule.produce.formula, payload, context));
204
+ }
205
+ catch (error) {
206
+ throw new errors_1.RuleEvaluationError(rule.id, 'produce', error);
207
+ }
208
+ this.step(context, 'Producing the result', {
209
+ ruleId: rule.id,
210
+ produce: rule.produce,
211
+ payload,
212
+ result,
213
+ });
214
+ return result;
215
+ }
216
+ };
217
+ exports.BusinessEngineService = BusinessEngineService;
218
+ exports.BusinessEngineService = BusinessEngineService = __decorate([
219
+ (0, common_1.Injectable)(),
220
+ __param(0, (0, common_1.Optional)()),
221
+ __param(0, (0, common_1.Inject)(business_engine_options_1.BUSINESS_ENGINE_OPTIONS)),
222
+ __metadata("design:paramtypes", [Object])
223
+ ], BusinessEngineService);