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
package/dist/index.d.cts CHANGED
@@ -1,10 +1,69 @@
1
+ type Prettify<T> = {
2
+ [K in keyof T]: T[K];
3
+ } & {};
4
+
5
+ /**
6
+ * Configuration options for error handling behavior in rule combinators
7
+ * @template TError - The type of the error that will be caught and transformed (when safe)
8
+ *
9
+ * @property errorHandling - Determines how the combinator handles thrown errors
10
+ * - "safe": (default) Catches errors and converts them to failed RuleResults
11
+ * - "unsafe": Lets errors propagate normally (for performance-critical cases)
12
+ *
13
+ * @property errorTransform - Optional custom error transformation function
14
+ * Only used when errorHandling="safe". Allows customizing how thrown errors
15
+ * are converted to the rule's error type.
16
+ *
17
+ * @example
18
+ * // Basic usage with default safe handling
19
+ * const rule = every([rule1, rule2], { errorHandling: "safe" });
20
+ *
21
+ * @example
22
+ * // Unsafe mode for performance
23
+ * const rule = every([rule1, rule2], { errorHandling: "unsafe" });
24
+ *
25
+ * @example
26
+ * // Custom error transformation
27
+ * const rule = every([rule1, rule2], {
28
+ * errorHandling: "safe",
29
+ * errorTransform: (err) => ({
30
+ * code: 500,
31
+ * message: String(err)
32
+ * })
33
+ * });
34
+ */
35
+ type RuleSafetyOptions<TError = unknown> = {
36
+ errorHandlingMode?: "safe" | "unsafe";
37
+ errorTransform?: (error: unknown) => TError;
38
+ };
39
+
1
40
  /**
2
41
  * Options for rule composition functions.
3
42
  * @property cloneContext - Whether to clone the context for each rule
43
+ * @property cloneStrategy - Which strategy to use when cloning the context
44
+ * @property errorHandling - Determines how the combinator handles thrown errors
45
+ * - "safe": (default) Catches errors and converts them to failed RuleResults
46
+ * - "unsafe": Lets errors propagate normally (for performance-critical cases)
47
+ *
48
+ * @property errorTransform - Optional custom error transformation function
49
+ * Only used when errorHandling="safe". Allows customizing how thrown errors
50
+ * are converted to the rule's error type.
51
+ *
52
+ *
53
+ * @warn
54
+ * - Cloning behavior follows this priority:
55
+ * 1. Uses shallowClone if options.cloneStrategy = "shallow"
56
+ * 2. Uses structuredClone if available and options.cloneStrategy = "structured"
57
+ * 3. Falls back to JSON clone otherwise
58
+ * - structuredClone requires Node 17+ or modern browsers
59
+ * - JSON clone will lose special types (Date, Map, etc.)
60
+ * - All clones convert undefined/null to empty object {}
61
+ * - Circular references fail silently in JSON clone mode
4
62
  */
5
- type CompositionOptions = {
63
+ type CompositionOptions<TError = string> = Prettify<{
6
64
  cloneContext?: boolean;
7
- };
65
+ cloneStrategy?: "shallow" | "json" | "structured";
66
+ } & RuleSafetyOptions<TError>>;
8
67
 
9
68
  /**
10
69
  * Represents the result of a rule evaluation.
@@ -68,6 +127,43 @@ type DebugOptions<TInput, TError, TContext> = {
68
127
  */
69
128
  type Rule<TInput, TError = string, TContext = unknown> = (input: TInput, context?: TContext) => Promise<RuleResult<TError>> | RuleResult<TError>;
70
129
 
