ts-rules-composer 0.0.1

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 (83) hide show
  1. package/.editorconfig +15 -0
  2. package/.eslintrc.json +66 -0
  3. package/.github/CONTRIBUTING.md +3 -0
  4. package/.github/ISSUE_TEMPLATE.md +9 -0
  5. package/.github/PULL_REQUEST_TEMPLATE.md +7 -0
  6. package/.github/workflows/docs.yml +29 -0
  7. package/.github/workflows/publish.yml +25 -0
  8. package/.github/workflows/test.yml +37 -0
  9. package/.prettierignore +2 -0
  10. package/.releaserc +11 -0
  11. package/LICENSE +21 -0
  12. package/README.md +625 -0
  13. package/dist/index.cjs +2 -0
  14. package/dist/index.cjs.map +1 -0
  15. package/dist/index.d.cts +634 -0
  16. package/dist/index.d.ts +634 -0
  17. package/dist/index.js +2 -0
  18. package/dist/index.js.map +1 -0
  19. package/package.json +64 -0
  20. package/src/lib/combinators/index.ts +2 -0
  21. package/src/lib/combinators/logic/every.spec.ts +264 -0
  22. package/src/lib/combinators/logic/every.ts +47 -0
  23. package/src/lib/combinators/logic/if-else.spec.ts +72 -0
  24. package/src/lib/combinators/logic/if-else.ts +39 -0
  25. package/src/lib/combinators/logic/index.ts +8 -0
  26. package/src/lib/combinators/logic/match.spec.ts +186 -0
  27. package/src/lib/combinators/logic/match.ts +92 -0
  28. package/src/lib/combinators/logic/not.spec.ts +62 -0
  29. package/src/lib/combinators/logic/not.ts +25 -0
  30. package/src/lib/combinators/logic/one-of.spec.ts +68 -0
  31. package/src/lib/combinators/logic/one-of.ts +41 -0
  32. package/src/lib/combinators/logic/unless.spec.ts +61 -0
  33. package/src/lib/combinators/logic/unless.ts +27 -0
  34. package/src/lib/combinators/logic/when.spec.ts +123 -0
  35. package/src/lib/combinators/logic/when.ts +29 -0
  36. package/src/lib/combinators/logic/with-fallback.spec.ts +72 -0
  37. package/src/lib/combinators/logic/with-fallback.ts +37 -0
  38. package/src/lib/combinators/utility/index.ts +8 -0
  39. package/src/lib/combinators/utility/inject.spec.ts +55 -0
  40. package/src/lib/combinators/utility/inject.ts +25 -0
  41. package/src/lib/combinators/utility/map-error.spec.ts +63 -0
  42. package/src/lib/combinators/utility/map-error.ts +35 -0
  43. package/src/lib/combinators/utility/tap.spec.ts +102 -0
  44. package/src/lib/combinators/utility/tap.ts +38 -0
  45. package/src/lib/combinators/utility/validate-field.spec.ts +150 -0
  46. package/src/lib/combinators/utility/validate-field.ts +59 -0
  47. package/src/lib/combinators/utility/with-debug.spec.ts +71 -0
  48. package/src/lib/combinators/utility/with-debug.ts +55 -0
  49. package/src/lib/combinators/utility/with-memoize.spec.ts +82 -0
  50. package/src/lib/combinators/utility/with-memoize.ts +81 -0
  51. package/src/lib/combinators/utility/with-retry.spec.ts +220 -0
  52. package/src/lib/combinators/utility/with-retry.ts +68 -0
  53. package/src/lib/combinators/utility/with-timeout.spec.ts +115 -0
  54. package/src/lib/combinators/utility/with-timeout.ts +34 -0
  55. package/src/lib/composition/compose-rules.spec.ts +211 -0
  56. package/src/lib/composition/compose-rules.ts +47 -0
  57. package/src/lib/composition/index.ts +3 -0
  58. package/src/lib/composition/pipe-rules.spec.ts +220 -0
  59. package/src/lib/composition/pipe-rules.ts +44 -0
  60. package/src/lib/composition/pipe.spec.ts +47 -0
  61. package/src/lib/composition/pipe.ts +106 -0
  62. package/src/lib/helpers/context/has-context.ts +13 -0
  63. package/src/lib/helpers/context/index.ts +3 -0
  64. package/src/lib/helpers/context/require-context.spec.ts +55 -0
  65. package/src/lib/helpers/context/require-context.ts +61 -0
  66. package/src/lib/helpers/context/with-lazy-context.spec.ts +74 -0
  67. package/src/lib/helpers/context/with-lazy-context.ts +35 -0
  68. package/src/lib/helpers/index.ts +6 -0
  69. package/src/lib/helpers/result/fail.ts +15 -0
  70. package/src/lib/helpers/result/index.ts +2 -0
  71. package/src/lib/helpers/result/pass.ts +14 -0
  72. package/src/lib/helpers/retry/calculate-delay.ts +31 -0
  73. package/src/lib/index.ts +4 -0
  74. package/src/lib/types/composition-options.ts +7 -0
  75. package/src/lib/types/debug-options.ts +36 -0
  76. package/src/lib/types/index.ts +4 -0
  77. package/src/lib/types/rule-result.ts +16 -0
  78. package/src/lib/types/rule.ts +21 -0
  79. package/src/test/helpers/get-rule-error.ts +23 -0
  80. package/src/test/integration.spec.ts +285 -0
  81. package/tsconfig.json +55 -0
  82. package/tsup.config.ts +36 -0
  83. package/vitest.config.ts +16 -0
