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
@@ -1,5 +1,7 @@
1
- import type { Rule } from "../../types";
2
- import { pass } from "../../helpers";
1
+ import { fail, getNormalizedRule, pass } from "../../helpers";
2
+ import type { Predicate, Rule } from "../../types";
3
+ import type { SafetyOptions } from "../../types/safety-options";
4
+ import { withSafePredicate } from "../utility";
3
5
 
4
6
  /**
5
7
  * Executes a rule only if the predicate returns false.
@@ -8,6 +10,12 @@ import { pass } from "../../helpers";
8
10
  * @template TContext - The type of the context object (optional)
9
11
  * @param predicate - Condition to check
10
12
  * @param rule - Rule to execute when predicate is false
13
+ * @param options - Configuration for error handling and predicate safety
14
+ * @param options.errorHandlingMode - Determines how errors are handled:
15
+ * - 'safe': (default) Converts thrown errors to validation failures
16
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
17
+ * @param options.errorTransform - Custom transformation for caught errors
18
+ * @param options.predicateErrorTransform - Special error handler for predicate failures
11
19
  * @returns A rule that conditionally executes based on the predicate
12
20
  * @example
13
21
  * const rule = unless(
@@ -19,9 +27,24 @@ import { pass } from "../../helpers";
19
27
  * - Automatically passes when predicate is true
20
28
  */
21
29
  export const unless = <TInput, TError = string, TContext = unknown>(
22
- predicate: (input: TInput) => Promise<boolean> | boolean,
30
+ predicate: Predicate<TInput, TContext>,
23
31
  rule: Rule<TInput, TError, TContext>,
32
+ options?: SafetyOptions<TError>,
24
33
  ): Rule<TInput, TError, TContext> => {
25
- return async (input: TInput, context?: TContext) =>
26
- (await predicate(input)) ? pass() : rule(input, context);
34
+ return async (input: TInput, context?: TContext) => {
35
+ const normalizedRule = getNormalizedRule(rule, options);
36
+ const safePredicate = withSafePredicate<TInput, TError, TContext>(
37
+ predicate,
38
+ options?.predicateErrorTransform,
39
+ );
40
+
41
+ const safePredicateResult = await safePredicate(input, context);
42
+
43
+ // Predicate fail to run or returned invalid result
44
+ if (safePredicateResult.status === "failed") {
45
+ return fail(safePredicateResult.error);
46
+ }
47
+
48
+ return safePredicateResult.value ? pass() : normalizedRule(input, context);
49
+ };
27
50
  };
@@ -19,7 +19,7 @@ describe("when combinator", () => {
19
19
 
20
20
  await conditionalRule(input);
21
21
 
22
- expect(mockPredicateTrue).toHaveBeenCalledWith(input);
22
+ expect(mockPredicateTrue).toHaveBeenCalledWith(input, undefined);
23
23
  expect(mockRule).toHaveBeenCalledWith(input, undefined);
24
24
  });
25
25
 
@@ -28,7 +28,7 @@ describe("when combinator", () => {
28
28
  const input = { active: false };
29
29
  const result = await conditionalRule(input);
30
30
 
31
- expect(mockPredicateFalse).toHaveBeenCalledWith(input);
31
+ expect(mockPredicateFalse).toHaveBeenCalledWith(input, undefined);
32
32
  expect(result).toEqual(pass());
33
33
  expect(mockRule).not.toHaveBeenCalled();
34
34
  });
@@ -74,16 +74,6 @@ describe("when combinator", () => {
74
74
  }
75
75
  });
76
76
 