130
+ /**
131
+ * A predicate function that evaluates an input and returns a boolean result.
132
+ * Can be synchronous or asynchronous.
133
+ */
134
+ type Predicate<TInput, TContext> = (input: TInput, context?: TContext) => boolean | Promise<boolean>;
135
+
136
+ /**
137
+ * Represents the result of a predicate evaluation.
138
+ * @template TError - The type of the error (defaults to string)
139
+ * @example
140
+ * // Passed result, true value
141
+ * const passed: PredicateResult = { status: "passed", value: true };
142
+ *
143
+ * // Passed result, false value
144
+ * const passed: PredicateResult = { status: "passed", value: false };
145
+ *
146
+ *
147
+ * // Failed result
148
+ * const failed: PredicateResult = {
149
+ * status: "failed",
150
+ * error: "Validation failed"
151
+ * };
152
+ */
153
+ type PredicateResult<TError = string> = {
154
+ readonly status: "passed";
155
+ value: boolean;
156
+ } | {
157
+ readonly status: "failed";
158
+ readonly error: TError;
159
+ };
160
+
161
+ /**
162
+ * A predicate function that evaluates an input and returns a PredicateResult.
163
+ * Can be synchronous or asynchronous.
164
+ */
165
+ type PredicateSafe<TInput, TError, TContext> = (input: TInput, context?: TContext) => PredicateResult<TError> | Promise<PredicateResult<TError>>;
166
+
71
167
  /**
72
168
  * Composes multiple rules into a single rule that runs them all and collects all errors.
73
169
  * @template TInput - The type of the input to validate
@@ -76,6 +172,11 @@ type Rule<TInput, TError = string, TContext = unknown> = (input: TInput, context
76
172
  * @param rules - Array of rules to compose
77
173
  * @param options - Configuration options
78
174
  * @param options.cloneContext - Whether to clone the context for each rule (default: false)
175
+ * @param options.cloneStrategy -Which strategy to use when cloning the context
176
+ * @param options.errorHandlingMode - Determines how errors are handled:
177
+ * - 'safe': (default) Converts thrown errors to validation failures
178
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
179
+ * @param options.errorTransform - Custom transformation for caught errors
79
180
  * @returns A new rule that returns all errors from all failing rules
80
181
  * @example
81
182
  * const rule = every([
@@ -91,8 +192,42 @@ type Rule<TInput, TError = string, TContext = unknown> = (input: TInput, context
91
192
  * @caveats
92
193
  * - Rules are executed in parallel (using Promise.all)
93
194
  * - All rules are executed even if some fail
195
+ * - Cloning behavior follows this priority:
196
+ * 1. Uses shallowClone if options.shallowClone = true
197
+ * 2. Uses structuredClone if available and options.structuredClone = true
198
+ * 3. Falls back to JSON clone otherwise
94
199
  */
95
- declare const every: <TInput, TError = string, TContext = unknown>(rules: Rule<TInput, TError, TContext>[], options?: CompositionOptions) => Rule<TInput, TError[], TContext>;
200
+ declare const every: <TInput, TError = string, TContext = unknown>(rules: Rule<TInput, TError, TContext>[], options?: CompositionOptions<TError>) => Rule<TInput, TError[], TContext>;
201
+
202
+ /**
203
+ * Configuration options for error handling behavior in rule combinators
204
+ * @template TError - The type of the error that will be caught and transformed (when safe)
205
+ *
206
+ *
207
+ * @property predicateErrorTransform - Optional custom error transformation function
208
+ * Only used when errorHandling="safe". Allows customizing how thrown errors
209
+ * are converted to the rule's error type.
210
+ *
211
+ *
212
+ * @example
213
+ * // Custom error transformation
214
+ * const rule = ifElse(
215
+ * (user) => user.age >= 18,
216
+ * validateAdultAccount,
217
+ * validateMinorAccount,
218
+ * {
219
+ * predicateErrorTransform: (err) => ({
220
+ * code: 500,
221
+ * message: String(err)
222
+ * })
223
+ * }
224
+ * );
225
+ */
226
+ type PredicateSafetyOptions<TError = unknown> = {
227
+ predicateErrorTransform?: (error: unknown) => TError;
228
+ };
229
+
230
+ type SafetyOptions<TError = unknown> = Prettify<RuleSafetyOptions<TError> & PredicateSafetyOptions<TError>>;
96
231
 
97
232
  /**
98
233
  * Conditionally executes one of two rules based on a predicate
@@ -102,21 +237,27 @@ declare const every: <TInput, TError = string, TContext = unknown>(rules: Rule<T
102
237
  * @param predicate - Function that determines which rule to execute
103
238
  * @param ifRule - Rule to execute when predicate returns true
104
239
  * @param elseRule - Rule to execute when predicate returns false (optional)
240
+ * @param options - Configuration for error handling and predicate safety
241
+ * @param options.errorHandlingMode - Determines how errors are handled:
242
+ * - 'safe': (default) Converts thrown errors to validation failures
243
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
244
+ * @param options.errorTransform - Custom transformation for caught errors
245
+ * @param options.predicateErrorTransform - Special error handler for predicate failures
105
246
  * @returns A new rule that conditionally executes one of two rules
106
247
  * @example
107
- * const rule = branch(
248
+ * const rule = ifElse(
108
249
  * (user) => user.age >= 18,
109
250
  * validateAdultAccount,
110
251
  * validateMinorAccount
111
252
  * );
112
253
  *
113
254
  * // Without elseRule (passes when predicate is false)
114
- * const adultOnlyRule = branch(
255
+ * const adultOnlyRule = ifElse(
115
256
  * (user) => user.age >= 18,
116
257
  * validateAdultAccount
117
258
  * );
118
259
  */