@@ -0,0 +1,186 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { match } from "./match";
3
+ import type { Rule } from "../../types";
4
+
5
+ describe("match combinator", () => {
6
+ // Mock rules for testing
7
+ const mockPass = vi.fn().mockResolvedValue({ status: "passed" });
8
+ const mockFail = vi
9
+ .fn()
10
+ .mockResolvedValue({ status: "failed", error: "error" });
11
+ const mockAsyncPass = vi.fn().mockResolvedValue({ status: "passed" });
12
+
13
+ it("should execute the matching rule based on accessor", async () => {
14
+ const rules = {
15
+ admin: mockPass,
16
+ user: mockFail,
17
+ };
18
+ const matcher = match((user: { role: string }) => user.role, rules);
19
+ await matcher({ role: "admin" });
20
+
21
+ expect(mockPass).toHaveBeenCalledWith({ role: "admin" }, undefined);
22
+ expect(mockFail).not.toHaveBeenCalled();
23
+ });
24
+
25
+ it("should return the matched rule result", async () => {
26
+ const rules = {
27
+ admin: mockPass,
28
+ user: mockFail,
29
+ };
30
+ const matcher = match((user: { role: string }) => user.role, rules);
31
+ const result = await matcher({ role: "admin" });
32
+
33
+ expect(result).toEqual({ status: "passed" });
34
+ });
35
+
36
+ it("should use default case when no match found", async () => {
37
+ const rules = {
38
+ admin: mockPass,
39
+ };
40
+ const matcher = match(
41
+ (user: { role: string }) => user.role,
42
+ rules,
43
+ mockFail,
44
+ );
45
+ await matcher({ role: "guest" });
46
+
47
+ expect(mockFail).toHaveBeenCalledWith({ role: "guest" }, undefined);
48
+ });
49
+
50
+ it("should use default error when no match and no default rule", async () => {
51
+ const rules = {
52
+ admin: mockPass,
53
+ };
54
+ const matcher = match((user: { role: string }) => user.role, rules);
55
+ const result = await matcher({ role: "guest" });
56
+
57
+ expect(result).toEqual({
58
+ status: "failed",
59
+ error: "No matching rule for key: guest",
60
+ });
61
+ });
62
+
63
+ it("should work with custom error types", async () => {
64
+ interface CustomError {
65
+ code: number;
66
+ message: string;
67
+ }
68
+ const customError: CustomError = { code: 404, message: "Not found" };
69
+
70
+ const matcher = match<{ id: number }, CustomError>(
71
+ (item) => (item.id > 100 ? "special" : "normal"),
72
+ {
73
+ special: mockPass,
74
+ },
75
+ customError,
76
+ );
77
+
78
+ const result = await matcher({ id: 50 });
79
+ expect(result).toEqual({
80
+ status: "failed",
81
+ error: customError,
82
+ });
83
+ });
84
+
85
+ it("should pass context to matched rules", async () => {
86
+ const rules = {
87
+ admin: mockPass,
88
+ };
89
+ const context = { auth: true };
90
+ const matcher = match((user: { role: string }) => user.role, rules);
91
+ await matcher({ role: "admin" }, context);
92
+
93
+ expect(mockPass).toHaveBeenCalledWith({ role: "admin" }, context);
94
+ });
95
+
96
+ it("should handle async accessor functions", async () => {
97
+ const rules = {
98
+ admin: mockPass,
99
+ };
100
+ const matcher = match(async (user: { role: string }) => {
101
+ await Promise.resolve();
102
+ return user.role;
103
+ }, rules);
104
+ await matcher({ role: "admin" });
105
+
106
+ expect(mockPass).toHaveBeenCalled();
107
+ });
108
+
109
+ it("should work with numeric keys", async () => {
110
+ const rules = {
111
+ 1: mockPass,
112
+ 2: mockFail,
113
+ };
114
+ const matcher = match((item: { code: number }) => item.code, rules);
115
+ await matcher({ code: 1 });
116
+
117
+ expect(mockPass).toHaveBeenCalled();
118
+ });
119
+
120
+ it("should work with symbol keys", async () => {
121
+ const TEST_SYMBOL = Symbol("test");
122
+ const rules = {
123
+ [TEST_SYMBOL]: mockPass,
124
+ };
125
+ const matcher = match(() => TEST_SYMBOL, rules);
126
+ await matcher({});
127
+
128
+ expect(mockPass).toHaveBeenCalled();
129
+ });
130
+
131
+ it("should handle default case as error string", async () => {
132
+ const rules = {
133
+ admin: mockPass,
134
+ };
135
+ const matcher = match(
136
+ (user: { role: string }) => user.role,
137
+ rules,
138
+ "Invalid role",
139
+ );
140
+ const result = await matcher({ role: "guest" });
141
+
142
+ expect(result).toEqual({
143
+ status: "failed",
144
+ error: "Invalid role",
145
+ });
146
+ });
147
+
148
+ it("should handle default case as Rule", async () => {
149
+ const rules = {
150
+ admin: mockPass,
151
+ };
152
+ const matcher = match(
153
+ (user: { role: string }) => user.role,
154
+ rules,
155
+ mockAsyncPass,
156
+ );
157
+ await matcher({ role: "guest" });
158
+
159
+ expect(mockAsyncPass).toHaveBeenCalled();
160
+ });
161
+
162
+ it("should maintain type safety with complex inputs", async () => {
163
+ interface ComplexInput {
164
+ nested: {
165
+ value: string;
166
+ items: number[];
167
+ };
168
+ }
169
+
170
+ const complexRule: Rule<ComplexInput> = () =>
171
+ Promise.resolve({ status: "passed" });
172
+
173
+ const matcher = match((input: ComplexInput) => input.nested.value, {
174
+ test: complexRule,
175
+ });
176
+
177
+ const result = await matcher({
178
+ nested: {
179
+ value: "test",
180
+ items: [1, 2, 3],
181
+ },
182
+ });
183
+
184
+ expect(result.status).toBe("passed");
185
+ });
186
+ });
@@ -0,0 +1,92 @@
1
+ import { fail } from "../../helpers";
2
+ import { Rule, RuleResult } from "../../types";
3
+
4
+ const isRule = <TInput, TError, TContext>(
5
+ value: unknown,
6
+ ): value is Rule<TInput, TError, TContext> => {
7
+ return typeof value === "function";
8
+ };
9
+
10
+ /**
11
+ * Pattern-matching combinator that selects a rule based on a key extracted from input.
12
+ * @template TInput - The type of the input to validate
13
+ * @template TError - The type of the error (defaults to string)
14
+ * @template TContext - The type of the context object (optional)
15
+ * @template TKey - The type of the branch key (must be string | number | symbol)
16
+ * @param accessor - Function that extracts the match key from input
17
+ * @param cases - Object mapping keys to their corresponding rules
18
+ * @param defaultCase - Optional default rule or error when no match is found
19
+ * @returns A new rule that executes the matching case's rule
20
+ * @example
21
+ * // Basic usage with string error type
22
+ * const validatePayment = match(
23
+ * (order) => order.paymentMethod,
24
+ * {
25
+ * credit: validateCreditCard,
26
+ * paypal: validatePayPal,
27
+ * crypto: validateCrypto
28
+ * },
29
+ * "Unsupported payment method"
30
+ * );
31
+ *
32
+ * @example
33
+ * // With custom error type
34
+ * interface ValidationError { code: number; message: string }
35
+ * const validateStatus = match<Order, ValidationError>(
36
+ * (order) => order.status,
37
+ * {
38
+ * pending: validatePendingOrder,
39
+ * completed: validateCompletedOrder
40
+ * },
41
+ * { code: 400, message: "Invalid status" }
42
+ * );
43
+ *
44
+ * @example
45
+ * // With default rule instead of error
46
+ * const validateProduct = match(
47
+ * (product) => product.type,
48
+ * {
49
+ * book: validateBook,
50
+ * digital: validateDigitalProduct
51
+ * },
52
+ * validateGenericProduct
53
+ * );
54
+ *
55
+ * @caveats
56
+ * - The accessor function should return a primitive value (string/number/symbol)
57
+ * - If no matching case is found and no default is provided, returns a failed result with:
58
+ * - A string error when TError is string (default)
59
+ * - A type-asserted error when TError is custom (may require type casting)
60
+ * - All case rules must have compatible input/context types
61
+ * - For conditional branching (true/false), consider using `branch` instead
62
+ */
63
+ export const match = <
64
+ TInput,
65
+ TError = string,
66
+ TContext = unknown,
67
+ TKey extends string | number | symbol = string,
68
+ >(
69
+ accessor: (input: TInput, context?: TContext) => TKey | Promise<TKey>,
70
+ cases: Record<TKey, Rule<TInput, TError, TContext>>,
71
+ defaultCase?: Rule<TInput, TError, TContext> | TError,
72
+ ): Rule<TInput, TError, TContext> => {
73
+ return async (
74
+ input: TInput,
75
+ context?: TContext,
76
+ ): Promise<RuleResult<TError>> => {
77
+ const key = await accessor(input, context);
78
+ const matchedRule = cases[key];
79
+
80
+ if (matchedRule) {
81
+ return matchedRule(input, context);
82
+ }
83
+
84
+ if (defaultCase !== undefined) {
85
+ return isRule<TInput, TError, TContext>(defaultCase)
86
+ ? defaultCase(input, context)
87
+ : fail(defaultCase);
88
+ }
89
+
90
+ return fail(`No matching rule for key: ${String(key)}` as TError);
91
+ };
92
+ };
@@ -0,0 +1,62 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { fail, pass } from "../../helpers";
3
+ import { not } from "./not";
4
+
5
+ describe("not combinator", () => {
6
+ const mockRule = vi.fn(() => pass());
7
+ const errorMsg = "Inverted error";
8
+
9
+ beforeEach(() => {
10
+ vi.clearAllMocks();
11
+ });
12
+
13
+ it("should invert pass to fail", async () => {
14
+ const invertedRule = not(mockRule, errorMsg);
15
+ const result = await invertedRule({});
16
+
17
+ expect(result).toEqual(fail(errorMsg));
18
+ expect(mockRule).toHaveBeenCalled();
19
+ });
20
+
21
+ it("should invert fail to pass", async () => {
22
+ const failingRule = vi.fn(() => fail("Original error"));
23
+ const invertedRule = not(failingRule, errorMsg);
24
+ const result = await invertedRule({});
25
+
26
+ expect(result).toEqual(pass());
27
+ expect(failingRule).toHaveBeenCalled();
28
+ });
29
+
30
+ it("should preserve context", async () => {
31
+ const context = { userId: 123 };
32
+ const contextAwareRule = vi.fn((_, ctx) =>
33
+ ctx?.userId === 123 ? pass() : fail("Wrong user"),
34
+ );
35
+
36
+ const invertedRule = not(contextAwareRule, errorMsg);
37
+ await invertedRule({}, context);
38
+
39
+ expect(contextAwareRule).toHaveBeenCalledWith({}, context);
40
+ });
41
+
42
+ it("should handle async rules", async () => {
43
+ const asyncRule = vi.fn(async () => {
44
+ await Promise.resolve();
45
+ return pass();
46
+ });
47
+
48
+ const invertedRule = not(asyncRule, errorMsg);
49
+ const result = await invertedRule({});
50
+
51
+ expect(result).toEqual(fail(errorMsg));
52
+ });
53
+
54
+ it("should propagate rule errors", async () => {
55
+ const errorRule = vi.fn(() => {
56
+ throw new Error("Boom!");
57
+ });
58
+
59
+ const invertedRule = not(errorRule, errorMsg);
60
+ await expect(invertedRule({})).rejects.toThrow("Boom!");
61
+ });
62
+ });
@@ -0,0 +1,25 @@
1
+ import { pass, fail } from "../../helpers";
2
+ import { Rule } from "../../types/rule";
3
+
4
+ /**
5
+ * Inverts the logic of a rule - passes when original fails and vice versa.
6
+ * @template TInput - The type of the input to validate
7
+ * @template TError - The type of the error (defaults to string)
8
+ * @param rule - The rule to invert
9
+ * @param error - The error to return when original rule passes
10
+ * @returns A new rule with inverted logic
11
+ * @example
12
+ * const isNotAdmin = not(isAdmin, "User must not be admin");
13
+ * @caveats
14
+ * - The original rule's error is discarded when it fails
15
+ * - Always uses the provided error when original passes
16
+ */
17
+ export const not = <TInput, TError = string>(
18
+ rule: Rule<TInput, TError>,
19
+ error: TError,
20
+ ): Rule<TInput, TError> => {
21
+ return async (input: TInput, context?: unknown) => {
22
+ const result = await rule(input, context);
23
+ return result.status === "passed" ? fail(error) : pass();
24
+ };
25
+ };
@@ -0,0 +1,68 @@
1
+ import { describe, beforeEach, it, expect, vi } from "vitest";
2
+ import { fail, pass } from "../../helpers";
3
+ import { Rule } from "../../types";
4
+ import { oneOf } from "./one-of";
5
+
6
+ describe("oneOf combinator", () => {
7
+ const passingRule = vi.fn(() => pass());
8
+ const failingRule1 = vi.fn(() => fail("Error 1"));
9
+ const failingRule2 = vi.fn(() => fail("Error 2"));
10
+
11
+ beforeEach(() => {
12
+ vi.clearAllMocks();
13
+ });
14
+
15
+ it("should pass if any rule passes", async () => {
16
+ const validator = oneOf(failingRule1, passingRule, failingRule2);
17
+ const result = await validator({});
18
+
19
+ expect(result).toEqual(pass());
20
+ expect(failingRule1).toHaveBeenCalled();
21
+ expect(passingRule).toHaveBeenCalled();
22
+ expect(failingRule2).not.toHaveBeenCalled(); // Short-circuits
23
+ });
24
+
25
+ it("should fail with all errors if no rules pass", async () => {
26
+ const validator = oneOf(failingRule1, failingRule2);
27
+ const result = await validator({});
28
+
29
+ expect(result).toEqual(fail(["Error 1", "Error 2"]));
30
+ });
31
+
32
+ it("should handle empty rules array", async () => {
33
+ const validator = oneOf();
34
+ const result = await validator({});
35
+
36
+ expect(result).toEqual(pass()); // Vacuous truth
37
+ });
38
+
39
+ it("should pass context to all rules", async () => {
40
+ const context = { userId: 123 };
41
+ const rule = vi.fn(() => pass());
42
+
43
+ await oneOf(rule)({}, context);
44
+ expect(rule).toHaveBeenCalledWith({}, context);
45
+ });
46
+
47
+ it("should work with async rules", async () => {
48
+ const asyncRule = vi.fn(async () => {
49
+ await Promise.resolve();
50
+ return pass();
51
+ });
52
+
53
+ const result = await oneOf(asyncRule)({});
54
+ expect(result).toEqual(pass());
55
+ });
56
+
57
+ // Type safety tests
58
+ it("should enforce rule type matching", () => {
59
+ type StrictInput = { id: string };
60
+ const typedRule: Rule<StrictInput, string> = () => pass();
61
+
62
+ // Valid usage
63
+ oneOf(typedRule, () => fail("Error"));
64
+
65
+ // @ts-expect-error - Should fail if input types mismatch
66
+ oneOf(typedRule, (input: { other: number }) => pass());
67
+ });
68
+ });
@@ -0,0 +1,41 @@
1
+ import { fail, pass } from "../../helpers";
2
+ import { Rule } from "../../types";
3
+
4
+ /**
5
+ * Creates a rule that passes if any of the provided rules pass (short-circuiting).
6
+ * @template TInput - The type of the input to validate
7
+ * @template TError - The type of the error (defaults to string)
8
+ * @template TContext - The type of the context object (optional)
9
+ * @param rules - Rules to try (in order)
10
+ * @returns A rule that passes if any rule passes, or fails with all errors
11
+ * @example
12
+ * const rule = oneOf(
13
+ * validateEmail,
14
+ * validatePhone,
15
+ * validateUsername
16
+ * );
17
+ * @caveats
18
+ * - Rules are executed in sequence until one passes
19
+ * - Returns all errors if all rules fail
20
+ */
21
+ export const oneOf = <TInput, TError = string, TContext = unknown>(
22
+ ...rules: Rule<TInput, TError, TContext>[]
23
+ ): Rule<TInput, TError[], TContext> => {
24
+ return async (input: TInput, context?: TContext) => {
25
+ const errors: TError[] = [];
26
+
27
+ if (!rules || rules.length === 0) {
28
+ return pass();
29
+ }
30
+
31
+ for (const rule of rules) {
32
+ const result = await rule(input, context);
33
+ if (result.status === "passed") {
34
+ return pass();
35
+ }
36
+ errors.push(result.error);
37
+ }
38
+
39
+ return fail(errors);
40
+ };
41
+ };
@@ -0,0 +1,61 @@
1
+ import { describe, vi, beforeEach, it, expect } from "vitest";
2
+ import { fail, pass } from "../../helpers";
3
+ import { Rule } from "../../types";
4
+ import { unless } from "./unless";
5
+
6
+ describe("unless combinator", () => {
7
+ const mockRule = vi.fn(() => fail("Rule executed"));
8
+ const isAdmin = (input: { role: string }) => input.role === "admin";
9
+
10
+ beforeEach(() => {
11
+ vi.clearAllMocks();
12
+ });
13
+
14
+ it("should skip rule when predicate is true", async () => {
15
+ const validateUnlessAdmin = unless(isAdmin, mockRule);
16
+ const result = await validateUnlessAdmin({ role: "admin" });
17
+
18
+ expect(result).toEqual(pass());
19
+ expect(mockRule).not.toHaveBeenCalled();
20
+ });
21
+
22
+ it("should run rule when predicate is false", async () => {
23
+ const validateUnlessAdmin = unless(isAdmin, mockRule);
24
+ const result = await validateUnlessAdmin({ role: "user" });
25
+
26
+ expect(result).toEqual(fail("Rule executed"));
27
+ expect(mockRule).toHaveBeenCalled();
28
+ });
29
+
30
+ it("should pass context to the rule", async () => {
31
+ const context = { logger: console };
32
+ const rule = vi.fn(() => pass());
33
+ const validator = unless(() => false, rule);
34
+
35
+ await validator({}, context);
36
+ expect(rule).toHaveBeenCalledWith({}, context);
37
+ });
38
+
39
+ it("should handle async predicates", async () => {
40
+ const asyncPredicate = async (input: { id: number }) => {
41
+ await Promise.resolve();
42
+ return input.id > 10;
43
+ };
44
+ const validator = unless(asyncPredicate, mockRule);
45
+
46
+ await validator({ id: 5 });
47
+ expect(mockRule).toHaveBeenCalled();
48
+ });
49
+
50
+ // Type safety tests
51
+ it("should enforce predicate input type", () => {
52
+ type StrictInput = { id: string };
53
+ const typedRule: Rule<StrictInput> = () => pass();
54
+
55
+ // Valid usage
56
+ unless((input: StrictInput) => !!input.id, typedRule);
57
+
58
+ // @ts-expect-error - Should fail if predicate expects wrong type
59
+ unless((input: { other: number }) => true, typedRule);
60
+ });
61
+ });
@@ -0,0 +1,27 @@
1
+ import type { Rule } from "../../types";
2
+ import { pass } from "../../helpers";
3
+
4
+ /**
5
+ * Executes a rule only if the predicate returns false.
6
+ * @template TInput - The type of the input to validate
7
+ * @template TError - The type of the error (defaults to string)
8
+ * @template TContext - The type of the context object (optional)
9
+ * @param predicate - Condition to check
10
+ * @param rule - Rule to execute when predicate is false
11
+ * @returns A rule that conditionally executes based on the predicate
12
+ * @example
13
+ * const rule = unless(
14
+ * (user) => user.isVerified,
15
+ * requireVerification
16
+ * );
17
+ * @caveats
18
+ * - Opposite behavior of `when`
19
+ * - Automatically passes when predicate is true
20
+ */
21
+ export const unless = <TInput, TError = string, TContext = unknown>(
22
+ predicate: (input: TInput) => Promise<boolean> | boolean,
23
+ rule: Rule<TInput, TError, TContext>,
24
+ ): Rule<TInput, TError, TContext> => {
25
+ return async (input: TInput, context?: TContext) =>
26
+ (await predicate(input)) ? pass() : rule(input, context);
27
+ };
@@ -0,0 +1,123 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { when } from "./when";
3
+ import { pass } from "../../helpers/result/pass";
4
+ import { fail } from "../../helpers/result/fail";
5
+
6
+ describe("when combinator", () => {
7
+ const mockRule = vi.fn(() => pass());
8
+ const mockPredicateTrue = vi.fn((_: any) => true);
9
+ const mockPredicateFalse = vi.fn((_: any) => false);
10
+
11
+ beforeEach(() => {
12
+ vi.clearAllMocks();
13
+ });
14
+
15
+ // Basic functionality
16
+ it("should apply rule when condition is true", async () => {
17
+ const conditionalRule = when(mockPredicateTrue, mockRule);
18
+ const input = { active: true };
19
+
20
+ await conditionalRule(input);
21
+
22
+ expect(mockPredicateTrue).toHaveBeenCalledWith(input);
23
+ expect(mockRule).toHaveBeenCalledWith(input, undefined);
24
+ });
25
+
26
+ it("should skip rule when condition is false", async () => {
27
+ const conditionalRule = when(mockPredicateFalse, mockRule);
28
+ const input = { active: false };
29
+ const result = await conditionalRule(input);
30
+
31
+ expect(mockPredicateFalse).toHaveBeenCalledWith(input);
32
+ expect(result).toEqual(pass());
33
+ expect(mockRule).not.toHaveBeenCalled();
34
+ });
35
+
36
+ it("should work with async predicates", async () => {
37
+ const conditionalRule = when(async (input: { id: number }) => {
38
+ await Promise.resolve();
39
+ return input.id > 10;
40
+ }, mockRule);
41
+
42
+ await conditionalRule({ id: 20 });
43
+ expect(mockRule).toHaveBeenCalled();
44
+
45
+ mockRule.mockClear();
46
+ await conditionalRule({ id: 5 });
47
+ expect(mockRule).not.toHaveBeenCalled();
48
+ });
49
+
50
+ it("should handle mixed async predicates with sync rules", async () => {
51
+ const conditionalRule = when(async (input: { value: number }) => {
52
+ await Promise.resolve();
53
+ return input.value > 5;
54
+ }, mockRule);
55
+
56
+ await conditionalRule({ value: 10 });
57
+ expect(mockRule).toHaveBeenCalled();
58
+ });
59
+
60
+ it("should handle falsy conditions", async () => {
61
+ const testCases = [
62
+ { condition: false, shouldRun: false },
63
+ { condition: 0, shouldRun: false },
64
+ { condition: "", shouldRun: false },
65
+ { condition: null, shouldRun: false },
66
+ { condition: undefined, shouldRun: false },
67
+ ];
68
+
69
+ for (const { condition, shouldRun } of testCases) {
70
+ const conditionalRule = when(() => condition as any, mockRule);
71
+ await conditionalRule({});
72
+ expect(mockRule.mock.calls.length).toBe(shouldRun ? 1 : 0);
73
+ mockRule.mockClear();
74
+ }
75
+ });
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
+ it("should work with async rules needing context", async () => {
88
+ const context = {
89
+ db: {
90
+ findUser: async (_id: string) => true,
91
+ },
92
+ };
93
+ const validate = when(
94
+ (input: { id: string }) => !!input.id,
95
+ async (input, ctx: any) => {
96
+ const exists = await ctx.db.findUser(input.id);
97
+ return exists ? pass() : fail("Not found");
98
+ },
99
+ );
100
+
101
+ await validate({ id: "123" }, context);
102
+ });
103
+
104
+ // Error cases
105
+ it("should propagate condition errors", async () => {
106
+ const errorCondition = () => {
107
+ throw new Error("Condition failed");
108
+ };
109
+ const conditionalRule = when(errorCondition, mockRule);
110
+
111
+ expect(conditionalRule({})).rejects.toThrow("Condition failed");
112
+ expect(mockRule).not.toHaveBeenCalled();
113
+ });
114
+
115
+ it("should propagate rule errors when condition passes", async () => {
116
+ const errorRule = () => {
117
+ throw new Error("Rule failed");
118
+ };
119
+ const conditionalRule = when(() => true, errorRule);
120
+
121
+ expect(conditionalRule({})).rejects.toThrow("Rule failed");
122
+ });
123
+ });