ts-rules-composer 0.0.1 → 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.
Files changed (89) hide show
  1. package/.github/workflows/publish.yml +1 -1
  2. package/README.md +310 -42
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +335 -55
  6. package/dist/index.d.ts +335 -55
  7. package/dist/index.js +1 -1
  8. package/dist/index.js.map +1 -1
  9. package/eslint.config.mjs +84 -0
  10. package/examples/financial-transaction.example.ts +188 -0
  11. package/examples/model-deployment.example.ts +136 -0
  12. package/examples/user-registration.example.ts +101 -0
  13. package/package.json +21 -6
  14. package/src/lib/combinators/logic/every.spec.ts +1 -1
  15. package/src/lib/combinators/logic/every.ts +17 -7
  16. package/src/lib/combinators/logic/if-else.spec.ts +11 -1
  17. package/src/lib/combinators/logic/if-else.ts +33 -8
  18. package/src/lib/combinators/logic/match.ts +20 -6
  19. package/src/lib/combinators/logic/not.spec.ts +3 -1
  20. package/src/lib/combinators/logic/not.ts +12 -3
  21. package/src/lib/combinators/logic/one-of.spec.ts +7 -7
  22. package/src/lib/combinators/logic/one-of.ts +11 -4
  23. package/src/lib/combinators/logic/unless.spec.ts +1 -1
  24. package/src/lib/combinators/logic/unless.ts +28 -5
  25. package/src/lib/combinators/logic/when.spec.ts +11 -15
  26. package/src/lib/combinators/logic/when.ts +29 -8
  27. package/src/lib/combinators/logic/with-fallback.ts +13 -4
  28. package/src/lib/combinators/utility/index.ts +5 -2
  29. package/src/lib/combinators/utility/inject.ts +1 -1
  30. package/src/lib/combinators/utility/map-error.ts +1 -1
  31. package/src/lib/combinators/utility/tap.spec.ts +63 -63
  32. package/src/lib/combinators/utility/tap.ts +18 -28
  33. package/src/lib/combinators/utility/validate-field.spec.ts +1 -1
  34. package/src/lib/combinators/utility/validate-field.ts +10 -3
  35. package/src/lib/combinators/utility/with-debug.spec.ts +1 -1
  36. package/src/lib/combinators/utility/with-debug.ts +1 -1
  37. package/src/lib/combinators/utility/with-memoize.spec.ts +1 -1
  38. package/src/lib/combinators/utility/with-memoize.ts +12 -4
  39. package/src/lib/combinators/utility/with-retry.spec.ts +1 -1
  40. package/src/lib/combinators/utility/with-retry.ts +4 -2
  41. package/src/lib/combinators/utility/with-safe-error.spec.ts +137 -0
  42. package/src/lib/combinators/utility/with-safe-error.ts +56 -0
  43. package/src/lib/combinators/utility/with-safe-predicate.spec.ts +176 -0
  44. package/src/lib/combinators/utility/with-safe-predicate.ts +64 -0
  45. package/src/lib/combinators/utility/with-tap.spec.ts +104 -0
  46. package/src/lib/combinators/utility/with-tap.ts +46 -0
  47. package/src/lib/combinators/utility/with-timeout.spec.ts +1 -1
  48. package/src/lib/combinators/utility/with-timeout.ts +10 -3
  49. package/src/lib/composition/compose-rules.spec.ts +1 -1
  50. package/src/lib/composition/compose-rules.ts +16 -8
  51. package/src/lib/composition/pipe-rules.spec.ts +1 -1
  52. package/src/lib/composition/pipe-rules.ts +15 -7
  53. package/src/lib/composition/pipe.ts +1 -0
  54. package/src/lib/helpers/clone/clone.ts +12 -0
  55. package/src/lib/helpers/clone/getCloneFn.ts +17 -0
  56. package/src/lib/helpers/clone/shallowClone.ts +12 -0
  57. package/src/lib/helpers/context/require-context.ts +1 -1
  58. package/src/lib/helpers/context/with-lazy-context.spec.ts +1 -1
  59. package/src/lib/helpers/context/with-lazy-context.ts +1 -1
  60. package/src/lib/helpers/index.ts +2 -0
  61. package/src/lib/helpers/result/fail.ts +1 -1
  62. package/src/lib/helpers/result/pass.ts +1 -1
  63. package/src/lib/helpers/retry/calculate-delay.ts +1 -1
  64. package/src/lib/helpers/safety/get-normalized-rule.spec.ts +209 -0
  65. package/src/lib/helpers/safety/get-normalized-rule.ts +14 -0
  66. package/src/lib/helpers/safety/get-normalized-rules.spec.ts +138 -0
  67. package/src/lib/helpers/safety/get-normalized-rules.ts +14 -0
  68. package/src/lib/index.ts +1 -1
  69. package/src/lib/types/composition-options.ts +28 -3
  70. package/src/lib/types/debug-options.ts +1 -1
  71. package/src/lib/types/index.ts +8 -4
  72. package/src/lib/types/predicate-result.ts +20 -0
  73. package/src/lib/types/predicate-safe.ts +10 -0
  74. package/src/lib/types/predicate-safety-options.ts +27 -0
  75. package/src/lib/types/predicate.ts +8 -0
  76. package/src/lib/types/prettify.ts +3 -0
  77. package/src/lib/types/rule-safety-options.ts +34 -0
  78. package/src/lib/types/rule.ts +1 -1
  79. package/src/lib/types/safety-options.ts +7 -0
  80. package/src/test/financial-transaction.spec.ts +251 -0
  81. package/src/test/helpers/get-rule-error.ts +1 -1
  82. package/src/test/integration.spec.ts +3 -3
  83. package/src/test/model-deployment.spec.ts +209 -0
  84. package/src/test/user-registration.spec.ts +164 -0
  85. package/tsconfig.json +5 -4
  86. package/tsup.config.ts +15 -15
  87. package/typedoc/tsconfig.typedoc.json +15 -0
  88. package/typedoc/typedoc.json +14 -0
  89. package/.eslintrc.json +0 -66