119
- declare const ifElse: <TInput, TError = string, TContext = unknown>(predicate: (input: TInput, context?: TContext) => boolean | Promise<boolean>, ifRule: Rule<TInput, TError, TContext>, elseRule?: Rule<TInput, TError, TContext>) => Rule<TInput, TError, TContext>;
260
+ declare const ifElse: <TInput, TError = string, TContext = unknown>(predicate: Predicate<TInput, TContext>, ifRule: Rule<TInput, TError, TContext>, elseRule?: Rule<TInput, TError, TContext>, options?: SafetyOptions<TError>) => Rule<TInput, TError, TContext>;
120
261
 
121
262
  /**
122
263
  * Pattern-matching combinator that selects a rule based on a key extracted from input.
@@ -127,6 +268,11 @@ declare const ifElse: <TInput, TError = string, TContext = unknown>(predicate: (
127
268
  * @param accessor - Function that extracts the match key from input
128
269
  * @param cases - Object mapping keys to their corresponding rules
129
270
  * @param defaultCase - Optional default rule or error when no match is found
271
+ * @param options - Configuration for error handling safety
272
+ * @param options.errorHandlingMode - Determines how errors are handled:
273
+ * - 'safe': (default) Converts thrown errors to validation failures
274
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
275
+ * @param options.errorTransform - Custom transformation for caught errors
130
276
  * @returns A new rule that executes the matching case's rule
131
277
  * @example
132
278
  * // Basic usage with string error type
@@ -171,7 +317,7 @@ declare const ifElse: <TInput, TError = string, TContext = unknown>(predicate: (
171
317
  * - All case rules must have compatible input/context types
172
318
  * - For conditional branching (true/false), consider using `branch` instead
173
319
  */
174
- declare const match: <TInput, TError = string, TContext = unknown, TKey extends string | number | symbol = string>(accessor: (input: TInput, context?: TContext) => TKey | Promise<TKey>, cases: Record<TKey, Rule<TInput, TError, TContext>>, defaultCase?: Rule<TInput, TError, TContext> | TError) => Rule<TInput, TError, TContext>;
320
+ declare const match: <TInput, TError = string, TContext = unknown, TKey extends string | number | symbol = string>(accessor: (input: TInput, context?: TContext) => TKey | Promise<TKey>, cases: Record<TKey, Rule<TInput, TError, TContext>>, defaultCase?: Rule<TInput, TError, TContext> | TError, options?: RuleSafetyOptions<TError>) => Rule<TInput, TError, TContext>;
175
321
 
176
322
  /**
177
323
  * Inverts the logic of a rule - passes when original fails and vice versa.
@@ -179,6 +325,11 @@ declare const match: <TInput, TError = string, TContext = unknown, TKey extends
179
325
  * @template TError - The type of the error (defaults to string)
180
326
  * @param rule - The rule to invert
181
327
  * @param error - The error to return when original rule passes
328
+ * @param options - Configuration for error handling safety
329
+ * @param options.errorHandlingMode - Determines how errors are handled:
330
+ * - 'safe': (default) Converts thrown errors to validation failures
331
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
332
+ * @param options.errorTransform - Custom transformation for caught errors
182
333
  * @returns A new rule with inverted logic
183
334
  * @example
184
335
  * const isNotAdmin = not(isAdmin, "User must not be admin");
@@ -186,7 +337,7 @@ declare const match: <TInput, TError = string, TContext = unknown, TKey extends
186
337
  * - The original rule's error is discarded when it fails
187
338
  * - Always uses the provided error when original passes
188
339
  */
189
- declare const not: <TInput, TError = string>(rule: Rule<TInput, TError>, error: TError) => Rule<TInput, TError>;
340
+ declare const not: <TInput, TError = string>(rule: Rule<TInput, TError>, error: TError, options?: RuleSafetyOptions<TError>) => Rule<TInput, TError>;
190
341
 
191
342
  /**
192
343
  * Creates a rule that passes if any of the provided rules pass (short-circuiting).
@@ -194,6 +345,11 @@ declare const not: <TInput, TError = string>(rule: Rule<TInput, TError>, error:
194
345
  * @template TError - The type of the error (defaults to string)
195
346
  * @template TContext - The type of the context object (optional)
196
347
  * @param rules - Rules to try (in order)
348
+ * @param options - Configuration for error handling
349
+ * @param options.errorHandlingMode - Determines how errors are handled:
350
+ * - 'safe': (default) Converts thrown errors to validation failures
351
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
352
+ * @param options.errorTransform - Custom transformation for caught errors
197
353
  * @returns A rule that passes if any rule passes, or fails with all errors
198
354
  * @example
199
355
  * const rule = oneOf(
@@ -205,7 +361,7 @@ declare const not: <TInput, TError = string>(rule: Rule<TInput, TError>, error:
205
361
  * - Rules are executed in sequence until one passes
206
362
  * - Returns all errors if all rules fail
207
363
  */
