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,7 +1,7 @@
1
1
  import { pipeRules } from "./pipe-rules";
2
2
  import { fail, pass } from "../helpers";
3
3
  import { beforeEach, describe, expect, it, vi } from "vitest";
4
- import { Rule } from "../types";
4
+ import type { Rule } from "../types";
5
5
 
6
6
  describe("pipeRules", () => {
7
7
  // Mock rules
@@ -1,5 +1,6 @@
1
- import { pass } from "../helpers";
2
- import { CompositionOptions, Rule } from "../types";
1
+ import { getNormalizedRules, pass } from "../helpers";
2
+ import { getCloneFn } from "../helpers/clone/getCloneFn";
3
+ import type { CompositionOptions, Rule } from "../types";
3
4
 
4
5
  /**
5
6
  * Pipes multiple rules into a single rule that runs them sequentially (fail-fast).
@@ -10,6 +11,10 @@ import { CompositionOptions, Rule } from "../types";
10
11
  * @param rules - Array of rules to compose
11
12
  * @param options - Configuration options
12
13
  * @param options.cloneContext - Whether to clone the context for each rule (default: false)
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 pipes all input rules
14
19
  * @example
15
20
  * const rule = pipeRules([
@@ -22,18 +27,21 @@ import { CompositionOptions, Rule } from "../types";
22
27
  * @caveats
23
28
  * - Rules are execute from left to right
24
29
  * - Rules are executed in sequence, not in parallel
25
- * - Context clone uses structuredClone Nodejs implementation
30
+ * - Cloning behavior follows this priority:
31
+ * 1. Uses shallowClone if options.shallowClone = true
32
+ * 2. Uses structuredClone if available and options.structuredClone = true
33
+ * 3. Falls back to JSON clone otherwise
26
34
  */
27
35
  export const pipeRules = <TInput, TError = string, TContext = unknown>(
28
36
  rules: Rule<TInput, TError, TContext>[],
29
37
  options: CompositionOptions = {},
30
38
  ): Rule<TInput, TError, TContext> => {
31
39
  return async (input: TInput, context?: TContext) => {
32
- const currentContext = options?.cloneContext
33
- ? structuredClone(context)
34
- : context;
40
+ const cloneFn = getCloneFn(options);
41
+ const currentContext = options?.cloneContext ? cloneFn(context) : context;
42
+ const normalizedRules = getNormalizedRules(rules);
35
43
 
36
- for (const rule of rules) {
44
+ for (const rule of normalizedRules) {
37
45
  const result = await rule(input, currentContext);
38
46
  if (result.status === "failed") {
39
47
  return result;
@@ -1,3 +1,4 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1
2
  type AnyFunction = (...args: any[]) => any;
2
3
 
3
4
  /**
@@ -0,0 +1,12 @@
1
+ export const clone = <T>(obj: T): T => {
2
+ if (!obj) return {} as T;
3
+ try {
4
+ return JSON.parse(JSON.stringify(obj));
5
+ } catch (e) {
6
+ console.warn(
7
+ `Clone failed for ${obj?.constructor?.name}, returning empty object`,
8
+ e,
9
+ );
10
+ return {} as T;
11
+ }
12
+ };
@@ -0,0 +1,17 @@
1
+ import type { CompositionOptions } from "../../types";
2
+
3
+ import { clone } from "./clone";
4
+ import { shallowClone } from "./shallowClone";
5
+
6
+ export const getCloneFn = (opts: CompositionOptions<unknown>) => {
7
+ const canUseStructuredClone = typeof structuredClone !== "undefined";
8
+
9
+ const cloneFn =
10
+ opts.cloneStrategy === "shallow"
11
+ ? shallowClone
12
+ : opts.cloneStrategy === "structured" && canUseStructuredClone
13
+ ? structuredClone
14
+ : clone;
15
+
16
+ return cloneFn;
17
+ };
@@ -0,0 +1,12 @@
1
+ export const shallowClone = <T>(obj: T): T => {
2
+ if (!obj) return {} as T;
3
+ try {
4
+ return { ...obj };
5
+ } catch (e) {
6
+ console.warn(
7
+ `Clone failed for ${obj?.constructor?.name}, returning empty object`,
8
+ e,
9
+ );
10
+ return {} as T;
11
+ }
12
+ };
@@ -1,4 +1,4 @@
1
- import { Rule, RuleResult } from "../../types";
1
+ import type { Rule, RuleResult } from "../../types";
2
2
  import { fail } from "../result";
3
3
 
4
4
  /**
@@ -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 { fail, pass } from "../result";
4
4
  import { withLazyContext } from "./with-lazy-context";
5
5
 
@@ -1,4 +1,4 @@
1
- import { Rule } from "../../types";
1
+ import type { Rule } from "../../types";
2
2
  import { fail } from "../result";
3
3
 
4
4
  /**
@@ -4,3 +4,5 @@ export * from "./context/with-lazy-context";
4
4
  export * from "./result/fail";
5
5
  export * from "./result/pass";
6
6
  export * from "./retry/calculate-delay";
7
+ export * from "./safety/get-normalized-rule";
8
+ export * from "./safety/get-normalized-rules";
@@ -1,4 +1,4 @@
1
- import { RuleResult } from "../../types";
1
+ import type { RuleResult } from "../../types";
2
2
 
3
3
  /**
4
4
  * Creates a failed RuleResult with the provided error.
@@ -1,4 +1,4 @@
1
- import { RuleResult } from "../../types";
1
+ import type { RuleResult } from "../../types";
2
2
 
3
3
  /**
4
4
  * Creates a successful RuleResult with "passed" status.
@@ -1,4 +1,4 @@
1
- import { RetryStrategy } from "../../combinators";
1
+ import type { RetryStrategy } from "../../combinators";
2
2
 
3
3
  export const calculateDelay = (
4
4
  strategy: RetryStrategy | undefined,
@@ -0,0 +1,209 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { getNormalizedRule } from "./get-normalized-rule";
3
+ import type { Rule, RuleSafetyOptions } from "../../types";
4
+ import { pass, fail } from "../../helpers";
5
+
6
+ describe("getNormalizedRule", () => {
7
+ // Mock rules for testing
8
+ interface CustomError {
9
+ code: number;
10
+ message: string;
11
+ }
12
+
13
+ const passingRule: Rule<string> = vi.fn(() => pass());
14
+
15
+ const errorThrowingRuleCustom: Rule<string, CustomError> = vi.fn(() => {
16
+ throw new Error("Boom!");
17
+ });
18
+ const passingRuleCustom: Rule<string, CustomError> = vi.fn(() =>
19
+ pass(),
20
+ ) as Rule<string, CustomError>;
21
+ const failingRuleCustom: Rule<string, CustomError> = vi.fn(() =>
22
+ fail({ code: 400, message: "Expected error" }),
23
+ );
24
+
25
+ const errorThrowingRule: Rule<string> = vi.fn(() => {
26
+ throw new Error("Boom!");
27
+ });
28
+ const objectThrowingRule: Rule<string, { code: number }> = vi.fn(() => {
29
+ throw { code: 500 };
30
+ });
31
+
32
+ beforeEach(() => {
33
+ vi.clearAllMocks();
34
+ });
35
+
36
+ describe("with errorHandlingMode = 'safe' (default)", () => {
37
+ const defaultOptions: RuleSafetyOptions = {};
38
+
39
+ it("should return original rule when it doesn't throw", async () => {
40
+ const normalized = getNormalizedRule(passingRule, defaultOptions);
41
+ const result = await normalized("test");
42
+
43
+ expect(result).toEqual(pass());
44
+ expect(passingRule).toHaveBeenCalledWith("test", undefined);
45
+ });
46
+
47
+ it("should wrap with withSafeError when rule throws", async () => {
48
+ const normalized = getNormalizedRule(errorThrowingRule, defaultOptions);
49
+ const result = await normalized("test");
50
+
51
+ expect(result.status).toBe("failed");
52
+ expect((result as any).error.message).toBe("Boom!");
53
+ });
54
+ });
55
+
56
+ describe("with errorHandlingMode = 'unsafe'", () => {
57
+ const unsafeOptions: RuleSafetyOptions = { errorHandlingMode: "unsafe" };
58
+
59
+ it("should return original rule when it doesn't throw", async () => {
60
+ const normalized = getNormalizedRule(passingRule, unsafeOptions);
61
+ const result = await normalized("test");
62
+
63
+ expect(result).toEqual(pass());
64
+ expect(passingRule).toHaveBeenCalledWith("test");
65
+ });
66
+
67
+ it("should not catch thrown errors", async () => {
68
+ // Create a fresh mock that throws when called
69
+ const throwingRule: Rule<string> = vi.fn(() => {
70
+ throw new Error("Boom!");
71
+ });
72
+
73
+ const normalized = getNormalizedRule(throwingRule, unsafeOptions);
74
+ expect(async () => await normalized("test")).rejects.toThrow("Boom!");
75
+
76
+ expect(throwingRule).toHaveBeenCalledWith("test");
77
+ });
78
+
79
+ it("should preserve original error throwing behavior", async () => {
80
+ const normalized = getNormalizedRule(objectThrowingRule, unsafeOptions);
81
+
82
+ expect(async () => await normalized("test")).rejects.toEqual({
83
+ code: 500,
84
+ });
85
+ });
86
+ });
87
+
88
+ describe("with custom errorTransform", () => {
89
+ const customTransform = vi.fn(
90
+ (error: unknown): CustomError => ({
91
+ code: 500,
92
+ message: String(error),
93
+ }),
94
+ );
95
+
96
+ const transformOptions: RuleSafetyOptions<CustomError> = {
97
+ errorTransform: customTransform,
98
+ };
99
+
100
+ it("should use custom transform for thrown errors", async () => {
101
+ const normalized = getNormalizedRule(
102
+ errorThrowingRuleCustom,
103
+ transformOptions,
104
+ );
105
+ const result = await normalized("test");
106
+
107
+ expect(result).toEqual(
108
+ fail({
109
+ code: 500,
110
+ message: "Error: Boom!",
111
+ }),
112
+ );
113
+ expect(customTransform).toHaveBeenCalledWith(expect.any(Error));
114
+ });
115
+
116
+ it("should not call transform for successful rules", async () => {
117
+ const normalized = getNormalizedRule(passingRuleCustom, transformOptions);
118
+ await normalized("test");
119
+
120
+ expect(customTransform).not.toHaveBeenCalled();
121
+ });
122
+
123
+ it("should not call transform for explicit failures", async () => {
124
+ const normalized = getNormalizedRule(failingRuleCustom, transformOptions);
125
+ await normalized("test");
126
+
127
+ expect(customTransform).not.toHaveBeenCalled();
128
+ });
129
+
130
+ it("should use default string error when no transform provided", async () => {
131
+ const stringErrorRule: Rule<string> = vi.fn(() => {
132
+ throw new Error("Boom!");
133
+ });
134
+
135
+ const normalized = getNormalizedRule(stringErrorRule, {});
136
+ const result = await normalized("test");
137
+
138
+ expect(result).toEqual(fail(new Error("Boom!")));
139
+ });
140
+ });
141
+
142
+ describe("edge cases", () => {
143
+ it("should handle null/undefined input safely", async () => {
144
+ const normalized = getNormalizedRule(passingRule, {});
145
+ await expect(normalized(null as any)).resolves.not.toThrow();
146
+ await expect(normalized(undefined as any)).resolves.not.toThrow();
147
+ });
148
+
149
+ it("should handle rules that return invalid results", async () => {
150
+ const invalidRule = vi.fn(() => "not a RuleResult" as any);
151
+ const normalized = getNormalizedRule(invalidRule, {});
152
+ const result = await normalized("test");
153
+
154
+ expect(result.status).toBe("failed");
155
+ expect((result as any).error.message).toContain(
156
+ "Invalid rule - did not return RuleResult",
157
+ );
158
+ });
159
+
160
+ it("should pass context to wrapped rules", async () => {
161
+ const context = { userId: 123 };
162
+ const contextAwareRule = vi.fn((_: string, ctx: any) =>
163
+ ctx?.userId === 123 ? pass() : fail("Wrong user"),
164
+ );
165
+
166
+ const normalized = getNormalizedRule(contextAwareRule, {});
167
+ await normalized("test", context);
168
+
169
+ expect(contextAwareRule).toHaveBeenCalledWith("test", context);
170
+ });
171
+ });
172
+
173
+ describe("type safety", () => {
174
+ it("should maintain input type safety", () => {
175
+ type StrictInput = { id: string };
176
+ const typedRule: Rule<StrictInput> = () => pass();
177
+
178
+ // Should compile
179
+ getNormalizedRule(typedRule, {})({ id: "123" });
180
+
181
+ // @ts-expect-error - Should fail if input types don't match
182
+ getNormalizedRule(typedRule, {})({ notId: "123" });
183
+ });
184
+
185
+ it("should maintain error type safety", async () => {
186
+ interface CustomError {
187
+ code: number;
188
+ details: string;
189
+ }
190
+ const customErrorRule: Rule<string, CustomError> = () => {
191
+ throw new Error("Test");
192
+ };
193
+
194
+ const normalized = getNormalizedRule(customErrorRule, {
195
+ errorTransform: (e) => ({
196
+ code: 500,
197
+ details: String(e),
198
+ }),
199
+ });
200
+
201
+ const result = await normalized("test");
202
+ expect(result.status).toBe("failed");
203
+ expect((result as any).error).toMatchObject({
204
+ code: expect.any(Number),
205
+ details: expect.any(String),
206
+ });
207
+ });
208
+ });
209
+ });
@@ -0,0 +1,14 @@
1
+ import { withSafeError } from "../../combinators";
2
+ import type { Rule, RuleSafetyOptions } from "../../types";
3
+
4
+ export const getNormalizedRule = <TInput, TError, TContext>(
5
+ rule: Rule<TInput, TError, TContext>,
6
+ opts?: RuleSafetyOptions<TError>,
7
+ ): Rule<TInput, TError, TContext> => {
8
+ const normalizedRule =
9
+ opts?.errorHandlingMode === "unsafe"
10
+ ? rule
11
+ : withSafeError(rule, opts?.errorTransform);
12
+
13
+ return normalizedRule;
14
+ };
@@ -0,0 +1,138 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { getNormalizedRules } from "./get-normalized-rules";
3
+ import type { Rule, RuleSafetyOptions } from "../../types";
4
+ import { pass, fail } from "../../helpers";
5
+
6
+ describe("getNormalizedRules", () => {
7
+ // Mock rules for testing
8
+ interface CustomError {
9
+ code: number;
10
+ message: string;
11
+ }
12
+
13
+ const passingRule: Rule<string> = vi.fn(() => pass());
14
+ const errorThrowingRule: Rule<string> = vi.fn(() => {
15
+ throw new Error("Boom!");
16
+ });
17
+ const objectThrowingRule: Rule<string, { code: number }> = vi.fn(() => {
18
+ throw { code: 500 };
19
+ });
20
+
21
+ const passingRuleCustom: Rule<string, CustomError> = vi.fn(() =>
22
+ pass(),
23
+ ) as Rule<string, CustomError>;
24
+ const errorThrowingRuleCustom: Rule<string, CustomError> = vi.fn(() => {
25
+ throw new Error("Boom!");
26
+ });
27
+
28
+ beforeEach(() => {
29
+ vi.clearAllMocks();
30
+ });
31
+
32
+ describe("with errorHandlingMode = 'safe' (default)", () => {
33
+ const defaultOptions: RuleSafetyOptions = {};
34
+
35
+ it("should return original rules when they don't throw", async () => {
36
+ const rules = [passingRule, passingRule];
37
+ const normalized = getNormalizedRules(rules, defaultOptions);
38
+
39
+ expect(normalized).toHaveLength(2);
40
+
41
+ // Verify behavior instead of function reference
42
+ const result1 = await normalized[0]("test");
43
+ expect(result1).toEqual(pass());
44
+ expect(passingRule).toHaveBeenCalledWith("test", undefined);
45
+
46
+ const result2 = await normalized[1]("test");
47
+ expect(result2).toEqual(pass());
48
+ expect(passingRule).toHaveBeenCalledWith("test", undefined);
49
+ });
50
+ it("should wrap throwing rules with safe handlers", async () => {
51
+ const rules = [errorThrowingRule];
52
+ const normalized = getNormalizedRules(rules, defaultOptions);
53
+
54
+ const result = await normalized[0]("test");
55
+ expect(result.status).toBe("failed");
56
+ expect((result as any).error.message).toBe("Boom!");
57
+ });
58
+
59
+ it("should handle empty rules array", () => {
60
+ const normalized = getNormalizedRules([], defaultOptions);
61
+ expect(normalized).toEqual([]);
62
+ });
63
+ });
64
+
65
+ describe("with errorHandlingMode = 'unsafe'", () => {
66
+ const unsafeOptions: RuleSafetyOptions = { errorHandlingMode: "unsafe" };
67
+
68
+ it("should return original rules without wrapping", () => {
69
+ const rules = [passingRule, errorThrowingRule, objectThrowingRule];
70
+ const normalized = getNormalizedRules(rules, unsafeOptions);
71
+
72
+ expect(normalized).toEqual(rules);
73
+ });
74
+
75
+ it("should preserve custom error types", () => {
76
+ const rules = [passingRuleCustom, errorThrowingRuleCustom];
77
+ const normalized = getNormalizedRules(rules, unsafeOptions);
78
+
79
+ expect(normalized).toEqual(rules);
80
+ });
81
+ });
82
+
83
+ describe("with custom errorTransform", () => {
84
+ const customTransform = vi.fn(
85
+ (error: unknown): CustomError => ({
86
+ code: 500,
87
+ message: String(error),
88
+ }),
89
+ );
90
+
91
+ const transformOptions: RuleSafetyOptions<CustomError> = {
92
+ errorTransform: customTransform,
93
+ };
94
+
95
+ it("should apply transform to throwing rules", async () => {
96
+ const rules = [errorThrowingRuleCustom];
97
+ const normalized = getNormalizedRules(rules, transformOptions);
98
+
99
+ // Test behavior instead of function reference
100
+ const result = await normalized[0]("test");
101
+ expect(result.status).toBe("failed");
102
+ expect((result as any).error).toEqual({
103
+ code: 500,
104
+ message: "Error: Boom!",
105
+ });
106
+ expect(customTransform).toHaveBeenCalled();
107
+ });
108
+
109
+ it("should not transform non-throwing rules", async () => {
110
+ const rules = [passingRuleCustom];
111
+ const normalized = getNormalizedRules(rules, transformOptions);
112
+
113
+ // Test behavior instead of function reference
114
+ const result = await normalized[0]("test");
115
+ expect(result).toEqual(pass());
116
+ expect(customTransform).not.toHaveBeenCalled();
117
+ });
118
+ });
119
+
120
+ describe("edge cases", () => {
121
+ it("should handle null/undefined rules array", () => {
122
+ expect(getNormalizedRules(null as any, {})).toEqual([]);
123
+ expect(getNormalizedRules(undefined as any, {})).toEqual([]);
124
+ });
125
+
126
+ it("should pass context through to normalized rules", async () => {
127
+ const context = { userId: 123 };
128
+ const contextAwareRule: Rule<string> = vi.fn((_, ctx) =>
129
+ ctx?.userId === 123 ? pass() : fail("Wrong context"),
130
+ );
131
+
132
+ const normalized = getNormalizedRules([contextAwareRule], {});
133
+ await normalized[0]("test", context);
134
+
135
+ expect(contextAwareRule).toHaveBeenCalledWith("test", context);
136
+ });
137
+ });
138
+ });
@@ -0,0 +1,14 @@
1
+ import { withSafeError } from "../../combinators";
2
+ import type { Rule, RuleSafetyOptions } from "../../types";
3
+
4
+ export const getNormalizedRules = <TInput, TError, TContext>(
5
+ rules: Rule<TInput, TError, TContext>[],
6
+ opts?: RuleSafetyOptions<TError>,
7
+ ): Rule<TInput, TError, TContext>[] => {
8
+ const normalizedRules =
9
+ opts?.errorHandlingMode === "unsafe"
10
+ ? rules
11
+ : (rules || [])?.map((rule) => withSafeError(rule, opts?.errorTransform));
12
+
13
+ return normalizedRules;
14
+ };
package/src/lib/index.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export * from "./combinators";
2
2
  export * from "./composition";
3
3
  export * from "./helpers";
4
- export * from "./types";
4
+ export type * from "./types";
@@ -1,7 +1,32 @@
1
+ import type { Prettify } from "./prettify";
2
+ import type { RuleSafetyOptions } from "./rule-safety-options";
3
+
1
4
  /**
2
5
  * Options for rule composition functions.
3
6
  * @property cloneContext - Whether to clone the context for each rule
7
+ * @property cloneStrategy - Which strategy to use when cloning the context
8
+ * @property errorHandling - Determines how the combinator handles thrown errors
9
+ * - "safe": (default) Catches errors and converts them to failed RuleResults
10
+ * - "unsafe": Lets errors propagate normally (for performance-critical cases)
11
+ *
12
+ * @property errorTransform - Optional custom error transformation function
13
+ * Only used when errorHandling="safe". Allows customizing how thrown errors
14
+ * are converted to the rule's error type.
15
+ *
16
+ *
17
+ * @warn
18
+ * - Cloning behavior follows this priority:
19
+ * 1. Uses shallowClone if options.cloneStrategy = "shallow"
20
+ * 2. Uses structuredClone if available and options.cloneStrategy = "structured"
21
+ * 3. Falls back to JSON clone otherwise
22
+ * - structuredClone requires Node 17+ or modern browsers
23
+ * - JSON clone will lose special types (Date, Map, etc.)
24
+ * - All clones convert undefined/null to empty object {}
25
+ * - Circular references fail silently in JSON clone mode
4
26
  */
5
- export type CompositionOptions = {
6
- cloneContext?: boolean;
7
- };
27
+ export type CompositionOptions<TError = string> = Prettify<
28
+ {
29
+ cloneContext?: boolean;
30
+ cloneStrategy?: "shallow" | "json" | "structured";
31
+ } & RuleSafetyOptions<TError>
32
+ >;
@@ -1,4 +1,4 @@
1
- import { RuleResult } from "./rule-result";
1
+ import type { RuleResult } from "./rule-result";
2
2
 
3
3
  /**
4
4
  * Configuration options for debug functionality.
@@ -1,4 +1,8 @@
1
- export * from "./composition-options";
2
- export * from "./debug-options";
3
- export * from "./rule-result";
4
- export * from "./rule";
1
+ export type * from "./composition-options";
2
+ export type * from "./debug-options";
3
+ export type * from "./rule-result";
4
+ export type * from "./rule";
5
+ export type * from "./rule-safety-options";
6
+ export type * from "./predicate";
7
+ export type * from "./predicate-result";
8
+ export type * from "./predicate-safe";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Represents the result of a predicate evaluation.
3
+ * @template TError - The type of the error (defaults to string)
4
+ * @example
5
+ * // Passed result, true value
6
+ * const passed: PredicateResult = { status: "passed", value: true };
7
+ *
8
+ * // Passed result, false value
9
+ * const passed: PredicateResult = { status: "passed", value: false };
10
+ *
11
+ *
12
+ * // Failed result
13
+ * const failed: PredicateResult = {
14
+ * status: "failed",
15
+ * error: "Validation failed"
16
+ * };
17
+ */
18
+ export type PredicateResult<TError = string> =
19
+ | { readonly status: "passed"; value: boolean }
20
+ | { readonly status: "failed"; readonly error: TError };
@@ -0,0 +1,10 @@
1
+ import type { PredicateResult } from "./predicate-result";
2
+
3
+ /**
4
+ * A predicate function that evaluates an input and returns a PredicateResult.
5
+ * Can be synchronous or asynchronous.
6
+ */
7
+ export type PredicateSafe<TInput, TError, TContext> = (
8
+ input: TInput,
9
+ context?: TContext,
10
+ ) => PredicateResult<TError> | Promise<PredicateResult<TError>>;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Configuration options for error handling behavior in rule combinators
3
+ * @template TError - The type of the error that will be caught and transformed (when safe)
4
+ *
5
+ *
6
+ * @property predicateErrorTransform - Optional custom error transformation function
7
+ * Only used when errorHandling="safe". Allows customizing how thrown errors
8
+ * are converted to the rule's error type.
9
+ *
10
+ *
11
+ * @example
12
+ * // Custom error transformation
13
+ * const rule = ifElse(
14
+ * (user) => user.age >= 18,
15
+ * validateAdultAccount,
16
+ * validateMinorAccount,
17
+ * {
18
+ * predicateErrorTransform: (err) => ({
19
+ * code: 500,
20
+ * message: String(err)
21
+ * })
22
+ * }
23
+ * );
24
+ */
25
+ export type PredicateSafetyOptions<TError = unknown> = {
26
+ predicateErrorTransform?: (error: unknown) => TError;
27
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A predicate function that evaluates an input and returns a boolean result.
3
+ * Can be synchronous or asynchronous.
4
+ */
5
+ export type Predicate<TInput, TContext> = (
6
+ input: TInput,
7
+ context?: TContext,
8
+ ) => boolean | Promise<boolean>;