@@ -22,4 +22,4 @@ jobs:
22
22
  - name: Publish
23
23
  run: npm run release
24
24
  env:
25
- NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
25
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/README.md CHANGED
@@ -10,7 +10,7 @@ A **dependency-free**, type-safe validation engine for composing complex busines
10
10
  // Example: E-commerce checkout
11
11
  const validateCheckout = pipeRules([
12
12
  validateCart,
13
- match(paymentMethod, {
13
+ match((order) => order.paymentMethod, {
14
14
  'credit_card': validateCreditCard,
15
15
  'paypal': validatePaypal
16
16
  }),
@@ -23,12 +23,14 @@ const result = await validateCheckout(order);
23
23
  ## Features ✨
24
24
 
25
25
  - 🧩 **Composable** - Build pipelines with 25+ combinators (`when`, `unless`, `mapError`, etc.)
26
- - 🚀 **Zero Dependencies** - Lightweight (under 5KB gzipped)
26
+ - 🚀 **Zero Dependencies** - Lightweight (under 2KB gzipped)
27
27
  - 🦾 **TypeScript First** - Full inference for inputs, contexts, and errors
28
28
  - ⏱ **Async Ready** - Mix sync/async rules seamlessly
29
29
  - 🛡 **Context-Aware** - Shared validation state
30
30
  - 🔌 **Extensible** - Easily create custom combinators that integrate seamlessly
31
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 most Node.js versions (14+)
32
34
 
33
35
  ## Installation
34
36
 
@@ -59,12 +61,18 @@ Always returns:
59
61
 
60
62
  ```typescript
61
63
  type RuleResult<TError> =
62
- | { readonly status: "passed" }
63
- | { readonly status: "failed"; readonly error: TError };
64
+ | { readonly status: "passed" }; // pass()
65
+ | { readonly status: "failed"; readonly error: TError }; // fail(error)
64
66
  ```
65
67
 
66
68
  ## Usage Examples
67
69
 
70
+ Complete examples can be found here:
71
+
72
+ - 🧑‍💻 [User Registration](./examples/user-registration.example.ts)
73
+ - 💳 [Financial Transaction Validation](./examples/financial-transaction.example.ts)
74
+ - 🚀 [Model Deployment Validator](./examples/model-deployment.example.ts)
75
+
68
76
  ### Example 1: Financial Transaction Validation
69
77
 
70
78
  ```typescript
@@ -134,15 +142,13 @@ const validateTransaction = pipeRules([
134
142
  ]);
135
143
 
136
144
  // Usage
137
- const result = await validateTransaction(paymentRequest, {
138
- userKycStatus: await getKycStatus(userId)
139
- });
145
+ const result = await validateTransaction(paymentRequest);
140
146
  ```
141
147
 
142
148
  ### Example 2: User Registration
143
149
 
144
150
  ```typescript
145
- import { pipeRules, every, match, withMetrics } from 'ts-rules-composer';
151
+ import { pipeRules, every, match } from 'ts-rules-composer';
146
152
 
147
153
  const validateUser = pipeRules([
148
154
  // Sequential validation
@@ -166,11 +172,6 @@ const validateUser = pipeRules([
166
172
  fail('Unknown role')
167
173
  )
168
174
  ]);
169
-
170
- // With instrumentation
171
- const instrumentedValidation = withMetrics(validateUser, {
172
- onEnd: (result) => trackAnalytics(result)
173
- });
174
175
  ```
175
176
 
176
177
  ### Example 3: Healthcare Appointment System
@@ -275,6 +276,255 @@ const postModerationResult = await moderatePost(
275
276
  );
276
277
  ```
277
278
 
279
+ ## Error Handling Standardization
280
+
281
+ This library provides consistent error handling across all validation operations through a standardized system:
282
+
283
+ ### Core Principles
284
+
285
+ 1. **No Uncaught Exceptions** - All errors are converted to `RuleResult` objects
286
+ 2. **Type Safety** - Custom error types are preserved throughout operations
287
+ 3. **Flexible Control** - Choose between safety and performance with error handling modes
288
+
289
+ ### Standardization Functions
290
+
291
+ | Function | Purpose |
292
+ |-------------------------|-------------------------------------------------------------------------|
293
+ | `withSafeError` | Wraps rules to catch exceptions and convert to failed validation results|
294
+ | `withSafePredicate` | Safely handles predicate functions that may throw |
295
+ | `getNormalizedRule` | Applies consistent error handling to single rules |
296
+ | `getNormalizedRules` | Batch processes multiple rules with standardized error handling |
297
+
298
+ ### Error Handling Modes
299
+
300
+ Configure via `RuleSafetyOptions`:
301
+
302
+ ```typescript
303
+ {
304
+ errorHandlingMode?: 'safe' | 'unsafe', // Default: 'safe'
305
+ errorTransform?: (error: unknown) => TError // Custom error conversion
306
+ }
307
+ ```
308
+
309
+ **Modes**:
310
+
311
+ - `safe`: (Default) All errors are caught and converted to validation failures
312
+ - `unsafe`: Lets exceptions propagate (for performance-critical paths)
313
+
314
+ ### Error Flow
315
+
316
+ ```mermaid
317
+ graph TD
318
+ A[Raw Error] -->|Thrown| B{Handling Mode?}
319
+ B -->|safe| C[Convert to RuleResult]
320
+ B -->|unsafe| D[Propagate Exception]
321
+ C --> E[Apply errorTransform if provided]
322
+ E --> F[Return Failed Result]
323
+ ```
324
+
325
+ ### Best Practices
326
+
327
+ 1. **For validation logic**:
328
+
329
+ ```typescript
330
+ // Safe mode with custom error transformation
331
+ const rule = getNormalizedRule(myRule, {
332
+ errorTransform: (e) => ({ code: 500, message: String(e) })
333
+ });
334
+ ```
335
+
336
+ 2. **For performance-critical paths**:
337
+
338
+ ```typescript
339
+ // Unsafe mode - ensure calling code handles exceptions
340
+ const fastRule = getNormalizedRule(highPerfRule, {
341
+ errorHandlingMode: 'unsafe'
342
+ });
343
+ ```
344
+
345
+ 3. **Custom error types**:
346
+
347
+ ```typescript
348
+ type APIError = { status: number };
349
+ const apiRule: Rule<string, APIError> = /*...*/;
350
+ // Preserves APIError type through all transformations
351
+ ```
352
+
353
+ ### Debugging Tips
354
+
355
+ Enable debug mode to get enhanced error information:
356
+
357
+ ```typescript
358
+ import { withDebug } from './combinators';
359
+
360
+ const debugRule = withDebug(myRule, {
361
+ onError: (error) => console.error('Rule failed:', error)
362
+ });
363
+ ```
364
+
365
+ ### Error Handling Precedence Rules
366
+
367
+ **Key Principle**: Composition configuration always overrides individual rule settings. This ensures consistent behavior within each composition block.
368
+
369
+ ```mermaid
370
+ graph TD
371
+ A[Composition Config] -->|Overrides| B[Individual Rule Config]
372
+ style A stroke:#28cc9e,stroke-width:2px
373
+ style B stroke:#ff9f43
374
+ ```
375
+
376
+ #### Hierarchy of Control
377
+
378
+ 1. **Composition-Level Setting** (Highest priority)
379
+ - `pipeRules/composeRules/every/oneOf` configurations
380
+ 2. **Rule-Level Configuration** (Only applies if composition allows)
381
+ - `withSafeError` or `getNormalizedRule` settings
382
+ 3. **Global Default** (`safe` mode)
383
+
384
+ #### Behavior Matrix
385
+
386
+ | Composition Mode | Rule Mode | Effective Behavior |
387
+ |------------------|-----------------|--------------------------|
388
+ | `safe` | Any | All rules run in safe mode |
389
+ | `unsafe` | Not specified | Rule's native behavior |
390
+ | `unsafe` | `safe` | Rule runs in safe mode |
391
+ | `unsafe` | `unsafe` | Rule runs in unsafe mode |
392
+
393
+ #### Complete Error Flow
394
+
395
+ ```mermaid
396
+ graph TD
397
+ A[Raw Error] --> B{Composition<br>Configuration?}
398
+ B -->|safe| C[Force Safe Handling]
399
+ B -->|unsafe| D{Individual Rule<br>Configuration?}
400
+ D -->|safe or not specified| C[Propagate Exception]
401
+ D -->|unsafe| E
402
+ C --> F[Apply errorTransform]
403
+ F --> G[Return Failed Result]
404
+ E --> H[Propagate Raw Exception]
405
+
406
+ style B stroke:#28cc9e,stroke-width:2px
407
+ style D stroke:#ff9f43
408
+ classDef green fill:#e6f7e6,stroke:#28cc9e
409
+ classDef yellow fill:#fff8e6,stroke:#ff9f43
410
+ class B,D green,yellow
411
+
412
+ ```
413
+
414
+ #### Examples
415
+
416
+ **1. Composition Forces Safe Mode** (Overrides all rules)
417
+
418
+ ```typescript
419
+ // All rules will use safe mode regardless of their own config
420
+ const pipeline = pipeRules([
421
+ unsafeRule, // Will be forced to safe mode
422
+ withSafeError(rule, { // Configuration ignored
423
+ errorHandlingMode: 'unsafe'
424
+ })
425
+ ], {
426
+ errorHandlingMode: 'safe' // ← Takes precedence
427
+ })
428
+ ```
429
+
430
+ **2. Unsafe Composition with Mixed Rules**
431
+
432
+ ```typescript
433
+ // Rules can specify their own mode since composition allows it
434
+ const pipeline = pipeRules([
435
+ unsafeRule, // Runs in unsafe mode
436
+ withSafeError(rule, { // Runs in safe mode
437
+ errorHandlingMode: 'safe'
438
+ })
439
+ ], {
440
+ errorHandlingMode: 'unsafe' // ← Allows rule-level configs
441
+ })
442
+ ```
443
+
444
+ ## Context Cloning Options
445
+
446
+ The library provides flexible context cloning strategies to balance between performance and correctness. You can control cloning behavior through `CompositionOptions`:
447
+
448
+ ```typescript
449
+ interface CompositionOptions {
450
+ cloneContext?: boolean; // Enable/disable cloning
451
+ shallowClone?: boolean; // Use shallow clone when true
452
+ structuredClone?: boolean; // Force structuredClone when true
453
+ }
454
+ ```
455
+
456
+ ### Cloning Strategies
457
+
458
+ The library automatically selects the best available cloning method based on your options and runtime environment:
459
+
460
+ | Option | Priority | Speed | Depth | Special Types* | Circular Refs | Node.js | Browser |
461
+ |-------------------|----------|--------|-------|----------------|---------------|---------|---------|
462
+ | `shallowClone` | 1st | 🚀 Fast | Shallow | ❌ No | ✅ Yes | ✅ | ✅ |
463
+ | `structuredClone` | 2nd | 🐢 Slow | Deep | ✅ Yes | ✅ Yes | 17+ | Modern |
464
+ | JSON Clone | Fallback | 🏎 Fast | Deep | ❌ No | ❌ No | ✅ | ✅ |
465
+
466
+ *Special Types: Date, Map, Set, RegExp, etc.
467
+
468
+ ### Usage Examples
469
+
470
+ **1. Default Behavior (Smart Auto-Detect)**
471
+
472
+ ```typescript
473
+ // Automatically uses the best available clone method
474
+ pipeRules(rules, { cloneContext: true })
475
+ ```
476
+
477
+ **2. Force Shallow Clone**
478
+
479
+ ```typescript
480
+ // Fastest option - only clones top-level properties
481
+ pipeRules(rules, { cloneContext: true, shallowClone: true })
482
+ ```
483
+
484
+ **3. Force Structured Clone**
485
+
486
+ ```typescript
487
+ // Most accurate - preserves special object types
488
+ pipeRules(rules, { cloneContext: true, structuredClone: true })
489
+ // Falls back to JSON clone if structuredClone isn't available
490
+ ```
491
+
492
+ ## Best Practices
493
+
494
+ 1. **Small Rules** - Keep each rule focused
495
+ 2. **Pure Functions** - Avoid side effects in rules
496
+ 3. **Memoize** - Cache expensive validations
497
+ 4. **Type Narrowing** - Use `requireContextRule` for safety
498
+ 5. **Instrument** - Add metrics in production
499
+
500
+ ## 🔍 Comparison to Other Libraries
501
+
502
+ 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.
503
+
504
+ Here’s how it compares to popular alternatives:
505
+
506
+ | Library | Type | Async | Context-Aware | Type Inference | Size (gzipped) | Notes |
507
+ | ------------------------------------------------------------------------ | ----------------------- | ----- | ------------- | -------------- | ------------- | ------------------------------------------------ |
508
+ | **`ts-rules-composer`** | Rule engine, functional | ✅ | ✅ | ✅ | \~4KB | Built for composing complex, contextual rules |
509
+ | [`zod`](https://github.com/colinhacks/zod) | Schema validation | ✅ | ❌ | ✅ | \~40KB | Excellent for static object validation |
510
+ | [`io-ts`](https://github.com/gcanti/io-ts) | Runtime type validation | ✅ | ❌ | ✅ | \~5KB+ | Powerful but requires deep functional patterns |
511
+ | [`json-rules-engine`](https://github.com/CacheControl/json-rules-engine) | Declarative JSON rules | ✅ | ❌ | ❌ | \~25KB | Config-based rules, limited type safety |
512
+ | [`casl`](https://casl.js.org/) | Authorization DSL | ✅ | ✅ | ⚠️ Limited | \~6KB | Great for access control, not general validation |
513
+
514
+ ---
515
+
516
+ ### 🧠 When to Use `ts-rules-composer`
517
+
518
+ Choose `ts-rules-composer` when your validation or rule logic:
519
+
520
+ - Involves **multiple branching paths**, retries, timeouts, or side effects
521
+ - Requires **shared context** (e.g. user metadata, database, external services)
522
+ - Needs **clean separation** of rule logic and pipeline composition
523
+ - Must run in both **Node.js or the browser**
524
+ - Should remain **type-safe** and **composable**
525
+
526
+ This library is not meant to replace schema validators like `zod`, but to complement them — it's ideal when your business logic **cannot be expressed declaratively** or **requires orchestration** of multiple validation steps.
527
+
278
528
  ## API Reference
279
529
 
280
530
  ### Core Functions
@@ -317,7 +567,7 @@ const validateProfile = every([
317
567
 
318
568
  ### Control Flow
319
569
 
320
- #### `match(accessor, cases, defaultCase?)`
570
+ #### `match(accessor, cases, defaultCase?, options?)`
321
571
 
322
572
  Pattern matching routing
323
573
 
@@ -333,7 +583,7 @@ const validatePayment = match(
333
583
  )
334
584
  ```
335
585
 
336
- #### `when(condition, rule)`
586
+ #### `when(condition, rule, options?)`
337
587
 
338
588
  Executes only if condition is true
339
589
 
@@ -344,7 +594,7 @@ const validateAdmin = when(
344
594
  )
345
595
  ```
346
596
 
347
- #### `unless(condition, rule)`
597
+ #### `unless(condition, rule, options?)`
348
598
 
349
599
  Executes only if condition is false
350
600
 
@@ -355,7 +605,7 @@ const validateGuest = unless(
355
605
  )
356
606
  ```
357
607
 
358
- #### `ifElse(condition, ifRule, elseRule?)`
608
+ #### `ifElse(condition, ifRule, elseRule?, options?)`
359
609
 
360
610
  Branch between two rules
361
611
 
@@ -367,7 +617,7 @@ const validateAge = ifElse(
367
617
  )
368
618
  ```
369
619
 
370
- #### `oneOf(...rules)`
620
+ #### `oneOf(rules, options?)`
371
621
 
372
622
  Tries rules until one passes
373
623
 
@@ -392,7 +642,7 @@ const validateWithFallback = withFallback(
392
642
 
393
643
  ### Error Handling
394
644
 
395
- #### `mapError(rule, transform)`
645
+ #### `mapError(rule, transform, options?)`
396
646
 
397
647
  Transforms error output
398
648
 
@@ -403,7 +653,7 @@ const friendlyErrors = mapError(
403
653
  )
404
654
  ```
405
655
 
406
- #### `not(rule, error)`
656
+ #### `not(rule, error, options?)`
407
657
 
408
658
  Inverts rule logic
409
659
 
@@ -414,6 +664,28 @@ const isNotBanned = not(
414
664
  )
415
665
  ```
416
666
 
667
+ #### `withSafeError(rule, errorTransform?)`
668
+
669
+ Wraps a rule to catch errors and convert them to failed RuleResults
670
+
671
+ ```typescript
672
+ const customSafeRule = withSafeError(riskyRule, e => ({
673
+ code: 500,
674
+ message: String(e)
675
+ }));
676
+ ```
677
+
678
+ #### `withSafePredicate(rule, errorTransform?)`
679
+
680
+ Wraps a predicate function with error handling and type safety
681
+
682
+ ```typescript
683
+ const safePredicate = withSafePredicate(
684
+ (input: string) => input.length > 5,
685
+ (err) => `Predicate failed: ${String(err)}`
686
+ );
687
+ ```
688
+
417
689
  ### Performance
418
690
 
419
691
  #### `withMemoize(rule, keyFn, options?)`
@@ -428,7 +700,7 @@ const cachedCheck = withMemoize(
428
700
  )
429
701
  ```
430
702
 
431
- #### `withTimeout(rule, ms, timeoutError)`
703
+ #### `withTimeout(rule, ms, timeoutError, options?)`
432
704
 
433
705
  Adds execution timeout
434
706
 
@@ -465,7 +737,7 @@ const authRule = requireContextRule(
465
737
  )
466
738
  ```
467
739
 
468
- #### `withLazyContext(loader, rule)`
740
+ #### `withLazyContext(loader, rule, options?)`
469
741
 
470
742
  Lazy-loads context
471
743
 
@@ -499,14 +771,27 @@ const debugRule = withDebug(validateOrder, {
499
771
  })
500
772
  ```
501
773
 
502
- #### `tap(effect)`
774
+ #### `tap(effect, options?)`
775
+
776
+ Creates a standalone tap effect for use in composition pipelines
777
+
778
+ ```typescript
779
+ pipeRules([
780
+ tap((input) => console.log('Processing: ', input)),
781
+ validateInput
782
+ ])
783
+ ```
784
+
785
+ #### `withTap(effect, options?)`
503
786
 
504
- Performs side effects
787
+ Wraps a rule with side effects without modifying its result
505
788
 
506
789
  ```typescript
507
- const loggedRule = tap((input, result) => {
790
+ const loggedRule = withTap((input, result) => {
508
791
  analytics.trackValidation(input, result)
509
792
  })
793
+
794
+ const ruleResult = await loggedRule(input)
510
795
  ```
511
796
 
512
797
  ### Utilities
@@ -594,23 +879,6 @@ const dbRule = inject(database, createDbRule)
594
879
  | `withDebug` | Debug logging | `withDebug(rule, { name: "Validation" })` |
595
880
  | `tap` | Side effects | `tap((input, result) => log(result))` |
596
881
 
597
- ## Best Practices
598
-
599
- 1. **Small Rules** - Keep each rule focused
600
- 2. **Pure Functions** - Avoid side effects in rules
601
- 3. **Memoize** - Cache expensive validations
602
- 4. **Type Narrowing** - Use `requireContextRule` for safety
603
- 5. **Instrument** - Add metrics in production
604
-
605
- ```mermaid
606
- graph TD
607
- A[Input] --> B{Valid?}
608
- B -->|Yes| C[Process]
609
- B -->|No| D[Collect Errors]
610
- C --> E[Output]
611
- D --> E
612
- ```
613
-
614
882
  ## Contributing
615
883
 
616
884
  1. Fork the repository
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var E=n=>n!==void 0;var a=n=>({status:"failed",error:n});var s=()=>({status:"passed"});var d=(n,e,t)=>{let o=t||(u=>u!==void 0);return async(u,T)=>o(T)?e(u,T):a(n)};var A=(n,e)=>async t=>{try{let r=await n(t);return e(t,r)}catch(r){let o=r instanceof Error?r.message:"Context loading failed";return a(o)}};var m=(n,e,t)=>{let r={fixed:()=>t,linear:o=>t*o,exponential:o=>t*2**(o-1)};if(!n)return r.fixed(e);if(typeof n=="string"){let o=r[n];return o?o(e):t}return typeof n=="function"?n(e):r.fixed(e)};var B=(n,e={})=>async(t,r)=>{let o=e!=null&&e.cloneContext?structuredClone(r):r,T=(await Promise.all(n.map(p=>p(t,o)))).flatMap(p=>p.status==="failed"?[p.error]:[]);return T.length>0?a(T):s()};var v=(n,e,t)=>async(r,o)=>await n(r,o)?e(r,o):t?t(r,o):s();var x=n=>typeof n=="function",S=(n,e,t)=>async(r,o)=>{let u=await n(r,o),T=e[u];return T?T(r,o):t!==void 0?x(t)?t(r,o):a(t):a(`No matching rule for key: ${String(u)}`)};var K=(n,e)=>async(t,r)=>(await n(t,r)).status==="passed"?a(e):s();var J=(...n)=>async(e,t)=>{let r=[];if(!n||n.length===0)return s();for(let o of n){let u=await o(e,t);if(u.status==="passed")return s();r.push(u.error);}return a(r)};var V=(n,e)=>async(t,r)=>await n(t)?s():e(t,r);var j=(n,e)=>async(t,r)=>await n(t)?e(t,r):s();var $=(n,e,t={})=>async(r,o)=>{let u=await n(r,o);return u.status==="failed"&&(!t.onlyFallbackOn||t.onlyFallbackOn(u.error))?e(r,o):u};var U=(n,e)=>{let t=e(n);return r=>t(r)};var Z=(n,e)=>async(t,r)=>{let o=await n(t,r);return o.status==="failed"?a(e(o.error)):s()};var tr=(n,e,t={})=>{let r=new Map;return async(o,u)=>{let T=e(o),p=Date.now();if(t.ttl)for(let[l,f]of r)p-f.timestamp>t.ttl&&r.delete(l);if(t.maxSize&&r.size>=t.maxSize){let l=r.keys().next().value;l&&r.delete(l);}if(r.has(T))return r.get(T).result;let i=n(o,u);return r.set(T,{result:i,timestamp:p}),i instanceof Promise&&i.catch(()=>r.delete(T)),i}};function or(n,e,t){return async(r,o)=>{let u=n(r),T=u!==void 0?u:t;return T===void 0?a("Missing required value"):e(T,o)}}var Tr=n=>e=>async(t,r)=>{let o=await e(t,r);try{await n(t,o,r);}catch(u){console.error("Tap effect failed:",u);}return o};var sr=(n,e)=>{let t=typeof e=="string"?{name:e}:e;return async(r,o)=>{var p,i,l;let u=performance.now(),T=t.name||n.name||"anonymous_rule";try{(p=t.onStart)==null||p.call(t,r,o);let f=await n(r,o),c=performance.now()-u;return (i=t.onEnd)==null||i.call(t,r,f,o,{ruleName:T,duration:c,startTime:u}),f}catch(f){let c=performance.now()-u;throw (l=t.onError)==null||l.call(t,f,r,o,c),f}}};var ir=(n,e={})=>{let{attempts:t=3,delayMs:r=100,shouldRetry:o=()=>true}=e;return async(u,T)=>{let p;for(let i=1;i<=t;i++){try{let l=await n(u,T);if(l.status==="passed")return l;p=l.error;}catch(l){p=l;}if(!o(p,i))return a(p);if(i<t&&r>0){let l=m(e==null?void 0:e.retryStrategy,i,r);await new Promise(f=>setTimeout(f,l));}}return a("MAX_RETRIES_EXCEEDED")}};var mr=(n,e,t)=>async(r,o)=>{let u=new Promise(T=>setTimeout(()=>T(a(t)),e));return Promise.race([n(r,o),u])};var Cr=(n,e={})=>async(t,r)=>{let o=e!=null&&e.cloneContext?structuredClone(r):r;for(let u=n.length-1;u>=0;u--){let T=await n[u](t,o);if(T.status==="failed")return T}return s()};var gr=(n,e={})=>async(t,r)=>{let o=e!=null&&e.cloneContext?structuredClone(r):r;for(let u of n){let T=await u(t,o);if(T.status==="failed")return T}return s()};function yr(n,...e){return e.reduce((t,r)=>r(t),n)}exports.calculateDelay=m;exports.composeRules=Cr;exports.every=B;exports.fail=a;exports.hasContext=E;exports.ifElse=v;exports.inject=U;exports.mapError=Z;exports.match=S;exports.not=K;exports.oneOf=J;exports.pass=s;exports.pipe=yr;exports.pipeRules=gr;exports.requireContextRule=d;exports.tap=Tr;exports.unless=V;exports.validateField=or;exports.when=j;exports.withDebug=sr;exports.withFallback=$;exports.withLazyContext=A;exports.withMemoize=tr;exports.withRetry=ir;exports.withTimeout=mr;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var w=e=>e!==void 0;var l=e=>({status:"failed",error:e});var p=()=>({status:"passed"});var k=(e,t,r)=>{let o=r||(a=>a!==void 0);return async(a,s)=>o(s)?t(a,s):l(e)};var D=(e,t)=>async r=>{try{let n=await e(r);return t(r,n)}catch(n){let o=n instanceof Error?n.message:"Context loading failed";return l(o)}};var C=(e,t,r)=>{let n={fixed:()=>r,linear:o=>r*o,exponential:o=>r*2**(o-1)};if(!e)return n.fixed(t);if(typeof e=="string"){let o=n[e];return o?o(t):r}return typeof e=="function"?e(t):n.fixed(t)};var f=(e,t)=>(t==null?void 0:t.errorHandlingMode)==="unsafe"?e:x(e,t==null?void 0:t.errorTransform);var m=(e,t)=>{var n;return (t==null?void 0:t.errorHandlingMode)==="unsafe"?e:(n=e||[])==null?void 0:n.map(o=>x(o,t==null?void 0:t.errorTransform))};var d=e=>{var t;if(!e)return {};try{return JSON.parse(JSON.stringify(e))}catch(r){return console.warn(`Clone failed for ${(t=e==null?void 0:e.constructor)==null?void 0:t.name}, returning empty object`,r),{}}};var g=e=>{var t;if(!e)return {};try{return {...e}}catch(r){return console.warn(`Clone failed for ${(t=e==null?void 0:e.constructor)==null?void 0:t.name}, returning empty object`,r),{}}};var R=e=>{let t=typeof structuredClone!="undefined";return e.cloneStrategy==="shallow"?g:e.cloneStrategy==="structured"&&t?structuredClone:d};var X=(e,t={})=>async(r,n)=>{let o=R(t),a=t!=null&&t.cloneContext?o(n):n,s=m(e,t),T=(await Promise.all(s.map(i=>i(r,a)))).flatMap(i=>i.status==="failed"?[i.error]:[]);return T.length>0?l(T):p()};var L=(e,t)=>{let r=t(e);return n=>r(n)};var W=(e,t)=>async(r,n)=>{let o=await e(r,n);return o.status==="failed"?l(t(o.error)):p()};var j=e=>async(t,r)=>{try{await e(t,r);}catch(n){console.error("Tap effect failed: ",n);}return p()};var er=(e,t)=>r=>async(n,o)=>{let s=await f(r,t)(n,o);try{await e(n,s,o);}catch(u){console.error("Tap effect failed:",u);}return s};function ur(e,t,r,n){return async(o,a)=>{let s=e(o),u=s!==void 0?s:r,T=f(t,n);return u===void 0?l("Missing required value"):T(u,a)}}var sr=(e,t)=>{let r=typeof t=="string"?{name:t}:t;return async(n,o)=>{var u,T,i;let a=performance.now(),s=r.name||e.name||"anonymous_rule";try{(u=r.onStart)==null||u.call(r,n,o);let c=await e(n,o),y=performance.now()-a;return (T=r.onEnd)==null||T.call(r,n,c,o,{ruleName:s,duration:y,startTime:a}),c}catch(c){let y=performance.now()-a;throw (i=r.onError)==null||i.call(r,c,n,o,y),c}}};var ir=(e,t,r={})=>{let n=new Map;return async(o,a)=>{let s=t(o),u=Date.now();if(r.ttl)for(let[c,y]of n)u-y.timestamp>r.ttl&&n.delete(c);if(r.maxSize&&n.size>=r.maxSize){let c=n.keys().next().value;c&&n.delete(c);}if(n.has(s))return n.get(s).result;let i=f(e,r)(o,a);return n.set(s,{result:i,timestamp:u}),i instanceof Promise&&i.catch(()=>n.delete(s)),i}};var cr=(e,t={})=>{let{attempts:r=3,delayMs:n=100,shouldRetry:o=()=>true}=t;return async(a,s)=>{let u;for(let T=1;T<=r;T++){try{let i=await e(a,s);if(i.status==="passed")return i;u=i.error;}catch(i){u=i;}if(!o(u,T))return l(u);if(T<r&&n>0){let i=C(t==null?void 0:t.retryStrategy,T,n);await new Promise(c=>setTimeout(c,i));}}return l("MAX_RETRIES_EXCEEDED")}};var x=(e,t=r=>typeof r=="object"&&r!==null?r:r instanceof Error?r.message:String(r))=>async(r,n)=>{try{let o=await e(r,n);return o&&typeof o=="object"&&"status"in o?o:l(t(new Error("Invalid rule - did not return RuleResult")))}catch(o){return l(t(o))}};var E=(e,t=r=>typeof r=="object"&&r!==null?r:r instanceof Error?r.message:String(r))=>async(r,n)=>{try{let o=await e(r,n);return typeof o=="boolean"?{status:"passed",value:o}:{status:"failed",error:t(new Error(`Predicate must return boolean, got ${typeof o}`))}}catch(o){return {status:"failed",error:t(o)}}};var Cr=(e,t,r,n)=>async(o,a)=>{let s=f(e,n),u=new Promise(T=>setTimeout(()=>T(l(r)),t));return Promise.race([s(o,a),u])};var wr=(e,t,r,n)=>async(o,a)=>{let u=await E(e,n==null?void 0:n.predicateErrorTransform)(o,a);if(u.status==="failed")return l(u.error);let[T,i]=m([t,r],n);return u.value?T(o,a):r?i(o,a):p()};var I=e=>typeof e=="function",Or=(e,t,r,n)=>async(o,a)=>{let s=await e(o,a),u=t[s];return u?f(u,n)(o,a):r!==void 0?I(r)?f(r,n)(o,a):l(r):l(`No matching rule for key: ${String(s)}`)};var zr=(e,t,r)=>async(n,o)=>(await f(e,r)(n,o)).status==="passed"?l(t):p();var Fr=(e,t)=>async(r,n)=>{let o=m(e,t),a=[];if(!e||e.length===0)return p();for(let s of o){let u=await s(r,n);if(u.status==="passed")return p();a.push(u.error);}return l(a)};var br=(e,t,r)=>async(n,o)=>{let a=f(t,r),u=await E(e,r==null?void 0:r.predicateErrorTransform)(n,o);return u.status==="failed"?l(u.error):u.value?p():a(n,o)};var Kr=(e,t,r)=>async(n,o)=>{let a=f(t,r),u=await E(e,r==null?void 0:r.predicateErrorTransform)(n,o);return u.status==="failed"?l(u.error):u.value?a(n,o):p()};var _r=(e,t,r={})=>async(n,o)=>{let[a,s]=m([e,t]),u=await a(n,o);return u.status==="failed"&&(!r.onlyFallbackOn||r.onlyFallbackOn(u.error))?s(n,o):u};var Ur=(e,t={})=>async(r,n)=>{let o=R(t),a=t!=null&&t.cloneContext?o(n):n,s=m(e);for(let u=s.length-1;u>=0;u--){let T=await s[u](r,a);if(T.status==="failed")return T}return p()};var Zr=(e,t={})=>async(r,n)=>{let o=R(t),a=t!=null&&t.cloneContext?o(n):n,s=m(e);for(let u of s){let T=await u(r,a);if(T.status==="failed")return T}return p()};function rt(e,...t){return t.reduce((r,n)=>n(r),e)}exports.calculateDelay=C;exports.composeRules=Ur;exports.every=X;exports.fail=l;exports.getNormalizedRule=f;exports.getNormalizedRules=m;exports.hasContext=w;exports.ifElse=wr;exports.inject=L;exports.mapError=W;exports.match=Or;exports.not=zr;exports.oneOf=Fr;exports.pass=p;exports.pipe=rt;exports.pipeRules=Zr;exports.requireContextRule=k;exports.tap=j;exports.unless=br;exports.validateField=ur;exports.when=Kr;exports.withDebug=sr;exports.withFallback=_r;exports.withLazyContext=D;exports.withMemoize=ir;exports.withRetry=cr;exports.withSafeError=x;exports.withSafePredicate=E;exports.withTap=er;exports.withTimeout=Cr;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map