208
- declare const oneOf: <TInput, TError = string, TContext = unknown>(...rules: Rule<TInput, TError, TContext>[]) => Rule<TInput, TError[], TContext>;
364
+ declare const oneOf: <TInput, TError = string, TContext = unknown>(rules: Rule<TInput, TError, TContext>[], options?: RuleSafetyOptions<TError>) => Rule<TInput, TError[], TContext>;
209
365
 
210
366
  /**
211
367
  * Executes a rule only if the predicate returns false.
@@ -214,6 +370,12 @@ declare const oneOf: <TInput, TError = string, TContext = unknown>(...rules: Rul
214
370
  * @template TContext - The type of the context object (optional)
215
371
  * @param predicate - Condition to check
216
372
  * @param rule - Rule to execute when predicate is false
373
+ * @param options - Configuration for error handling and predicate safety
374
+ * @param options.errorHandlingMode - Determines how errors are handled:
375
+ * - 'safe': (default) Converts thrown errors to validation failures
376
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
377
+ * @param options.errorTransform - Custom transformation for caught errors
378
+ * @param options.predicateErrorTransform - Special error handler for predicate failures
217
379
  * @returns A rule that conditionally executes based on the predicate
218
380
  * @example
219
381
  * const rule = unless(
@@ -224,7 +386,7 @@ declare const oneOf: <TInput, TError = string, TContext = unknown>(...rules: Rul
224
386
  * - Opposite behavior of `when`
225
387
  * - Automatically passes when predicate is true
226
388
  */
227
- declare const unless: <TInput, TError = string, TContext = unknown>(predicate: (input: TInput) => Promise<boolean> | boolean, rule: Rule<TInput, TError, TContext>) => Rule<TInput, TError, TContext>;
389
+ declare const unless: <TInput, TError = string, TContext = unknown>(predicate: Predicate<TInput, TContext>, rule: Rule<TInput, TError, TContext>, options?: SafetyOptions<TError>) => Rule<TInput, TError, TContext>;
228
390
 
229
391
  /**
230
392
  * Conditionally executes a rule based on a predicate.
@@ -233,6 +395,12 @@ declare const unless: <TInput, TError = string, TContext = unknown>(predicate: (
233
395
  * @template TError - The type of the error (defaults to string)
234
396
  * @param predicate - Function that determines whether to execute the rule
235
397
  * @param rule - Rule to execute when predicate returns true
398
+ * @param options - Configuration for error handling and predicate safety
399
+ * @param options.errorHandlingMode - Determines how errors are handled:
400
+ * - 'safe': (default) Converts thrown errors to validation failures
401
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
402
+ * @param options.errorTransform - Custom transformation for caught errors
403
+ * @param options.predicateErrorTransform - Special error handler for predicate failures
236
404
  * @returns A new rule that conditionally executes the input rule
237
405
  * @example
238
406
  * const rule = when(
@@ -243,7 +411,7 @@ declare const unless: <TInput, TError = string, TContext = unknown>(predicate: (
243
411
  * - The predicate can be async
244
412
  * - If predicate returns false, the rule automatically passes
245
413
  */
246
- declare const when: <TInput, TError = string>(predicate: (input: TInput) => boolean | Promise<boolean>, rule: Rule<TInput, TError>) => Rule<TInput, TError>;
414
+ declare const when: <TInput, TError = string, TContext = unknown>(predicate: Predicate<TInput, TContext>, rule: Rule<TInput, TError, TContext>, options?: SafetyOptions<TError>) => Rule<TInput, TError, TContext>;
247
415
 
248
416
  /**
249
417
  * Creates a rule that falls back to an alternative rule if the main rule fails.
@@ -254,6 +422,10 @@ declare const when: <TInput, TError = string>(predicate: (input: TInput) => bool
254
422
  * @param fallbackRule - Rule to execute if main rule fails
255
423
  * @param options - Configuration options
256
424
  * @param options.onlyFallbackOn - Predicate to conditionally enable fallback
425
+ * @param options.errorHandlingMode - Determines how errors are handled:
426
+ * - 'safe': (default) Converts thrown errors to validation failures
427
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
428
+ * @param options.errorTransform - Custom transformation for caught errors
257
429
  * @returns A new composite rule
258
430
  * @example
259
431
  * const rule = withFallback(
@@ -262,7 +434,7 @@ declare const when: <TInput, TError = string>(predicate: (input: TInput) => bool
262
434
  * { onlyFallbackOn: err => err.code !== 'FATAL' }
263
435
  * );
264
436
  */
