ts-rules-composer 1.4.0 β†’ 1.5.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/README.md CHANGED
@@ -1,36 +1,32 @@
1
- # TS Rules Composer 🎼
1
+ # TS Rules Composer
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/ts-rules-composer)](https://npmjs.com/package/ts-rules-composer)
4
4
  [![bundle size](https://img.shields.io/bundlephobia/minzip/ts-rules-composer)](https://bundlephobia.com/package/ts-rules-composer)
5
5
  [![license](https://img.shields.io/npm/l/ts-rules-composer)](LICENSE)
6
6
 
7
- A **dependency-free**, type-safe validation engine for composing complex business rules with elegant pipelines.
7
+ A **dependency-free**, type-safe engine for composing business rules and policy checks into pipelines.
8
8
 
9
- ```typescript
10
- // Example: E-commerce checkout
11
- const validateCheckout = pipeRules([
12
- validateCart,
13
- match((order) => order.paymentMethod, {
14
- 'credit_card': validateCreditCard,
15
- 'paypal': validatePaypal
16
- }),
17
- withRetry(validateInventory, { attempts: 3 })
18
- ]);
9
+ ## Why
19
10
 
20
- const result = await validateCheckout(order);
21
- ```
11
+ Schema validators answer "is this data shaped correctly?". Business rules ask more: does this user have permission, is this order within their limit, did the fraud service say yes before the timeout? Those checks need shared context, async calls, branching, retries and timeouts.
12
+
13
+ `ts-rules-composer` treats each check as a small function (a **rule**) and gives you combinators to wire rules together, with the input, context and error types inferred end to end. It complements schema validators such as `zod`; it does not replace them.
22
14
 
23
- ## Features ✨
15
+ ## Contents
24
16
 
25
- - 🧩 **Composable** - Build pipelines with 25+ combinators (`when`, `unless`, `mapError`, etc.)
26
- - πŸš€ **Zero Dependencies** - Lightweight (under 2KB gzipped)
27
- - 🦾 **TypeScript First** - Full inference for inputs, contexts, and errors
28
- - ⏱ **Async Ready** - Mix sync/async rules seamlessly
29
- - πŸ›‘ **Context-Aware** - Shared validation state
30
- - πŸ”Œ **Extensible** - Easily create custom combinators that integrate seamlessly
31
- - πŸ“Š **Instrumentation** - Debugging & metrics out-of-the-box
32
- - πŸ§ͺ **Rigorously Tested** - 95+% test coverage with 300+ test cases covering all edge cases
33
- - 🌐 **Node.js + Browser Compatible** – Works in modern browsers and Node.js 22+
17
+ - [Installation](#installation)
18
+ - [Quick start](#quick-start)
19
+ - [Features](#features)
20
+ - [Core concepts](#core-concepts)
21
+ - [Usage examples](#usage-examples)
22
+ - [Error handling](#error-handling-standardization)
23
+ - [Guardrails and policy checks](#guardrails-and-policy-checks)
24
+ - [Context cloning](#context-cloning-options)
25
+ - [Best practices](#best-practices)
26
+ - [Comparison to other libraries](#comparison-to-other-libraries)
27
+ - [API reference](#api-reference)
28
+ - [Cheat sheet](#cheat-sheet)
29
+ - [Contributing](#contributing)
34
30
 
35
31
  ## Installation
36
32
 
@@ -42,9 +38,64 @@ yarn add ts-rules-composer
42
38
  pnpm add ts-rules-composer
43
39
  ```
44
40
 
41
+ Requires Node.js 22 or later, or a modern browser.
42
+
43
+ ## Quick start
44
+
45
+ ```typescript
46
+ import { fail, match, pass, pipeRules } from "ts-rules-composer";
47
+
48
+ type Order = { items: number; total: number; payment: "card" | "paypal" };
49
+ type Ctx = { limit: number };
50
+
51
+ // A rule is a function: (input, context?) => pass() | fail(error)
52
+ const hasItems = (order: Order) =>
53
+ order.items > 0 ? pass() : fail("Cart is empty");
54
+
55
+ const withinLimit = (order: Order, ctx?: Ctx) =>
56
+ order.total <= (ctx?.limit ?? 1000) ? pass() : fail("Over the spending limit");
57
+
58
+ const validateCard = (order: Order) =>
59
+ order.total > 0 ? pass() : fail("Invalid amount");
60
+ const validatePaypal = (_order: Order) => pass();
61
+
62
+ // Combinators wire rules together; context reaches every rule
63
+ const validateCheckout = pipeRules<Order, string, Ctx>([
64
+ hasItems,
65
+ withinLimit,
66
+ match((order: Order) => order.payment, {
67
+ card: validateCard,
68
+ paypal: validatePaypal,
69
+ }),
70
+ ]);
71
+
72
+ await validateCheckout({ items: 2, total: 40, payment: "card" }, { limit: 500 });
73
+ // β†’ { status: "passed" }
74
+
75
+ await validateCheckout({ items: 0, total: 40, payment: "card" });
76
+ // β†’ { status: "failed", error: "Cart is empty" }
77
+
78
+ await validateCheckout({ items: 1, total: 900, payment: "paypal" }, { limit: 500 });
79
+ // β†’ { status: "failed", error: "Over the spending limit" }
80
+ ```
81
+
82
+ `pipeRules` runs rules in order and stops at the first failure. See [Core concepts](#core-concepts) for the model and the [API reference](#api-reference) for every combinator.
83
+
84
+ ## Features
85
+
86
+ - **Composable**: build pipelines from combinators such as `when`, `unless`, `match`, `every` and `mapError`
87
+ - **Zero dependencies**: small and tree-shakeable (`sideEffects: false`)
88
+ - **TypeScript first**: inference for inputs, contexts and errors
89
+ - **Async ready**: mix sync and async rules
90
+ - **Context-aware**: share state, services and configuration across rules
91
+ - **Resilient**: retries, timeouts, memoization and fallbacks built in
92
+ - **Extensible**: write your own combinators with the same `Rule` type
93
+ - **Instrumented**: `withDebug` and `withTap` for logging and metrics
94
+ - **Portable**: Node.js 22+ and modern browsers
95
+
45
96
  ## Core Concepts
46
97
 
47
- ### βš›οΈ The Atomic Validation Unit
98
+ ### The Rule
48
99
 
49
100
  At the heart of `ts-rules-composer` lies the **Rule** β€” a function that performs a single validation step.
50
101
 
@@ -56,7 +107,7 @@ Rules are:
56
107
  - **Async-compatible**: all rules can be sync or async, and combinators handle both transparently.
57
108
  - **Context-aware**: optional `context` can be passed to any rule for dependency injection, configuration, or shared state.
58
109
 
59
- #### 🧩 Rule Signature
110
+ #### Rule signature
60
111
 
61
112
  ```ts
62
113
  type Rule<TInput, TError = string, TContext = unknown> =
@@ -68,16 +119,18 @@ type Rule<TInput, TError = string, TContext = unknown> =
68
119
  - `TContext` – optional shared context object passed to the rule
69
120
  - `Result` – your rule can return synchronously or asynchronously
70
121
 
71
- #### πŸ§ͺ Rule Result
122
+ #### Rule result
72
123
 
73
124
  Rules must return one of two outcomes:
74
125
 
75
126
  ```ts
76
127
  type RuleResult<TError = string> =
77
128
  | { status: "passed" }
78
- | { status: "failed"; error: TError | TError[] };
129
+ | { status: "failed"; error: TError };
79
130
  ```
80
131
 
132
+ Aggregating combinators change the error type: `every` and `oneOf` return a rule whose error is `TError[]` (one entry per failed rule), while `pipeRules`, `composeRules` and the rest keep a single `TError`.
133
+
81
134
  Use the utility functions `pass()` and `fail(error)` to return results:
82
135
 
83
136
  ```ts
@@ -87,7 +140,7 @@ const isEven = (n: number) =>
87
140
  n % 2 === 0 ? pass() : fail("Must be even");
88
141
  ```
89
142
 
90
- #### 🧠 Context Example
143
+ #### Context example
91
144
 
92
145
  Context is optional but powerful. It lets rules access external services, user configuration, or metadata.
93
146
 
@@ -100,7 +153,7 @@ const isAboveThreshold = (n: number, ctx?: Ctx) =>
100
153
 
101
154
  When composing rules, context will be passed automatically to all child rules.
102
155
 
103
- #### πŸ”— Composing Rules
156
+ #### Composing rules
104
157
 
105
158
  Rules are designed to be combined using **combinators** like `pipeRules`, `every`, `oneOf`, `when`, and `match`.
106
159
 
@@ -121,27 +174,19 @@ const result2 = await validate(3, { threshold: 2 });
121
174
 
122
175
  ---
123
176
 
124
- #### 🧰 Summary
125
-
126
- | Feature | Supported |
127
- | ----------------- | --------- |
128
- | Sync & Async | βœ… |
129
- | Error Aggregation | βœ… |
130
- | Context Injection | βœ… |
131
- | Type Inference | βœ… |
132
- | Composition | βœ… |
133
-
134
177
  Each rule is a **unit of validation** that plugs into powerful composition pipelines. You write simple rules and then combine them into expressive, testable flows using composable logic.
135
178
 
136
179
  ## Usage Examples
137
180
 
138
- Complete examples can be found here:
181
+ Complete, type-checked examples (they are compiled by `npm run typecheck`):
139
182
 
140
- - πŸ§‘β€πŸ’» [User Registration](./examples/user-registration.example.ts)
141
- - πŸ’³ [Financial Transaction Validation](./examples/financial-transaction.example.ts)
142
- - πŸš€ [Model Deployment Validator](./examples/model-deployment.example.ts)
183
+ - [User Registration](./examples/user-registration.example.ts)
184
+ - [Financial Transaction Validation](./examples/financial-transaction.example.ts)
185
+ - [Model Deployment Validator](./examples/model-deployment.example.ts)
143
186
 
144
- ### Example 1: Financial Transaction Validation
187
+ ### Sketch: financial transaction pipeline
188
+
189
+ A sketch of how the combinators compose. Helper rules and services (`fraudService`, `validateCardNumber`, `bankAuthCheck` and so on) are assumed; see the linked file above for the runnable version.
145
190
 
146
191
  ```typescript
147
192
  import {
@@ -168,7 +213,7 @@ const checkFraudRisk = withMemoize(
168
213
  const risk = await fraudService.assess(tx);
169
214
  return risk.score < 5 ? pass() : fail("High fraud risk");
170
215
  },
171
- tx => `${tx.userId}-${tx.amount}-${tx.recipient}`,
216
+ tx => JSON.stringify([tx.userId, tx.amount, tx.recipient]),
172
217
  { ttl: 300000 }
173
218
  );
174
219
 
@@ -213,137 +258,6 @@ const validateTransaction = pipeRules([
213
258
  const result = await validateTransaction(paymentRequest);
214
259
  ```
215
260
 
216
- ### Example 2: User Registration
217
-
218
- ```typescript
219
- import { pipeRules, every, match } from 'ts-rules-composer';
220
-
221
- const validateUser = pipeRules([
222
- // Sequential validation
223
- validateUsernameFormat,
224
- withMemoize(checkUsernameAvailability, { ttl: 60000 }),
225
-
226
- // Parallel validation
227
- every([
228
- validatePasswordStrength,
229
- validateEmailFormat,
230
- checkEmailUnique
231
- ]),
232
-
233
- // pattern matching routing
234
- match(
235
- user => user.role,
236
- {
237
- 'admin': validateAdminPrivileges,
238
- 'user': validateStandardUser
239
- },
240
- fail('Unknown role')
241
- )
242
- ]);
243
- ```
244
-
245
- ### Example 3: Healthcare Appointment System
246
-
247
- ```typescript
248
- const bookAppointment = pipeRules([
249
- // Context-aware validation
250
- requireContextRule(
251
- "Missing schedule data",
252
- (appt, ctx: ScheduleContext) => validateDoctorAvailability(appt, ctx)
253
- ),
254
-
255
- // Error transformation
256
- mapError(
257
- validateInsurance,
258
- error => `Insurance error: ${error.code}`
259
- ),
260
-
261
- // Time-sensitive check
262
- withTimeout(
263
- checkFacilityCapacity,
264
- 5000,
265
- "System timeout"
266
- )
267
- ]);
268
-
269
- // Usage
270
- const result = await bookAppointment(newAppointment, clinicSchedule);
271
- ```
272
-
273
- ### Example 4: Content Moderation System
274
-
275
- ```typescript
276
- import {
277
- pipeRules,
278
- validateField,
279
- requireContextRule,
280
- inject,
281
- tap
282
- } from 'ts-rules-composer';
283
-
284
- // 1. Strongly typed context
285
- type ModerationContext = {
286
- moderatorId: string;
287
- permissions: string[];
288
- environment: 'staging' | 'production';
289
- };
290
-
291
- // 2. Rule factory with dependency injection
292
- const createModerationRules = (logger: LoggerService) =>
293
- pipeRules([
294
- // Enforce context requirements
295
- requireContextRule(
296
- "Moderator context required",
297
- (post, ctx: ModerationContext) => pipeRules([
298
-
299
- // Core validations
300
- validateField(post => post.content, content =>
301
- content.length > 0 || fail("Empty content")
302
- ),
303
-
304
- // Environment-specific rule
305
- when(
306
- (_, ctx) => ctx.environment === 'production',
307
- validateField(post => post.tags, tags =>
308
- tags.length <= 5 || fail("Too many tags")
309
- )
310
- ),
311
-
312
- // Permission-based rule
313
- when(
314
- (_, ctx) => ctx.permissions.includes('FLAG_SENSITIVE'),
315
- validateField(post => post.content, checkSensitiveContent)
316
- ),
317
-
318
- // Logging side effect
319
- tap((post, ctx) => {
320
- logger.log({
321
- action: 'moderate',
322
- moderator: ctx.moderatorId,
323
- postId: post.id
324
- });
325
- })
326
- ])
327
- )
328
- ]);
329
-
330
- // 3. Inject dependencies
331
- const moderatePost = inject(
332
- { logger: new Logger() },
333
- createModerationRules
334
- );
335
-
336
- // 4. Usage
337
- const postModerationResult = await moderatePost(
338
- { id: "post123", content: "Hello", tags: ["a"] },
339
- {
340
- moderatorId: "user456",
341
- permissions: ["FLAG_SENSITIVE"],
342
- environment: "production"
343
- }
344
- );
345
- ```
346
-
347
261
  ## Error Handling Standardization
348
262
 
349
263
  This library provides consistent error handling across all validation operations through a standardized system:
@@ -390,7 +304,7 @@ graph TD
390
304
  E --> F[Return Failed Result]
391
305
  ```
392
306
 
393
- ### Best Practices
307
+ ### Error Handling Recipes
394
308
 
395
309
  1. **For validation logic**:
396
310
 
@@ -423,7 +337,7 @@ graph TD
423
337
  Enable debug mode to get enhanced error information:
424
338
 
425
339
  ```typescript
426
- import { withDebug } from './combinators';
340
+ import { withDebug } from 'ts-rules-composer';
427
341
 
428
342
  const debugRule = withDebug(myRule, {
429
343
  onError: (error) => console.error('Rule failed:', error)
@@ -446,7 +360,7 @@ graph TD
446
360
  1. **Composition-Level Setting** (Highest priority)
447
361
  - `pipeRules/composeRules/every/oneOf` configurations
448
362
  2. **Rule-Level Configuration** (Only applies if composition allows)
449
- - `withSafeError` or `getNormalizedRule` settings
363
+ - `getNormalizedRule` settings
450
364
  3. **Global Default** (`safe` mode)
451
365
 
452
366
  #### Behavior Matrix
@@ -487,7 +401,7 @@ graph TD
487
401
  // All rules will use safe mode regardless of their own config
488
402
  const pipeline = pipeRules([
489
403
  unsafeRule, // Will be forced to safe mode
490
- withSafeError(rule, { // Configuration ignored
404
+ getNormalizedRule(rule, { // Configuration ignored
491
405
  errorHandlingMode: 'unsafe'
492
406
  })
493
407
  ], {
@@ -501,7 +415,7 @@ const pipeline = pipeRules([
501
415
  // Rules can specify their own mode since composition allows it
502
416
  const pipeline = pipeRules([
503
417
  unsafeRule, // Runs in unsafe mode
504
- withSafeError(rule, { // Runs in safe mode
418
+ getNormalizedRule(rule, { // Runs in safe mode
505
419
  errorHandlingMode: 'safe'
506
420
  })
507
421
  ], {
@@ -509,6 +423,17 @@ const pipeline = pipeRules([
509
423
  })
510
424
  ```
511
425
 
426
+ ## Guardrails and policy checks
427
+
428
+ When a rule decides whether something is allowed (a permission check, a safety policy, an LLM or fraud judge), a wrong "pass" costs more than a wrong "fail". These defaults and habits keep the failure side safe.
429
+
430
+ - **Fail closed on errors.** In the default `safe` mode a thrown exception becomes a failed result, so a crashing check never passes. Do not use `errorHandlingMode: "unsafe"` on policy rules unless the caller handles exceptions. See [Error handling modes](#error-handling-modes).
431
+ - **Never retry a decision.** `withRetry` retries failed results by default, so a "no" can be retried into a "yes". For policy checks use `retryOn: "thrown"`, which retries only transient exceptions. See [`withRetry`](#withretryrule-options).
432
+ - **Keep the reason when retries run out.** `onExhausted: "last-error"` returns the final error instead of `"MAX_RETRIES_EXCEEDED"`.
433
+ - **Key caches by identity.** `withMemoize` shares entries between callers with the same key, so include everything the verdict depends on (user, tenant, input id), build keys with `JSON.stringify([...])` rather than joining strings, and key by context when the result depends on who is asking. See [`withMemoize`](#withmemoizerule-keyfn-options).
434
+ - **Time out as a failure.** `withTimeout` returns your `timeoutError` as a failed result, so a slow dependency blocks the action instead of letting it through.
435
+ - **Test the failure paths.** Assert that thrown errors, timeouts and exhausted retries all produce `status: "failed"`.
436
+
512
437
  ## Context Cloning Options
513
438
 
514
439
  The library provides flexible context cloning strategies to balance between performance and correctness. You can control cloning behavior through `CompositionOptions`:
@@ -519,31 +444,30 @@ made by one child Rule are visible to the others; the original Context is left
519
444
  unchanged.
520
445
 
521
446
  ```typescript
522
- interface CompositionOptions {
447
+ type CompositionOptions = {
523
448
  cloneContext?: boolean; // Enable/disable cloning
524
- shallowClone?: boolean; // Use shallow clone when true
525
- structuredClone?: boolean; // Force structuredClone when true
526
- }
449
+ cloneStrategy?: "shallow" | "json" | "structured"; // Defaults to "json"
450
+ } & RuleSafetyOptions; // errorHandlingMode, errorTransform (see Error Handling)
527
451
  ```
528
452
 
529
453
  ### Cloning Strategies
530
454
 
531
- The library automatically selects the best available cloning method based on your options and runtime environment:
455
+ The clone method is chosen by `cloneStrategy`. Without it, the JSON clone is used (it is never auto-upgraded to `structuredClone`):
532
456
 
533
- | Option | Priority | Speed | Depth | Special Types* | Circular Refs | Node.js | Browser |
534
- |-------------------|----------|--------|-------|----------------|---------------|---------|---------|
535
- | `shallowClone` | 1st | πŸš€ Fast | Shallow | ❌ No | βœ… Yes | βœ… | βœ… |
536
- | `structuredClone` | 2nd | 🐒 Slow | Deep | βœ… Yes | βœ… Yes | 17+ | Modern |
537
- | JSON Clone | Fallback | 🏎 Fast | Deep | ❌ No | ❌ No | βœ… | βœ… |
457
+ | `cloneStrategy` | Speed | Depth | Special Types* | Circular Refs | Node.js | Browser |
458
+ |-------------------|--------|-------|----------------|---------------|---------|---------|
459
+ | `"shallow"` | πŸš€ Fast | Shallow | ❌ No | βœ… Yes | βœ… | βœ… |
460
+ | `"structured"` | 🐒 Slow | Deep | βœ… Yes | βœ… Yes | βœ… | Modern |
461
+ | `"json"` (default) | 🏎 Fast | Deep | ❌ No | ❌ No | βœ… | βœ… |
538
462
 
539
463
  *Special Types: Date, Map, Set, RegExp, etc.
540
464
 
541
- ### Usage Examples
465
+ ### Cloning examples
542
466
 
543
- **1. Default Behavior (Smart Auto-Detect)**
467
+ **1. Default Behavior (JSON clone)**
544
468
 
545
469
  ```typescript
546
- // Automatically uses the best available clone method
470
+ // Uses the JSON clone
547
471
  pipeRules(rules, { cloneContext: true })
548
472
  ```
549
473
 
@@ -551,15 +475,15 @@ pipeRules(rules, { cloneContext: true })
551
475
 
552
476
  ```typescript
553
477
  // Fastest option - only clones top-level properties
554
- pipeRules(rules, { cloneContext: true, shallowClone: true })
478
+ pipeRules(rules, { cloneContext: true, cloneStrategy: "shallow" })
555
479
  ```
556
480
 
557
481
  **3. Force Structured Clone**
558
482
 
559
483
  ```typescript
560
484
  // Most accurate - preserves special object types
561
- pipeRules(rules, { cloneContext: true, structuredClone: true })
562
- // Falls back to JSON clone if structuredClone isn't available
485
+ pipeRules(rules, { cloneContext: true, cloneStrategy: "structured" })
486
+ // Falls back to the JSON clone if structuredClone isn't available
563
487
  ```
564
488
 
565
489
  ## Best Practices
@@ -570,7 +494,7 @@ pipeRules(rules, { cloneContext: true, structuredClone: true })
570
494
  4. **Type Narrowing** - Use `requireContextRule` for safety
571
495
  5. **Instrument** - Add metrics in production
572
496
 
573
- ## πŸ” Comparison to Other Libraries
497
+ ## Comparison to Other Libraries
574
498
 
575
499
  While many libraries focus on schema validation or static rules, `ts-rules-composer` is designed specifically for **composable business logic**, dynamic workflows, and contextual validation pipelines.
576
500
 
@@ -578,7 +502,7 @@ Here’s how it compares to popular alternatives:
578
502
 
579
503
  | Library | Type | Async | Context-Aware | Type Inference | Size (gzipped) | Notes |
580
504
  | ------------------------------------------------------------------------ | ----------------------- | ----- | ------------- | -------------- | ------------- | ------------------------------------------------ |
581
- | **`ts-rules-composer`** | Rule engine, functional | βœ… | βœ… | βœ… | \~4KB | Built for composing complex, contextual rules |
505
+ | **`ts-rules-composer`** | Rule engine, functional | βœ… | βœ… | βœ… | \~2.3KB | Built for composing complex, contextual rules |
582
506
  | [`zod`](https://github.com/colinhacks/zod) | Schema validation | βœ… | ❌ | βœ… | \~40KB | Excellent for static object validation |
583
507
  | [`io-ts`](https://github.com/gcanti/io-ts) | Runtime type validation | βœ… | ❌ | βœ… | \~5KB+ | Powerful but requires deep functional patterns |
584
508
  | [`json-rules-engine`](https://github.com/CacheControl/json-rules-engine) | Declarative JSON rules | βœ… | ❌ | ❌ | \~25KB | Config-based rules, limited type safety |
@@ -586,7 +510,7 @@ Here’s how it compares to popular alternatives:
586
510
 
587
511
  ---
588
512
 
589
- ### 🧠 When to Use `ts-rules-composer`
513
+ ### When to use `ts-rules-composer`
590
514
 
591
515
  Choose `ts-rules-composer` when your validation or rule logic:
592
516
 
@@ -715,7 +639,7 @@ const validateWithFallback = withFallback(
715
639
 
716
640
  ### Error Handling
717
641
 
718
- #### `mapError(rule, transform, options?)`
642
+ #### `mapError(rule, transform)`
719
643
 
720
644
  Transforms error output
721
645
 
@@ -841,7 +765,7 @@ const authRule = requireContextRule(
841
765
  )
842
766
  ```
843
767
 
844
- #### `withLazyContext(loader, rule, options?)`
768
+ #### `withLazyContext(loader, rule)`
845
769
 
846
770
  Lazy-loads context
847
771
 
@@ -875,7 +799,7 @@ const debugRule = withDebug(validateOrder, {
875
799
  })
876
800
  ```
877
801
 
878
- #### `tap(effect, options?)`
802
+ #### `tap(effect)`
879
803
 
880
804
  Creates a standalone tap effect for use in composition pipelines
881
805
 
@@ -916,16 +840,6 @@ Creates failure result
916
840
  const failure = fail("Invalid input")
917
841
  ```
918
842
 
919
- #### `getRuleError(result)`
920
-
921
- Extracts error from failed result
922
-
923
- ```typescript
924
- if (result.status === "failed") {
925
- const error = getRuleError(result)
926
- }
927
- ```
928
-
929
843
  #### `validateField(getter, rule, defaultValue?)`
930
844
 
931
845
  Validates object fields
@@ -948,7 +862,9 @@ const createDbRule = (db: Database) => (input: string) =>
948
862
  const dbRule = inject(database, createDbRule)
949
863
  ```
950
864
 
951
- ### Core Functions
865
+ ## Cheat Sheet
866
+
867
+ ### Core
952
868
 
953
869
  | Function | Description | Example |
954
870
  |----------|-------------|---------|
@@ -958,30 +874,30 @@ const dbRule = inject(database, createDbRule)
958
874
  | `match` | Pattern matching routing | `match(getUserType, { admin: ruleA, user: ruleB })` |
959
875
  | `ifElse` | Conditional routing | `ifElse(isUnderAge, validateMinorAccount, validateAdultAccount)` |
960
876
 
961
- ### Combinators
877
+ ### Combinators (summary)
962
878
 
963
879
  | Combinator | Purpose | Example |
964
880
  |------------|---------|---------|
965
881
  | `when` | Conditional execution | `when(isAdmin, validateAdmin)` |
966
882
  | `unless` | Negative condition | `unless(isGuest, validateAccount)` |
967
883
  | `not` | Invert rule logic | `not(isBanned, "Must not be banned")` |
968
- | `oneOf` | First-successful validation | `oneOf(validateV1, validateV2)` |
884
+ | `oneOf` | First-successful validation | `oneOf([validateV1, validateV2])` |
969
885
  | `withFallback` | Fallback rule | `withFallback(primary, backup)` |
970
886
 
971
- ### Performance
887
+ ### Performance (summary)
972
888
 
973
889
  | Utility | Use Case | Example |
974
890
  |---------|----------|---------|
975
- | `withMemoize` | Cache results | `withMemoize(expensiveCheck, { ttl: 30000 })` |
891
+ | `withMemoize` | Cache results | `withMemoize(expensiveCheck, input => input.id, { ttl: 30000 })` |
976
892
  | `withTimeout` | Add time limit | `withTimeout(networkCall, 3000, "Timeout")` |
977
893
  | `withRetry` | Automatic retries | `withRetry(unstableAPI, { attempts: 3 })` |
978
894
 
979
- ### Instrumentation
895
+ ### Instrumentation (summary)
980
896
 
981
897
  | Tool | Purpose | Example |
982
898
  |------|---------|---------|
983
899
  | `withDebug` | Debug logging | `withDebug(rule, { name: "Validation" })` |
984
- | `tap` | Side effects | `tap((input, result) => log(result))` |
900
+ | `tap` | Side effects | `tap((input, context) => log(input))` |
985
901
 
986
902
  ## Contributing
987
903
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=e=>e!==void 0,t=e=>({status:`failed`,error:e}),n=()=>({status:`passed`}),r=(e,n,r)=>{let i=r||(e=>e!==void 0);return async(r,a)=>i(a)?n(r,a):t(e)},i=(e,n)=>async r=>{try{return n(r,await e(r))}catch(e){let n=e instanceof Error?e.message:`Context loading failed`;return t(n)}},a=(e,t,n)=>{let r={fixed:()=>n,linear:e=>n*e,exponential:e=>n*2**(e-1)};if(!e)return r.fixed(t);if(typeof e==`string`){let i=r[e];return i?i(t):n}return typeof e==`function`?e(t):r.fixed(t)},o=(e,t)=>t?.errorHandlingMode===`unsafe`?e:b(e,t?.errorTransform),s=(e,t)=>t?.errorHandlingMode===`unsafe`?e:(e||[])?.map(e=>b(e,t?.errorTransform)),c=e=>{if(!e)return{};try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},l=e=>{if(!e)return{};try{return{...e}}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},u=e=>{let t=typeof structuredClone<`u`;return e.cloneStrategy===`shallow`?l:e.cloneStrategy===`structured`&&t?structuredClone:c};function d(e,r,i){let a=s([...e],r),o=u(r),c=r.cloneContext;return async(e,r)=>{let s=c?o(r):r;if(i===`parallelCollect`){let r=(await Promise.all(a.map(t=>t(e,s)))).flatMap(e=>e.status===`failed`?[e.error]:[]);return r.length>0?t(r):n()}let l=i===`forwardFailFast`?a:[...a].reverse();for(let t of l){let n=await t(e,s);if(n.status===`failed`)return n}return n()}}const f=(e,t={})=>d(e,t,`parallelCollect`),p=(e,t)=>{let n=t(e);return(e,t)=>n(e,t)},m=(e,r)=>async(i,a)=>{let o=await e(i,a);return o.status===`failed`?t(r(o.error)):n()},h=e=>async(t,r)=>{try{await e(t,r)}catch(e){console.error(`Tap effect failed: `,e)}return n()};function g(e,n,r,i){return async(a,s)=>{let c=e(a),l=c===void 0?r:c,u=o(n,i);return l===void 0?t(`Missing required value`):u(l,s)}}const _=(e,t)=>{let n=typeof t==`string`?{name:t}:t;return async(t,r)=>{let i=performance.now(),a=n.name||e.name||`anonymous_rule`;try{n.onStart?.(t,r);let o=await e(t,r),s=performance.now()-i;return n.onEnd?.(t,o,r,{ruleName:a,duration:s,startTime:i}),o}catch(e){let a=performance.now()-i;throw n.onError?.(e,t,r,a),e}}},v=(e,t,n={})=>{let r=/* @__PURE__ */ new Map;return async(i,a)=>{let s=t(i,a),c=Date.now();if(n.ttl)for(let[e,t]of r)c-t.timestamp>n.ttl&&r.delete(e);let l=r.get(s);if(l)return l.result;if(n.maxSize&&r.size>=n.maxSize){let e=r.keys().next().value;e!==void 0&&r.delete(e)}let u=o(e,n)(i,a);return r.set(s,{result:u,timestamp:c}),u instanceof Promise&&u.catch(()=>r.delete(s)),u}};function y(e,n={}){let{attempts:r=3,delayMs:i=100,shouldRetry:o=()=>!0,retryOn:s=`both`,onExhausted:c=`max-retries`}=n;return async(l,u)=>{let d,f;for(let c=1;c<=r;c++){try{let t=await e(l,u);if(t.status===`passed`)return t;d=t.error,f=!1}catch(e){d=e,f=!0}if(s!==`both`&&s!==(f?`thrown`:`failed`)||!o(d,c))return t(d);if(c<r&&i>0){let e=a(n?.retryStrategy,c,i);await new Promise(t=>setTimeout(t,e))}}return t(c===`last-error`?d:`MAX_RETRIES_EXCEEDED`)}}const b=(e,n=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(r,i)=>{try{let a=await e(r,i);return a&&typeof a==`object`&&`status`in a?a:t(n(/* @__PURE__ */ Error(`Invalid rule - did not return RuleResult`)))}catch(e){return t(n(e))}},x=(e,t=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(n,r)=>{try{let i=await e(n,r);return typeof i==`boolean`?{status:`passed`,value:i}:{status:`failed`,error:t(/* @__PURE__ */ Error(`Predicate must return boolean, got ${typeof i}`))}}catch(e){return{status:`failed`,error:t(e)}}},S=(e,t)=>n=>async(r,i)=>{let a=await o(n,t)(r,i);try{await e(r,a,i)}catch(e){console.error(`Tap effect failed:`,e)}return a},C=(e,n,r,i)=>async(a,s)=>{let c=o(e,i),l=new Promise(e=>setTimeout(()=>e(t(r)),n));return Promise.race([c(a,s),l])},w=(e,r,i,a)=>async(o,c)=>{let l=await x(e,a?.predicateErrorTransform)(o,c);if(l.status===`failed`)return t(l.error);let[u,d]=s([r,i],a);return l.value?u(o,c):i?d(o,c):n()},T=e=>typeof e==`function`,E=(e,n,r,i)=>async(a,s)=>{let c=await e(a,s),l=n[c];return l?o(l,i)(a,s):r===void 0?t(`No matching rule for key: ${String(c)}`):T(r)?o(r,i)(a,s):t(r)},D=(e,r,i)=>async(a,s)=>(await o(e,i)(a,s)).status===`passed`?t(r):n(),O=(e,r)=>async(i,a)=>{let o=s(e,r),c=[];if(!e||e.length===0)return n();for(let e of o){let t=await e(i,a);if(t.status===`passed`)return n();c.push(t.error)}return t(c)},k=(e,r,i)=>async(a,s)=>{let c=o(r,i),l=await x(e,i?.predicateErrorTransform)(a,s);return l.status===`failed`?t(l.error):l.value?n():c(a,s)},A=(e,r,i)=>async(a,s)=>{let c=o(r,i),l=await x(e,i?.predicateErrorTransform)(a,s);return l.status===`failed`?t(l.error):l.value?c(a,s):n()},j=(e,t,n={})=>async(r,i)=>{let[a,o]=s([e,t],n),c=await a(r,i);return c.status===`failed`&&(!n.onlyFallbackOn||n.onlyFallbackOn(c.error))?o(r,i):c},M=(e,t={})=>d(e,t,`reverseFailFast`);function N(e,...t){return t.reduce((e,t)=>t(e),e)}const P=(e,t={})=>d(e,t,`forwardFailFast`);exports.calculateDelay=a,exports.composeRules=M,exports.every=f,exports.fail=t,exports.getNormalizedRule=o,exports.getNormalizedRules=s,exports.hasContext=e,exports.ifElse=w,exports.inject=p,exports.mapError=m,exports.match=E,exports.not=D,exports.oneOf=O,exports.pass=n,exports.pipe=N,exports.pipeRules=P,exports.requireContextRule=r,exports.tap=h,exports.unless=k,exports.validateField=g,exports.when=A,exports.withDebug=_,exports.withFallback=j,exports.withLazyContext=i,exports.withMemoize=v,exports.withRetry=y,exports.withSafeError=b,exports.withSafePredicate=x,exports.withTap=S,exports.withTimeout=C;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./to-graph-Dilv6lBr.cjs"),t=e=>e!==void 0,n=e=>({status:`failed`,error:e}),r=()=>({status:`passed`}),i=(e,t,r)=>{let i=r||(e=>e!==void 0);return async(r,a)=>i(a)?t(r,a):n(e)},a=(e,t)=>async r=>{try{return t(r,await e(r))}catch(e){let t=e instanceof Error?e.message:`Context loading failed`;return n(t)}},o=(e,t,n)=>{let r={fixed:()=>n,linear:e=>n*e,exponential:e=>n*2**(e-1)};if(!e)return r.fixed(t);if(typeof e==`string`){let i=r[e];return i?i(t):n}return typeof e==`function`?e(t):r.fixed(t)},s=(e,t)=>t?.errorHandlingMode===`unsafe`?e:x(e,t?.errorTransform),c=(e,t)=>t?.errorHandlingMode===`unsafe`?e:(e||[])?.map(e=>x(e,t?.errorTransform)),l=e=>{if(!e)return{};try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},u=e=>{if(!e)return{};try{return{...e}}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},d=e=>{let t=typeof structuredClone<`u`;return e.cloneStrategy===`shallow`?u:e.cloneStrategy===`structured`&&t?structuredClone:l};function f(e,t,i){let a=c([...e],t),o=d(t),s=t.cloneContext;return async(e,t)=>{let c=s?o(t):t;if(i===`parallelCollect`){let t=(await Promise.all(a.map(t=>t(e,c)))).flatMap(e=>e.status===`failed`?[e.error]:[]);return t.length>0?n(t):r()}let l=i===`forwardFailFast`?a:[...a].reverse();for(let t of l){let n=await t(e,c);if(n.status===`failed`)return n}return r()}}const p=(e,t={})=>f(e,t,`parallelCollect`),m=(e,t)=>{let n=t(e);return(e,t)=>n(e,t)},h=(e,t)=>async(i,a)=>{let o=await e(i,a);return o.status===`failed`?n(t(o.error)):r()},g=e=>async(t,n)=>{try{await e(t,n)}catch(e){console.error(`Tap effect failed: `,e)}return r()};function _(e,t,r,i){return async(a,o)=>{let c=e(a),l=c===void 0?r:c,u=s(t,i);return l===void 0?n(`Missing required value`):u(l,o)}}const v=(e,t)=>{let n=typeof t==`string`?{name:t}:t;return async(t,r)=>{let i=performance.now(),a=n.name||e.name||`anonymous_rule`;try{n.onStart?.(t,r);let o=await e(t,r),s=performance.now()-i;return n.onEnd?.(t,o,r,{ruleName:a,duration:s,startTime:i}),o}catch(e){let a=performance.now()-i;throw n.onError?.(e,t,r,a),e}}},y=(e,t,n={})=>{let r=/* @__PURE__ */ new Map;return async(i,a)=>{let o=t(i,a),c=Date.now();if(n.ttl)for(let[e,t]of r)c-t.timestamp>n.ttl&&r.delete(e);let l=r.get(o);if(l)return l.result;if(n.maxSize&&r.size>=n.maxSize){let e=r.keys().next().value;e!==void 0&&r.delete(e)}let u=s(e,n)(i,a);return r.set(o,{result:u,timestamp:c}),u instanceof Promise&&u.catch(()=>r.delete(o)),u}};function b(e,t={}){let{attempts:r=3,delayMs:i=100,shouldRetry:a=()=>!0,retryOn:s=`both`,onExhausted:c=`max-retries`}=t;return async(l,u)=>{let d,f;for(let c=1;c<=r;c++){try{let t=await e(l,u);if(t.status===`passed`)return t;d=t.error,f=!1}catch(e){d=e,f=!0}if(s!==`both`&&s!==(f?`thrown`:`failed`)||!a(d,c))return n(d);if(c<r&&i>0){let e=o(t?.retryStrategy,c,i);await new Promise(t=>setTimeout(t,e))}}return n(c===`last-error`?d:`MAX_RETRIES_EXCEEDED`)}}const x=(e,t=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(r,i)=>{try{let a=await e(r,i);return a&&typeof a==`object`&&`status`in a?a:n(t(/* @__PURE__ */ Error(`Invalid rule - did not return RuleResult`)))}catch(e){return n(t(e))}},S=(e,t=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(n,r)=>{try{let i=await e(n,r);return typeof i==`boolean`?{status:`passed`,value:i}:{status:`failed`,error:t(/* @__PURE__ */ Error(`Predicate must return boolean, got ${typeof i}`))}}catch(e){return{status:`failed`,error:t(e)}}},C=(e,t)=>n=>async(r,i)=>{let a=await s(n,t)(r,i);try{await e(r,a,i)}catch(e){console.error(`Tap effect failed:`,e)}return a},w=(e,t,r,i)=>async(a,o)=>{let c=s(e,i),l=new Promise(e=>setTimeout(()=>e(n(r)),t));return Promise.race([c(a,o),l])},T=(e,t,i,a)=>async(o,s)=>{let l=await S(e,a?.predicateErrorTransform)(o,s);if(l.status===`failed`)return n(l.error);let[u,d]=c([t,i],a);return l.value?u(o,s):i?d(o,s):r()},E=e=>typeof e==`function`,D=(e,t,r,i)=>async(a,o)=>{let c=await e(a,o),l=t[c];return l?s(l,i)(a,o):r===void 0?n(`No matching rule for key: ${String(c)}`):E(r)?s(r,i)(a,o):n(r)},O=(e,t,i)=>async(a,o)=>(await s(e,i)(a,o)).status===`passed`?n(t):r(),k=(e,t)=>async(i,a)=>{let o=c(e,t),s=[];if(!e||e.length===0)return r();for(let e of o){let t=await e(i,a);if(t.status===`passed`)return r();s.push(t.error)}return n(s)},A=(e,t,i)=>async(a,o)=>{let c=s(t,i),l=await S(e,i?.predicateErrorTransform)(a,o);return l.status===`failed`?n(l.error):l.value?r():c(a,o)},j=(t,i,a)=>e.n(async(e,o)=>{let c=s(i,a),l=await S(t,a?.predicateErrorTransform)(e,o);return l.status===`failed`?n(l.error):l.value?c(e,o):r()},{kind:`branch`,test:t,ifTrue:i}),M=(e,t,n={})=>async(r,i)=>{let[a,o]=c([e,t],n),s=await a(r,i);return s.status===`failed`&&(!n.onlyFallbackOn||n.onlyFallbackOn(s.error))?o(r,i):s},N=(e,t={})=>f(e,t,`reverseFailFast`);function P(e,...t){return t.reduce((e,t)=>t(e),e)}const F=(t,n={})=>e.n(f(t,n,`forwardFailFast`),{kind:`sequence`,via:`pipeRules`,steps:[...t]}),I=(t,n,r)=>e.n(((...e)=>n(...e)),{kind:`rule`,label:t,...r?.params?{params:r.params}:{}});exports.calculateDelay=o,exports.composeRules=N,exports.every=p,exports.fail=n,exports.getNormalizedRule=s,exports.getNormalizedRules=c,exports.hasContext=t,exports.ifElse=T,exports.inject=m,exports.mapError=h,exports.match=D,exports.named=I,exports.not=O,exports.oneOf=k,exports.pass=r,exports.pipe=P,exports.pipeRules=F,exports.requireContextRule=i,exports.tap=g,exports.toGraph=e.t,exports.unless=A,exports.validateField=_,exports.when=j,exports.withDebug=v,exports.withFallback=M,exports.withLazyContext=a,exports.withMemoize=y,exports.withRetry=b,exports.withSafeError=x,exports.withSafePredicate=S,exports.withTap=C,exports.withTimeout=w;
2
2
  //# sourceMappingURL=index.cjs.map