77
- it("should pass context to rule but not predicate", async () => {
78
- const context = { authToken: "xyz" };
79
- const rule = vi.fn(() => pass());
80
-
81
- await when(mockPredicateTrue, rule)({}, context);
82
-
83
- expect(mockPredicateTrue).toHaveBeenCalledWith({});
84
- expect(rule).toHaveBeenCalledWith({}, context);
85
- });
86
-
87
77
  it("should work with async rules needing context", async () => {
88
78
  const context = {
89
79
  db: {
@@ -106,9 +96,13 @@ describe("when combinator", () => {
106
96
  const errorCondition = () => {
107
97
  throw new Error("Condition failed");
108
98
  };
109
- const conditionalRule = when(errorCondition, mockRule);
99
+ const conditionalRule = when(errorCondition, mockRule, {
100
+ errorHandlingMode: "unsafe",
101
+ });
110
102
 
111
- expect(conditionalRule({})).rejects.toThrow("Condition failed");
103
+ expect(conditionalRule({})).resolves.toEqual(
104
+ fail(new Error("Condition failed")),
105
+ );
112
106
  expect(mockRule).not.toHaveBeenCalled();
113
107
  });
114
108
 
@@ -116,7 +110,9 @@ describe("when combinator", () => {
116
110
  const errorRule = () => {
117
111
  throw new Error("Rule failed");
118
112
  };
119
- const conditionalRule = when(() => true, errorRule);
113
+ const conditionalRule = when(() => true, errorRule, {
114
+ errorHandlingMode: "unsafe",
115
+ });
120
116
 
121
117
  expect(conditionalRule({})).rejects.toThrow("Rule failed");
122
118
  });
@@ -1,5 +1,9 @@
1
+ import { fail, getNormalizedRule } from "../../helpers";
1
2
  import { pass } from "../../helpers/result/pass";
2
- import { Rule } from "../../types/rule";
3
+ import type { Predicate } from "../../types";
4
+ import type { Rule } from "../../types/rule";
5
+ import type { SafetyOptions } from "../../types/safety-options";
6
+ import { withSafePredicate } from "../utility";
3
7
 
4
8
  /**
5
9
  * Conditionally executes a rule based on a predicate.
@@ -8,6 +12,12 @@ import { Rule } from "../../types/rule";
8
12
  * @template TError - The type of the error (defaults to string)
9
13
  * @param predicate - Function that determines whether to execute the rule
10
14
  * @param rule - Rule to execute when predicate returns true
15
+ * @param options - Configuration for error handling and predicate safety
16
+ * @param options.errorHandlingMode - Determines how errors are handled:
17
+ * - 'safe': (default) Converts thrown errors to validation failures
18
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
19
+ * @param options.errorTransform - Custom transformation for caught errors
20
+ * @param options.predicateErrorTransform - Special error handler for predicate failures
11
21
  * @returns A new rule that conditionally executes the input rule
12
22
  * @example
13
23
  * const rule = when(
@@ -18,12 +28,23 @@ import { Rule } from "../../types/rule";
18
28
  * - The predicate can be async
19
29
  * - If predicate returns false, the rule automatically passes
20
30
  */
21
- export const when = <TInput, TError = string>(
22
- predicate: (input: TInput) => boolean | Promise<boolean>,
23
- rule: Rule<TInput, TError>,
24
- ): Rule<TInput, TError> => {
25
- return async (input: TInput, context?: unknown) => {
26
- const shouldRun = await predicate(input);
27
- return shouldRun ? rule(input, context) : pass();
31
+ export const when = <TInput, TError = string, TContext = unknown>(
32
+ predicate: Predicate<TInput, TContext>,
33
+ rule: Rule<TInput, TError, TContext>,
34
+ options?: SafetyOptions<TError>,
35
+ ): Rule<TInput, TError, TContext> => {
36
+ return async (input: TInput, context?: TContext) => {
37
+ const normalizedRule = getNormalizedRule(rule, options);
38
+ const safePredicate = withSafePredicate<TInput, TError, TContext>(
39
+ predicate,
40
+ options?.predicateErrorTransform,
41
+ );
42
+
43
+ const safePredicateResult = await safePredicate(input, context);
44
+ if (safePredicateResult.status === "failed") {
45
+ return fail(safePredicateResult.error);
46
+ }
47
+
48
+ return safePredicateResult.value ? normalizedRule(input, context) : pass();
28
49
  };
29
50
  };
@@ -1,4 +1,5 @@
1
- import { Rule } from "../../types";
1
+ import { getNormalizedRules } from "../../helpers";
2
+ import type { Rule, RuleSafetyOptions } from "../../types";
2
3
 
3
4
  /**
4
5
  * Creates a rule that falls back to an alternative rule if the main rule fails.
@@ -9,6 +10,10 @@ import { Rule } from "../../types";
9
10
  * @param fallbackRule - Rule to execute if main rule fails
10
11
  * @param options - Configuration options
11
12
  * @param options.onlyFallbackOn - Predicate to conditionally enable fallback
13
+ * @param options.errorHandlingMode - Determines how errors are handled:
14
+ * - 'safe': (default) Converts thrown errors to validation failures
15
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
16
+ * @param options.errorTransform - Custom transformation for caught errors
12
17
  * @returns A new composite rule
13
18
  * @example
14
19
  * const rule = withFallback(
@@ -20,17 +25,21 @@ import { Rule } from "../../types";
20
25
  export const withFallback = <TInput, TError, TContext>(
21
26
  mainRule: Rule<TInput, TError, TContext>,
22
27
  fallbackRule: Rule<TInput, TError, TContext>,
23
- options: {
28
+ options: RuleSafetyOptions<TError> & {
24
29
  onlyFallbackOn?: (error: TError) => boolean;
25
30
  } = {},
26
31
  ): Rule<TInput, TError, TContext> => {
27
32
  return async (input: TInput, context?: TContext) => {
28
- const result = await mainRule(input, context);
33
+ const [mainSafeRule, fallbackSafeRule] = getNormalizedRules([
34
+ mainRule,
35
+ fallbackRule,
36
+ ]);
37
+ const result = await mainSafeRule(input, context);
29
38
  if (
30
39
  result.status === "failed" &&
31
40
  (!options.onlyFallbackOn || options.onlyFallbackOn(result.error))
32
41
  ) {
33
- return fallbackRule(input, context);
42
+ return fallbackSafeRule(input, context);
34
43
  }
35
44
  return result;
36
45
  };
@@ -1,8 +1,11 @@
1
1
  export * from "./inject";
2
2
  export * from "./map-error";
3
- export * from "./with-memoize";
4
- export * from "./validate-field";
5
3
  export * from "./tap";
4
+ export * from "./with-tap";
5
+ export * from "./validate-field";
6
6
  export * from "./with-debug";
7
+ export * from "./with-memoize";
7
8
  export * from "./with-retry";
9
+ export * from "./with-safe-error";
10
+ export * from "./with-safe-predicate";
8
11
  export * from "./with-timeout";
@@ -1,4 +1,4 @@
1
- import { Rule } from "../../types";
1
+ import type { Rule } from "../../types";
2
2
 
3
3
  /**
4
4
  * Injects a dependency into a rule creation function, returning a configured rule.
@@ -1,5 +1,5 @@
1
1
  import { fail, pass } from "../../helpers";
2
- import { Rule } from "../../types";
2
+ import type { Rule } from "../../types";
3
3
 
4
4
  /**
5
5
  * Transforms the error of a rule using a mapping function.
@@ -1,102 +1,102 @@
1
- import { describe, vi, beforeEach, it, expect } from "vitest";
2
- import { pipeRules } from "../../composition/pipe-rules";
3
- import { fail, pass } from "../../helpers";
4
- import { Rule } from "../../types";
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
5
2
  import { tap } from "./tap";
3
+ import { pass } from "../../helpers";
4
+ import { pipeRules } from "../../composition";
6
5
 
7
- describe("tap (standalone)", () => {
6
+ describe("tap", () => {
8
7
  const mockEffect = vi.fn();
9
- const mockRule = vi.fn(() => pass());
10
- const mockContext = { logger: console };
8
+ const mockContext = { requestId: "123" };
11
9
 
12
10
  beforeEach(() => {
13
11
  vi.clearAllMocks();
14
12
  });
15
13
 
16
- // Basic functionality
17
- it("should call effect without modifying rule result", async () => {
18
- const tappedRule = tap(mockEffect)(mockRule);
19
- const input = { test: "value" };
20
- const result = await tappedRule(input);
14
+ // 1. Basic functionality
15
+ it("should execute effect without modifying validation result", async () => {
16
+ const input = { id: "test" };
17
+ const rule = tap(mockEffect);
18
+ const result = await rule(input);
21
19
 
22
20
  expect(result).toEqual(pass());
23
- expect(mockEffect).toHaveBeenCalledWith(input, pass(), undefined);
24
- expect(mockRule).toHaveBeenCalledWith(input, undefined);
21
+ expect(mockEffect).toHaveBeenCalledWith(input, undefined);
25
22
  });
26
23
 
27
- // Error handling
28
- it("should not propagate effect errors", async () => {
29
- const errorEffect = vi.fn(() => {
30
- throw new Error("Effect failed");
31
- });
32
- const tappedRule = tap(errorEffect)(mockRule);
24
+ // 2. Context handling
25
+ it("should pass context to the effect", async () => {
26
+ const input = { id: "test" };
27
+ const rule = tap(mockEffect);
28
+ await rule(input, mockContext);
33
29
 
34
- await expect(tappedRule({})).resolves.toEqual(pass());
35
- expect(errorEffect).toHaveBeenCalled();
30
+ expect(mockEffect).toHaveBeenCalledWith(input, mockContext);
36
31
  });
37
32
 
38
- // Context handling
39
- it("should pass context to both rule and effect", async () => {
40
- const tappedRule = tap(mockEffect)(mockRule);
41
- await tappedRule({}, mockContext);
33
+ // 3. Error isolation
34
+ it("should not propagate effect errors", async () => {
35
+ const errorEffect = vi.fn().mockRejectedValue(new Error("Effect failed"));
36
+ const input = { id: "test" };
37
+ const rule = tap(errorEffect);
42
38
 
43
- expect(mockRule).toHaveBeenCalledWith({}, mockContext);
44
- expect(mockEffect).toHaveBeenCalledWith({}, pass(), mockContext);
39
+ await expect(rule(input)).resolves.toEqual(pass());
40
+ expect(errorEffect).toHaveBeenCalled();
45
41
  });
46
42
 
47
- // Async effects
43
+ // 4. Async effects
48
44
  it("should handle async effects", async () => {
49
- const asyncEffect = vi.fn(async () => {
45
+ const asyncEffect = vi.fn().mockImplementation(async (input: any) => {
50
46
  await Promise.resolve();
47
+ console.log(input);
51
48
  });
52
- const tappedRule = tap(asyncEffect)(mockRule);
53
- await tappedRule({});
49
+ const input = { id: "test" };
50
+ const rule = tap(asyncEffect);
54
51
 
55
- expect(asyncEffect).toHaveBeenCalled();
52
+ await expect(rule(input)).resolves.toEqual(pass());
53
+ expect(asyncEffect).toHaveBeenCalledWith(input, undefined);
56
54
  });
57
55
 
58
- // Composition
59
- it("should work with manual composition", async () => {
60
- const rule1 = vi.fn(() => pass());
61
- const rule2 = vi.fn(() => fail("Error"));
62
- const effect1 = vi.fn();
63
- const effect2 = vi.fn();
64
-
65
- const pipeline = tap(effect2)(pipeRules([tap(effect1)(rule1), rule2]));
56
+ // 5. Integration with pipeRules
57
+ it("should work in composition pipelines", async () => {
58
+ const mockRule = vi.fn().mockResolvedValue(pass());
59
+ const input = { id: "test" };
60
+ const pipeline = pipeRules([tap(mockEffect), mockRule]);
66
61
 
67
- await pipeline({});
68
- expect(effect1).toHaveBeenCalledWith({}, pass(), undefined);
69
- expect(effect2).toHaveBeenCalledWith({}, fail("Error"), undefined);
62
+ await pipeline(input);
63
+ expect(mockEffect).toHaveBeenCalledBefore(mockRule);
64
+ expect(mockRule).toHaveBeenCalledWith(input, undefined);
70
65
  });
71
66
 
72
- // Type safety tests
73
- it("should enforce input type matching", () => {
67
+ // 6. Type safety tests
68
+ it("should enforce input type matching", async () => {
74
69
  type StrictInput = { id: string };
75
- const typedRule: Rule<StrictInput> = () => pass();
70
+ const typedEffect = vi.fn((_: StrictInput) => {});
76
71
 
77
72
  // Valid usage
78
- tap((input: StrictInput) => console.log(input.id))(typedRule);
73
+ tap(typedEffect)({ id: "123" });
79
74
 
80
- // @ts-expect-error - Should fail if effect expects wrong input type
81
- tap((input: { other: number }) => {})(typedRule);
75
+ // @ts-expect-error - Should fail if input types mismatch
76
+ tap(typedEffect)({ notId: "123" });
82
77
  });
83
78
 
84
- // Edge cases
85
- it("should handle null/undefined inputs", async () => {
86
- const effect = vi.fn();
87
- const rule = () => pass();
88
- const tappedRule = tap(effect)(rule);
79
+ // 8. Effect error handling
80
+ it("should log effect errors to console", async () => {
81
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
82
+ const error = new Error("Test error");
83
+ const errorEffect = vi.fn().mockRejectedValue(error);
84
+ const rule = tap(errorEffect);
89
85
 
90
- await tappedRule(null as any);
91
- expect(effect).toHaveBeenCalledWith(null, pass(), undefined);
86
+ await rule({});
87
+ expect(consoleSpy).toHaveBeenCalledWith("Tap effect failed: ", error);
88
+ consoleSpy.mockRestore();
92
89
  });
93
90
 
94
- it("should handle effect returning Promise<void>", async () => {
95
- const asyncEffect = async () => {
96
- await Promise.resolve();
97
- };
98
- const tappedRule = tap(asyncEffect)(mockRule);
91
+ // 9. Multiple taps in pipeline
92
+ it("should allow multiple taps in sequence", async () => {
93
+ const effect1 = vi.fn();
94
+ const effect2 = vi.fn();
95
+ const input = { id: "test" };
96
+
97
+ const pipeline = pipeRules([tap(effect1), tap(effect2)]);
99
98
 
100
- await expect(tappedRule({})).resolves.toEqual(pass());
99
+ await pipeline(input);
100
+ expect(effect1).toHaveBeenCalledBefore(effect2);
101
101
  });
102
102
  });
@@ -1,38 +1,28 @@
1
- import { Rule, RuleResult } from "../../types";
1
+ import { pass } from "../../helpers";
2
+ import type { Rule } from "../../types";
2
3
 
3
4
  /**
4
- * Creates a rule wrapper that performs side effects without modifying the result.
5
- * @template TInput - The type of the input to validate
6
- * @template TError - The type of the error (defaults to string)
7
- * @template TContext - The type of the context object (optional)
8
- * @param effect - Side effect function receiving input, result and context
9
- * @returns A function that wraps a rule with the tap effect
5
+ * Creates a standalone tap effect for use in composition pipelines
6
+ * @template TInput - Input type
7
+ * @template TError - Error type
8
+ * @template TContext - Context type
9
+ * @param effect - Side effect function receiving (input, context)
10
+ * @returns A rule that passes through input unchanged
10
11
  * @example
11
- * const withLogging = tap((input, result) => {
12
- * console.log(`Validation result for ${input}:`, result);
13
- * });
14
- *
15
- * const rule = withLogging(validateInput);
16
- * @caveats
17
- * - Errors in the effect are caught and logged but don't affect rule execution
18
- * - Doesn't modify the rule's result
12
+ * pipeRules([
13
+ * tap((input) => console.log('Processing:', input)),
14
+ * validateInput
15
+ * ])
19
16
  */
20
17
  export const tap = <TInput, TError = string, TContext = unknown>(
21
- effect: (
22
- input: TInput,
23
- result: RuleResult<TError>,
24
- context?: TContext,
25
- ) => Promise<void> | void,
26
- ): ((
27
- rule: Rule<TInput, TError, TContext>,
28
- ) => Rule<TInput, TError, TContext>) => {
29
- return (rule) => async (input, context) => {
30
- const result = await rule(input, context);
18
+ effect: (input: TInput, context?: TContext) => Promise<void> | void,
19
+ ): Rule<TInput, TError, TContext> => {
20
+ return async (input, context) => {
31
21
  try {
32
- await effect(input, result, context);
22
+ await effect(input, context);
33
23
  } catch (error) {
34
- console.error("Tap effect failed:", error);
24
+ console.error("Tap effect failed: ", error);
35
25
  }
36
- return result;
26
+ return pass();
37
27
  };
38
28
  };
@@ -1,7 +1,7 @@
1
1
  import { describe, it, expect, vi, beforeEach } from "vitest";
2
2
  import { validateField } from "./validate-field";
3
3
  import { pass, fail } from "../../helpers";
4
- import { Rule } from "../../types";
4
+ import type { Rule } from "../../types";
5
5
 
6
6
  describe("validateField", () => {
7
7
  interface TestUser {
@@ -1,5 +1,5 @@
1
- import { fail } from "../../helpers";
2
- import { Rule } from "../../types";
1
+ import { fail, getNormalizedRule } from "../../helpers";
2
+ import type { Rule, RuleSafetyOptions } from "../../types";
3
3
 
4
4
  /**
5
5
  * Creates a rule that extracts a value using a getter function and validates it.
@@ -10,6 +10,11 @@ import { Rule } from "../../types";
10
10
  * @param getter - Function that extracts the value from input
11
11
  * @param rule - Rule to apply to the extracted value
12
12
  * @param defaultValue - Optional default value if getter returns undefined
13
+ * @param options - Configuration for error handling safety
14
+ * @param options.errorHandlingMode - Determines how errors are handled:
15
+ * - 'safe': (default) Converts thrown errors to validation failures
16
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
17
+ * @param options.errorTransform - Custom transformation for caught errors
13
18
  * @returns A new rule that validates the extracted value
14
19
  * @example
15
20
  * const validateName = validateField(
@@ -45,15 +50,17 @@ export function validateField<
45
50
  getter: (input: TInput) => TValue | undefined,
46
51
  rule: Rule<TValue, TError, TContext>,
47
52
  defaultValue?: TValue,
53
+ options?: RuleSafetyOptions<TError>,
48
54
  ): Rule<TInput, TError, TContext> {
49
55
  return async (input: TInput, context?: TContext) => {
50
56
  const value = getter(input);
51
57
  const finalValue = value !== undefined ? value : defaultValue;
58
+ const safeRule = getNormalizedRule(rule, options);
52
59
 
53
60
  if (finalValue === undefined) {
54
61
  return fail("Missing required value" as unknown as TError);
55
62
  }
56
63
 
57
- return rule(finalValue, context);
64
+ return safeRule(finalValue, context);
58
65
  };
59
66
  }
@@ -1,6 +1,6 @@
1
1
  import { describe, vi, beforeEach, it, expect } from "vitest";
2
2
  import { pass, fail } from "../../helpers";
3
- import { Rule } from "../../types";
3
+ import type { Rule } from "../../types";
4
4
  import { withDebug } from "./with-debug";
5
5
 
6
6
  describe("withDebug", () => {
@@ -1,4 +1,4 @@
1
- import { DebugOptions, Rule } from "../../types";
1
+ import type { DebugOptions, Rule } from "../../types";
2
2
 
3
3
  /**
4
4
  * Wraps a rule with debugging capabilities.
@@ -1,5 +1,5 @@
1
1
  import { describe, vi, beforeEach, it, expect } from "vitest";
2
- import { Rule } from "../../types";
2
+ import type { Rule } from "../../types";
3
3
  import { withMemoize } from "./with-memoize";
4
4
  import { pass } from "../../helpers";
5
5
 
@@ -1,4 +1,5 @@
1
- import { Rule, RuleResult } from "../../types";
1
+ import { getNormalizedRule } from "../../helpers";
2
+ import type { Rule, RuleResult, RuleSafetyOptions } from "../../types";
2
3
 
3
4
  /**
4
5
  * Creates a memoized version of a rule that caches results based on input keys.
@@ -7,9 +8,13 @@ import { Rule, RuleResult } from "../../types";
7
8
  * @template TContext - The type of the context object (optional)
8
9
  * @param rule - The rule to memoize
9
10
  * @param keyFn - Function that generates a cache key from the input
10
- * @param options - Memoization options
11
+ * @param options - Memoization and safety options
11
12
  * @param options.ttl - Time-to-live for cache entries in milliseconds
12
13
  * @param options.maxSize - Maximum number of entries to keep in cache
14
+ * @param options.errorHandlingMode - Determines how errors are handled:
15
+ * - 'safe': (default) Converts thrown errors to validation failures
16
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
17
+ * @param options.errorTransform - Custom transformation for caught errors
13
18
  * @returns A memoized version of the rule
14
19
  * @example
15
20
  * const memoizedRule = withMemoize(
@@ -21,6 +26,8 @@ import { Rule, RuleResult } from "../../types";
21
26
  * - Context changes don't invalidate cache by default
22
27
  * - Cache cleanup happens during rule execution
23
28
  * - Rejected promises are automatically evicted from cache
29
+ * - Successful results obey TTL rules
30
+ * - Cache is shared across rule instances
24
31
  */
25
32
  export const withMemoize = <TInput, TError = string, TContext = unknown>(
26
33
  rule: Rule<TInput, TError, TContext>,
@@ -28,7 +35,7 @@ export const withMemoize = <TInput, TError = string, TContext = unknown>(
28
35
  options: {
29
36
  ttl?: number; // Milliseconds
30
37
  maxSize?: number;
31
- } = {},
38
+ } & RuleSafetyOptions<TError> = {},
32
39
  ): Rule<TInput, TError, TContext> => {
33
40
  const cache = new Map<
34
41
  string,
@@ -65,7 +72,8 @@ export const withMemoize = <TInput, TError = string, TContext = unknown>(
65
72
  }
66
73
 
67
74
  // Cache miss
68
- const result = rule(input, context);
75
+ const normalizedRule = getNormalizedRule(rule, options);
76
+ const result = normalizedRule(input, context);
69
77
  cache.set(key, {
70
78
  result,
71
79
  timestamp: now,
@@ -1,6 +1,6 @@
1
1
  import { describe, vi, beforeEach, it, expect, afterEach } from "vitest";
2
2
  import { fail, pass } from "../../helpers";
3
- import { Rule } from "../../types";
3
+ import type { Rule } from "../../types";
4
4
  import { withRetry } from "./with-retry";
5
5
 
6
6
  describe("withRetry combinator", () => {
@@ -1,5 +1,5 @@
1
- import type { Rule } from "../../types";
2
1
  import { calculateDelay, fail } from "../../helpers";
2
+ import type { Rule } from "../../types";
3
3
 
4
4
  export type RetryStrategy =
5
5
  | "fixed"
@@ -45,7 +45,9 @@ export const withRetry = <TInput, TError = string, TContext = unknown>(
45
45
  for (let attempt = 1; attempt <= attempts; attempt++) {
46
46
  try {
47
47
  const result = await rule(input, context);
48
- if (result.status === "passed") return result;
48
+ if (result.status === "passed") {
49
+ return result;
50
+ }
49
51
  lastError = result.error;
50
52
  } catch (error) {
51
53
  lastError = error;