265
- declare const withFallback: <TInput, TError, TContext>(mainRule: Rule<TInput, TError, TContext>, fallbackRule: Rule<TInput, TError, TContext>, options?: {
437
+ declare const withFallback: <TInput, TError, TContext>(mainRule: Rule<TInput, TError, TContext>, fallbackRule: Rule<TInput, TError, TContext>, options?: RuleSafetyOptions<TError> & {
266
438
  onlyFallbackOn?: (error: TError) => boolean;
267
439
  }) => Rule<TInput, TError, TContext>;
268
440
 
@@ -310,31 +482,43 @@ declare const inject: <TInput, TError, TDep>(dependency: TDep, rule: (dep: TDep)
310
482
  declare const mapError: <TInput, TError, TNewError>(rule: Rule<TInput, TError>, transform: (error: TError) => TNewError) => Rule<TInput, TNewError>;
311
483
 
312
484
  /**
313
- * Creates a memoized version of a rule that caches results based on input keys.
485
+ * Creates a standalone tap effect for use in composition pipelines
486
+ * @template TInput - Input type
487
+ * @template TError - Error type
488
+ * @template TContext - Context type
489
+ * @param effect - Side effect function receiving (input, context)
490
+ * @returns A rule that passes through input unchanged
491
+ * @example
492
+ * pipeRules([
493
+ * tap((input) => console.log('Processing:', input)),
494
+ * validateInput
495
+ * ])
496
+ */
497
+ declare const tap: <TInput, TError = string, TContext = unknown>(effect: (input: TInput, context?: TContext) => Promise<void> | void) => Rule<TInput, TError, TContext>;
498
+
499
+ /**
500
+ * Creates a rule wrapper that performs side effects without modifying the result.
314
501
  * @template TInput - The type of the input to validate
315
502
  * @template TError - The type of the error (defaults to string)
316
503
  * @template TContext - The type of the context object (optional)
317
- * @param rule - The rule to memoize
318
- * @param keyFn - Function that generates a cache key from the input
319
- * @param options - Memoization options
320
- * @param options.ttl - Time-to-live for cache entries in milliseconds
321
- * @param options.maxSize - Maximum number of entries to keep in cache
322
- * @returns A memoized version of the rule
504
+ * @param effect - Side effect function receiving input, result and context
505
+ * @param options - Configuration for error handling safety
506
+ * @param options.errorHandlingMode - Determines how errors are handled:
507
+ * - 'safe': (default) Converts thrown errors to validation failures
508
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
509
+ * @param options.errorTransform - Custom transformation for caught errors
510
+ * @returns A function that wraps a rule with the tap effect
323
511
  * @example
324
- * const memoizedRule = withMemoize(
325
- * expensiveValidationRule,
326
- * (input) => input.id,
327
- * { ttl: 60000, maxSize: 100 }
328
- * );
512
+ * const withLogging = tap((input, result) => {
513
+ * console.log(`Validation result for ${input}:`, result);
514
+ * });
515
+ *
516
+ * const rule = withLogging(validateInput);
329
517
  * @caveats
330
- * - Context changes don't invalidate cache by default
331
- * - Cache cleanup happens during rule execution
332
- * - Rejected promises are automatically evicted from cache
518
+ * - Errors in the effect are caught and logged but don't affect rule execution
519
+ * - Doesn't modify the rule's result
333
520
  */
334
- declare const withMemoize: <TInput, TError = string, TContext = unknown>(rule: Rule<TInput, TError, TContext>, keyFn: (input: TInput) => string, options?: {
335
- ttl?: number;
336
- maxSize?: number;
337
- }) => Rule<TInput, TError, TContext>;
521
+ declare const withTap: <TInput, TError = string, TContext = unknown>(effect: (input: TInput, result: RuleResult<TError>, context?: TContext) => Promise<void> | void, options?: RuleSafetyOptions<TError>) => ((rule: Rule<TInput, TError, TContext>) => Rule<TInput, TError, TContext>);
338
522
 
339
523
  /**
340
524
  * Creates a rule that extracts a value using a getter function and validates it.
@@ -345,6 +529,11 @@ declare const withMemoize: <TInput, TError = string, TContext = unknown>(rule: R
345
529
  * @param getter - Function that extracts the value from input
346
530
  * @param rule - Rule to apply to the extracted value
347
531
  * @param defaultValue - Optional default value if getter returns undefined
532
+ * @param options - Configuration for error handling safety
533
+ * @param options.errorHandlingMode - Determines how errors are handled:
534
+ * - 'safe': (default) Converts thrown errors to validation failures
535
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
536
+ * @param options.errorTransform - Custom transformation for caught errors
348
537
  * @returns A new rule that validates the extracted value
349
538
  * @example
350
539
  * const validateName = validateField(
@@ -371,26 +560,7 @@ declare const withMemoize: <TInput, TError = string, TContext = unknown>(rule: R
371
560
  * - Defaults are applied before rule execution (the rule sees the default value)
372
561
  * - Default values aren't type-checked against potentially undefined returns
373
562
  */
374
- declare function validateField<TInput, TValue, TError = string, TContext = unknown>(getter: (input: TInput) => TValue | undefined, rule: Rule<TValue, TError, TContext>, defaultValue?: TValue): Rule<TInput, TError, TContext>;
375
-
376
- /**
377
- * Creates a rule wrapper that performs side effects without modifying the result.
378
- * @template TInput - The type of the input to validate
379
- * @template TError - The type of the error (defaults to string)
380
- * @template TContext - The type of the context object (optional)
381
- * @param effect - Side effect function receiving input, result and context
382
- * @returns A function that wraps a rule with the tap effect
383
- * @example
384
- * const withLogging = tap((input, result) => {
385
- * console.log(`Validation result for ${input}:`, result);
386
- * });
387
- *
388
- * const rule = withLogging(validateInput);
389
- * @caveats
390
- * - Errors in the effect are caught and logged but don't affect rule execution
391
- * - Doesn't modify the rule's result
392
- */
393
- declare const tap: <TInput, TError = string, TContext = unknown>(effect: (input: TInput, result: RuleResult<TError>, context?: TContext) => Promise<void> | void) => ((rule: Rule<TInput, TError, TContext>) => Rule<TInput, TError, TContext>);
563
+ declare function validateField<TInput, TValue, TError = string, TContext = unknown>(getter: (input: TInput) => TValue | undefined, rule: Rule<TValue, TError, TContext>, defaultValue?: TValue, options?: RuleSafetyOptions<TError>): Rule<TInput, TError, TContext>;
394
564
 
395
565
  /**
396
566
  * Wraps a rule with debugging capabilities.
@@ -418,6 +588,39 @@ declare const tap: <TInput, TError = string, TContext = unknown>(effect: (input:
418
588
  */
419
589
  declare const withDebug: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>, options: DebugOptions<TInput, TError, TContext> | string) => Rule<TInput, TError, TContext>;
420
590
 
591
+ /**
592
+ * Creates a memoized version of a rule that caches results based on input keys.
593
+ * @template TInput - The type of the input to validate
594
+ * @template TError - The type of the error (defaults to string)
595
+ * @template TContext - The type of the context object (optional)
596
+ * @param rule - The rule to memoize
597
+ * @param keyFn - Function that generates a cache key from the input
598
+ * @param options - Memoization and safety options
599
+ * @param options.ttl - Time-to-live for cache entries in milliseconds
600
+ * @param options.maxSize - Maximum number of entries to keep in cache
601
+ * @param options.errorHandlingMode - Determines how errors are handled:
602
+ * - 'safe': (default) Converts thrown errors to validation failures
603
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
604
+ * @param options.errorTransform - Custom transformation for caught errors
605
+ * @returns A memoized version of the rule
606
+ * @example
607
+ * const memoizedRule = withMemoize(
608
+ * expensiveValidationRule,
609
+ * (input) => input.id,
610
+ * { ttl: 60000, maxSize: 100 }
611
+ * );
612
+ * @caveats
613
+ * - Context changes don't invalidate cache by default
614
+ * - Cache cleanup happens during rule execution
615
+ * - Rejected promises are automatically evicted from cache
616
+ * - Successful results obey TTL rules
617
+ * - Cache is shared across rule instances
618
+ */
619
+ declare const withMemoize: <TInput, TError = string, TContext = unknown>(rule: Rule<TInput, TError, TContext>, keyFn: (input: TInput) => string, options?: {
620
+ ttl?: number;
621
+ maxSize?: number;
622
+ } & RuleSafetyOptions<TError>) => Rule<TInput, TError, TContext>;
623
+
421
624
  type RetryStrategy = "fixed" | "linear" | "exponential" | ((attempt: number) => number);
422
625
  /**
423
626
  * Wraps a rule with retry logic for handling transient failures.
@@ -447,6 +650,60 @@ declare const withRetry: <TInput, TError = string, TContext = unknown>(rule: Rul
447
650
  shouldRetry?: (error: TError | unknown, attempt: number) => boolean;
448
651
  }) => Rule<TInput, TError | "MAX_RETRIES_EXCEEDED", TContext>;
449
652
 
653
+ /**
654
+ * Wraps a rule to catch errors and convert them to failed RuleResults
655
+ * @template TInput - The input type
656
+ * @template TError - The error type (defaults to string)
657
+ * @template TContext - The context type
658
+ * @param rule - The rule to protect
659
+ * @param errorMapper - Optional error transformation logic
660
+ * @returns A protected version of the rule
661
+ * @example
662
+ * // Basic usage with default error handling
663
+ * const safeRule = withSafeError(riskyRule);
664
+ *
665
+ * // With custom error transformation
666
+ * const customSafeRule = withSafeError(riskyRule, e => ({
667
+ * code: 500,
668
+ * message: String(e)
669
+ * }));
670
+ *
671
+ * @caveats
672
+ *
673
+ * - Generic parameters must be explicitly set for custom error types
674
+ * - Doesn't verify error types match TError at runtime
675
+ */
676
+ declare const withSafeError: <TInput, TError = string, TContext = unknown>(rule: Rule<TInput, TError, TContext>, errorTransform?: (error: unknown) => TError) => Rule<TInput, TError, TContext>;
677
+
678
+ /**
679
+ * Wraps a predicate function with error handling and type safety.
680
+ * @template TInput - The input type
681
+ * @template TError - The error type (defaults to string)
682
+ * @template TContext - The context type
683
+ * @param predicate - The predicate function to wrap
684
+ * @param errorTransform - Optional function to transform errors
685
+ * @returns A safe predicate that never throws
686
+ *
687
+ * @example
688
+ * const safePredicate = withSafePredicate(
689
+ * (input: string) => input.length > 5,
690
+ * (err) => `Predicate failed: ${String(err)}`
691
+ * );
692
+ *
693
+ * @caveats
694
+ * **Error Handling Behavior**:
695
+ * - Will catch both synchronous throws and Promise rejections
696
+ * - Errors in the errorTransform itself will propagate (not caught)
697
+ * - The default transformer converts all errors to strings except Error objects
698
+ *
699
+ * **Edge Cases**:
700
+ * - Returns failed result for non-boolean returns (including null/undefined)
701
+ * - Returns failed result for Promise<non-boolean> resolutions
702
+ * - Returns failed result for Promise rejections (transformed via errorTransform)
703
+ * - Returns failed result for thrown non-Error values (like `throw "string"`)
704
+ */
705
+ declare const withSafePredicate: <TInput, TError = string, TContext = unknown>(predicate: Predicate<TInput, TContext>, errorTransform?: (error: unknown) => TError) => PredicateSafe<TInput, TError, TContext>;
706
+
450
707
  /**
451
708
  * Wraps a rule with timeout functionality.
452
709
  * @template TInput - The type of the input to validate
@@ -455,6 +712,11 @@ declare const withRetry: <TInput, TError = string, TContext = unknown>(rule: Rul
455
712
  * @param rule - The rule to wrap with timeout
456
713
  * @param timeoutMs - Timeout duration in milliseconds
457
714
  * @param timeoutError - Error to return if timeout occurs
715
+ * @param options - Configuration for error handling safety
716
+ * @param options.errorHandlingMode - Determines how errors are handled:
717
+ * - 'safe': (default) Converts thrown errors to validation failures
718
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
719
+ * @param options.errorTransform - Custom transformation for caught errors
458
720
  * @returns A new rule that fails with timeoutError if execution takes longer than timeoutMs
459
721
  * @example
460
722
  * const rule = withTimeout(
@@ -466,7 +728,7 @@ declare const withRetry: <TInput, TError = string, TContext = unknown>(rule: Rul
466
728
  * - The original rule's execution isn't aborted when timeout occurs
467
729
  * - Only fails if the rule doesn't complete before timeout, not if it fails before timeout
468
730
  */
469
- declare const withTimeout: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>, timeoutMs: number, timeoutError: TError) => Rule<TInput, TError, TContext>;
731
+ declare const withTimeout: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>, timeoutMs: number, timeoutError: TError, options?: RuleSafetyOptions<TError>) => Rule<TInput, TError, TContext>;
470
732
 
471
733
  /**
472
734
  * Composes multiple rules into a single rule that runs them in right-to-left order (fail-fast).
@@ -478,6 +740,10 @@ declare const withTimeout: <TInput, TError, TContext>(rule: Rule<TInput, TError,
478
740
  * @param rules - Array of rules to compose
479
741
  * @param options - Configuration options
480
742
  * @param options.cloneContext - Whether to clone the context for each rule (default: false)
743
+ * @param options.errorHandlingMode - Determines how errors are handled:
744
+ * - 'safe': (default) Converts thrown errors to validation failures
745
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
746
+ * @param options.errorTransform - Custom transformation for caught errors
481
747
  * @returns A new rule that composes all input rules
482
748
  *
483
749
  * @example
@@ -492,7 +758,10 @@ declare const withTimeout: <TInput, TError, TContext>(rule: Rule<TInput, TError,
492
758
  * @caveats
493
759
  * - Rules are executed from **right to left**
494
760
  * - Rules are executed sequentially (not in parallel)
495
- * - Context clone uses structuredClone from Node.js
761
+ * - Cloning behavior follows this priority:
762
+ * 1. Uses shallowClone if options.shallowClone = true
763
+ * 2. Uses structuredClone if available and options.structuredClone = true
764
+ * 3. Falls back to JSON clone otherwise
496
765
  */
497
766
  declare const composeRules: <TInput, TError = string, TContext = unknown>(rules: Rule<TInput, TError, TContext>[], options?: CompositionOptions) => Rule<TInput, TError, TContext>;
498
767
 
@@ -505,6 +774,10 @@ declare const composeRules: <TInput, TError = string, TContext = unknown>(rules:
505
774
  * @param rules - Array of rules to compose
506
775
  * @param options - Configuration options
507
776
  * @param options.cloneContext - Whether to clone the context for each rule (default: false)
777
+ * @param options.errorHandlingMode - Determines how errors are handled:
778
+ * - 'safe': (default) Converts thrown errors to validation failures
779
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
780
+ * @param options.errorTransform - Custom transformation for caught errors
508
781
  * @returns A new rule that pipes all input rules
509
782
  * @example
510
783
  * const rule = pipeRules([
@@ -517,7 +790,10 @@ declare const composeRules: <TInput, TError = string, TContext = unknown>(rules:
517
790
  * @caveats
518
791
  * - Rules are execute from left to right
519
792
  * - Rules are executed in sequence, not in parallel
520
- * - Context clone uses structuredClone Nodejs implementation
793
+ * - Cloning behavior follows this priority:
794
+ * 1. Uses shallowClone if options.shallowClone = true
795
+ * 2. Uses structuredClone if available and options.structuredClone = true
796
+ * 3. Falls back to JSON clone otherwise
521
797
  */
522
798
  declare const pipeRules: <TInput, TError = string, TContext = unknown>(rules: Rule<TInput, TError, TContext>[], options?: CompositionOptions) => Rule<TInput, TError, TContext>;
523
799
 
@@ -631,4 +907,8 @@ declare const pass: <TError = string>() => RuleResult<TError>;
631
907
 
632
908
  declare const calculateDelay: (strategy: RetryStrategy | undefined, attempt: number, initialDelayMs: number) => number;
633
909
 
634
- export { type CompositionOptions, type DebugOptions, type RetryStrategy, type Rule, type RuleResult, calculateDelay, composeRules, every, fail, hasContext, ifElse, inject, mapError, match, not, oneOf, pass, pipe, pipeRules, requireContextRule, tap, unless, validateField, when, withDebug, withFallback, withLazyContext, withMemoize, withRetry, withTimeout };
910
+ declare const getNormalizedRule: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>, opts?: RuleSafetyOptions<TError>) => Rule<TInput, TError, TContext>;
911
+
912
+ declare const getNormalizedRules: <TInput, TError, TContext>(rules: Rule<TInput, TError, TContext>[], opts?: RuleSafetyOptions<TError>) => Rule<TInput, TError, TContext>[];
913
+
914
+ export { type CompositionOptions, type DebugOptions, type Predicate, type PredicateResult, type PredicateSafe, type RetryStrategy, type Rule, type RuleResult, type RuleSafetyOptions, calculateDelay, composeRules, every, fail, getNormalizedRule, getNormalizedRules, hasContext, ifElse, inject, mapError, match, not, oneOf, pass, pipe, pipeRules, requireContextRule, tap, unless, validateField, when, withDebug, withFallback, withLazyContext, withMemoize, withRetry, withSafeError, withSafePredicate, withTap, withTimeout };