ts-rules-composer 1.0.0 → 1.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 (103) hide show
  1. package/package.json +7 -1
  2. package/.editorconfig +0 -15
  3. package/.github/CONTRIBUTING.md +0 -3
  4. package/.github/ISSUE_TEMPLATE.md +0 -9
  5. package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
  6. package/.github/workflows/docs.yml +0 -29
  7. package/.github/workflows/publish.yml +0 -25
  8. package/.github/workflows/test.yml +0 -37
  9. package/.prettierignore +0 -2
  10. package/.releaserc +0 -11
  11. package/eslint.config.mjs +0 -84
  12. package/examples/financial-transaction.example.ts +0 -188
  13. package/examples/model-deployment.example.ts +0 -136
  14. package/examples/user-registration.example.ts +0 -101
  15. package/src/lib/combinators/index.ts +0 -2
  16. package/src/lib/combinators/logic/every.spec.ts +0 -264
  17. package/src/lib/combinators/logic/every.ts +0 -57
  18. package/src/lib/combinators/logic/if-else.spec.ts +0 -82
  19. package/src/lib/combinators/logic/if-else.ts +0 -64
  20. package/src/lib/combinators/logic/index.ts +0 -8
  21. package/src/lib/combinators/logic/match.spec.ts +0 -186
  22. package/src/lib/combinators/logic/match.ts +0 -106
  23. package/src/lib/combinators/logic/not.spec.ts +0 -64
  24. package/src/lib/combinators/logic/not.ts +0 -34
  25. package/src/lib/combinators/logic/one-of.spec.ts +0 -68
  26. package/src/lib/combinators/logic/one-of.ts +0 -48
  27. package/src/lib/combinators/logic/unless.spec.ts +0 -61
  28. package/src/lib/combinators/logic/unless.ts +0 -50
  29. package/src/lib/combinators/logic/when.spec.ts +0 -119
  30. package/src/lib/combinators/logic/when.ts +0 -50
  31. package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
  32. package/src/lib/combinators/logic/with-fallback.ts +0 -46
  33. package/src/lib/combinators/utility/index.ts +0 -11
  34. package/src/lib/combinators/utility/inject.spec.ts +0 -55
  35. package/src/lib/combinators/utility/inject.ts +0 -25
  36. package/src/lib/combinators/utility/map-error.spec.ts +0 -63
  37. package/src/lib/combinators/utility/map-error.ts +0 -35
  38. package/src/lib/combinators/utility/tap.spec.ts +0 -102
  39. package/src/lib/combinators/utility/tap.ts +0 -28
  40. package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
  41. package/src/lib/combinators/utility/validate-field.ts +0 -66
  42. package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
  43. package/src/lib/combinators/utility/with-debug.ts +0 -55
  44. package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
  45. package/src/lib/combinators/utility/with-memoize.ts +0 -89
  46. package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
  47. package/src/lib/combinators/utility/with-retry.ts +0 -70
  48. package/src/lib/combinators/utility/with-safe-error.spec.ts +0 -137
  49. package/src/lib/combinators/utility/with-safe-error.ts +0 -56
  50. package/src/lib/combinators/utility/with-safe-predicate.spec.ts +0 -176
  51. package/src/lib/combinators/utility/with-safe-predicate.ts +0 -64
  52. package/src/lib/combinators/utility/with-tap.spec.ts +0 -104
  53. package/src/lib/combinators/utility/with-tap.ts +0 -46
  54. package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
  55. package/src/lib/combinators/utility/with-timeout.ts +0 -41
  56. package/src/lib/composition/compose-rules.spec.ts +0 -211
  57. package/src/lib/composition/compose-rules.ts +0 -55
  58. package/src/lib/composition/index.ts +0 -3
  59. package/src/lib/composition/pipe-rules.spec.ts +0 -220
  60. package/src/lib/composition/pipe-rules.ts +0 -52
  61. package/src/lib/composition/pipe.spec.ts +0 -47
  62. package/src/lib/composition/pipe.ts +0 -107
  63. package/src/lib/helpers/clone/clone.ts +0 -12
  64. package/src/lib/helpers/clone/getCloneFn.ts +0 -17
  65. package/src/lib/helpers/clone/shallowClone.ts +0 -12
  66. package/src/lib/helpers/context/has-context.ts +0 -13
  67. package/src/lib/helpers/context/index.ts +0 -3
  68. package/src/lib/helpers/context/require-context.spec.ts +0 -55
  69. package/src/lib/helpers/context/require-context.ts +0 -61
  70. package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
  71. package/src/lib/helpers/context/with-lazy-context.ts +0 -35
  72. package/src/lib/helpers/index.ts +0 -8
  73. package/src/lib/helpers/result/fail.ts +0 -15
  74. package/src/lib/helpers/result/index.ts +0 -2
  75. package/src/lib/helpers/result/pass.ts +0 -14
  76. package/src/lib/helpers/retry/calculate-delay.ts +0 -31
  77. package/src/lib/helpers/safety/get-normalized-rule.spec.ts +0 -209
  78. package/src/lib/helpers/safety/get-normalized-rule.ts +0 -14
  79. package/src/lib/helpers/safety/get-normalized-rules.spec.ts +0 -138
  80. package/src/lib/helpers/safety/get-normalized-rules.ts +0 -14
  81. package/src/lib/index.ts +0 -4
  82. package/src/lib/types/composition-options.ts +0 -32
  83. package/src/lib/types/debug-options.ts +0 -36
  84. package/src/lib/types/index.ts +0 -8
  85. package/src/lib/types/predicate-result.ts +0 -20
  86. package/src/lib/types/predicate-safe.ts +0 -10
  87. package/src/lib/types/predicate-safety-options.ts +0 -27
  88. package/src/lib/types/predicate.ts +0 -8
  89. package/src/lib/types/prettify.ts +0 -3
  90. package/src/lib/types/rule-result.ts +0 -16
  91. package/src/lib/types/rule-safety-options.ts +0 -34
  92. package/src/lib/types/rule.ts +0 -21
  93. package/src/lib/types/safety-options.ts +0 -7
  94. package/src/test/financial-transaction.spec.ts +0 -251
  95. package/src/test/helpers/get-rule-error.ts +0 -23
  96. package/src/test/integration.spec.ts +0 -285
  97. package/src/test/model-deployment.spec.ts +0 -209
  98. package/src/test/user-registration.spec.ts +0 -164
  99. package/tsconfig.json +0 -56
  100. package/tsup.config.ts +0 -36
  101. package/typedoc/tsconfig.typedoc.json +0 -15
  102. package/typedoc/typedoc.json +0 -14
  103. package/vitest.config.ts +0 -16
@@ -1,264 +0,0 @@
1
- import { pass, fail } from "../../helpers";
2
-
3
- import { beforeEach, describe, expect, it, vi } from "vitest";
4
- import type { Rule } from "../../types";
5
- import { every } from "./every";
6
-
7
- describe("every", () => {
8
- const delay = (ms: number) =>
9
- new Promise((resolve) => setTimeout(resolve, ms));
10
-
11
- it("should return pass if no rules are provided", async () => {
12
- const result = await every([])({});
13
- expect(result).toEqual(pass());
14
- });
15
-
16
- it("should return pass if all rules pass", async () => {
17
- const rule1 = vi.fn(() => pass());
18
- const rule2 = vi.fn(() => pass());
19
- const validator = every([rule1, rule2]);
20
- const input = { foo: "bar" };
21
-
22
- const result = await validator(input);
23
-
24
- expect(result).toEqual(pass());
25
- expect(rule1).toHaveBeenCalledWith(input, undefined);
26
- expect(rule2).toHaveBeenCalledWith(input, undefined);
27
- });
28
-
29
- it("should collect all errors in parallel", async () => {
30
- const error1 = "Error 1";
31
- const error2 = "Error 2";
32
- const rule1 = vi.fn(() => fail(error1));
33
- const rule2 = vi.fn(async () => {
34
- await delay(10); // Ensure parallel execution
35
- return fail(error2);
36
- });
37
- const validator = every([rule1, rule2]);
38
- const input = { foo: "bar" };
39
-
40
- const result = await validator(input);
41
-
42
- expect(result).toEqual(fail([error1, error2]));
43
- expect(rule1).toHaveBeenCalledWith(input, undefined);
44
- expect(rule2).toHaveBeenCalledWith(input, undefined);
45
- });
46
-
47
- it("should maintain error order when rules fail", async () => {
48
- const error1 = "Error 1";
49
- const error2 = "Error 2";
50
- const rule1 = vi.fn(async () => {
51
- await delay(20);
52
- return fail(error1);
53
- });
54
- const rule2 = vi.fn(async () => {
55
- await delay(10);
56
- return fail(error2);
57
- });
58
- const validator = every([rule1, rule2]);
59
-
60
- const result = await validator({});
61
-
62
- // Order should match input rule order, not completion order
63
- expect(result).toEqual(fail([error1, error2]));
64
- });
65
-
66
- it("should pass context to all rules", async () => {
67
- const rule1 = vi.fn(() => pass());
68
- const rule2 = vi.fn(() => pass());
69
- const validator = every([rule1, rule2]);
70
- const input = { foo: "bar" };
71
- const context = { userId: 123 };
72
-
73
- await validator(input, context);
74
-
75
- expect(rule1).toHaveBeenCalledWith(input, context);
76
- expect(rule2).toHaveBeenCalledWith(input, context);
77
- });
78
- });
79
-
80
- describe("Niche errors", () => {
81
- it("should preserve custom error types", async () => {
82
- type CustomError = { code: number; message: string };
83
- const rule: Rule<unknown, CustomError> = () =>
84
- fail({ code: 400, message: "Bad" });
85
-
86
- const validator = every([rule]);
87
- const result = await validator({});
88
-
89
- expect(result).toEqual(fail([{ code: 400, message: "Bad" }]));
90
- });
91
-
92
- // Mixed sync/async rules
93
- it("should handle mixed sync/async rules", async () => {
94
- const syncRule = () => fail("Sync error");
95
- const asyncRule = async () => fail("Async error");
96
-
97
- const validator = every([syncRule, asyncRule]);
98
- const result = await validator({});
99
-
100
- expect(result).toEqual(fail(["Sync error", "Async error"]));
101
- });
102
-
103
- it("should handle 1000+ parallel rules", async () => {
104
- const manyRules = Array(1000).fill(() => pass());
105
- const validator = every(manyRules);
106
- await expect(validator({})).resolves.toEqual(pass());
107
- });
108
-
109
- it('should handle falsy error values (false, 0, "")', async () => {
110
- const rules = [() => fail(false), () => fail(0), () => fail("")];
111
- const validator = every(rules as any);
112
- const result = await validator({});
113
- expect(result).toEqual(fail([false, 0, ""]));
114
- });
115
- });
116
- // Error type propagation
117
-
118
- describe("Context behavior tests", () => {
119
- const countingRule = vi.fn((_: unknown, ctx: any) => {
120
- ctx.count = (ctx.count || 0) + 1;
121
- return pass();
122
- });
123
-
124
- // Context checker rule
125
- const expectCountRule = (expected: number) =>
126
- vi.fn((_: unknown, ctx: any) =>
127
- ctx.count === expected
128
- ? pass()
129
- : fail(`Expected count ${expected}, got ${ctx.count}`),
130
- );
131
-
132
- beforeEach(() => {
133
- vi.clearAllMocks();
134
- });
135
-
136
- it("should allow context mutation by default (shared reference)", async () => {
137
- const context = { count: 0 };
138
- const validator = every(
139
- [countingRule, countingRule, expectCountRule(2)], // Expect both mutations to apply
140
- );
141
-
142
- const result = await validator({}, context);
143
-
144
- expect(result).toEqual(pass());
145
- expect(context.count).toBe(2); // Original context modified
146
- });
147
-
148
- it("should prevent context mutations when cloneContext=true", async () => {
149
- const context = { count: 0 };
150
- const validator = every([countingRule, expectCountRule(1)], {
151
- cloneContext: true,
152
- });
153
-
154
- const result = await validator({}, context);
155
-
156
- expect(result).toEqual(pass());
157
- expect(context.count).toBe(0); // Original context untouched
158
- expect(countingRule.mock.calls[0][1].count).toBe(1); // First clone
159
- });
160
-
161
- it("should deep clone complex context objects", async () => {
162
- const context = { nested: { value: 0 } };
163
- const mutateNested = vi.fn((_, ctx) => {
164
- ctx.nested.value++;
165
- return pass();
166
- });
167
-
168
- const validator = every([mutateNested, mutateNested], {
169
- cloneContext: true,
170
- });
171
-
172
- await validator({}, context);
173
-
174
- expect(context.nested.value).toBe(0); // Original unchanged
175
- expect(mutateNested.mock.calls[0][1].nested.value).toBe(2); // First clone
176
- expect(mutateNested.mock.calls[1][1].nested.value).toBe(2); // Fresh clone
177
- });
178
-
179
- it("should handle null/undefined context", async () => {
180
- const nullValidator = every([], { cloneContext: true });
181
- await expect(nullValidator({}, null)).resolves.not.toThrow();
182
- await expect(nullValidator({}, undefined)).resolves.not.toThrow();
183
- });
184
-
185
- it("should shallow clone when possible for performance", async () => {
186
- const context = { simple: "value" };
187
- const validator = every(
188
- [
189
- (_, ctx) => {
190
- (ctx as any).simple = "changed";
191
- return pass();
192
- },
193
- ],
194
- { cloneContext: true },
195
- );
196
-
197
- await validator({}, context);
198
- expect(context.simple).toBe("value"); // Original unchanged
199
- });
200
- });
201
-
202
- it("should prevent accidental context mutation", async () => {
203
- const context = { count: 0 };
204
-
205
- const rule1 = (_: any, ctx: any) => {
206
- (ctx as any).count++; // Bad practice but test should handle
207
- return pass();
208
- };
209
-
210
- const rule2 = (_: any, ctx: any) => {
211
- if ((ctx as any).count !== 0) {
212
- return fail("Context mutated");
213
- }
214
- return pass();
215
- };
216
-
217
- const validator = every([rule1, rule2]);
218
- await expect(validator({}, context)).resolves.toEqual(
219
- fail(["Context mutated"]),
220
- );
221
- });
222
-
223
- it("should preserve custom generic types through composition", async () => {
224
- type CustomInput = { id: string };
225
- type CustomError = { severity: number };
226
-
227
- const rule: Rule<CustomInput, CustomError> = (input) =>
228
- input.id ? pass() : fail({ severity: 5 });
229
-
230
- const validator = every([rule]);
231
- const result1 = await validator({ id: "test" });
232
- const result2 = await validator({} as CustomInput);
233
-
234
- expect(result1).toEqual(pass());
235
- expect(result2).toEqual(fail([{ severity: 5 }]));
236
- });
237
-
238
- it("should not retain rule references after execution", async () => {
239
- let heavyObject = new Array(1e6).fill(0); // 1MB object
240
- const rule = () => {
241
- heavyObject = null!; // Simulate cleanup
242
- return pass();
243
- };
244
-
245
- const validator = every([rule]);
246
- await validator({});
247
-
248
- // This would fail if composition held references
249
- expect(() => heavyObject.length).toThrow();
250
- });
251
-
252
- it("should handle circular reference errors", async () => {
253
- const obj: any = { self: null };
254
- obj.self = obj;
255
-
256
- const validator = every([() => fail(obj), () => pass()]);
257
- const result = await validator({});
258
-
259
- expect(result.status).toBe("failed");
260
- // Check circular reference is preserved
261
- const errors = (result as any).error;
262
- expect(errors[0].self).toBe(errors[0]); // Verify circularity
263
- expect(errors).toEqual([obj]); // Verify error content
264
- });
@@ -1,57 +0,0 @@
1
- import { fail, getNormalizedRules, pass } from "../../helpers";
2
- import { getCloneFn } from "../../helpers/clone/getCloneFn";
3
- import type { CompositionOptions, Rule } from "../../types";
4
-
5
- /**
6
- * Composes multiple rules into a single rule that runs them all and collects all errors.
7
- * @template TInput - The type of the input to validate
8
- * @template TError - The type of the error (defaults to string)
9
- * @template TContext - The type of the context object (optional)
10
- * @param rules - Array of rules to compose
11
- * @param options - Configuration options
12
- * @param options.cloneContext - Whether to clone the context for each rule (default: false)
13
- * @param options.cloneStrategy -Which strategy to use when cloning the context
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
- * @returns A new rule that returns all errors from all failing rules
19
- * @example
20
- * const rule = every([
21
- * validatePresence,
22
- * validateEmail,
23
- * validateUnique
24
- * ]);
25
- *
26
- * const result = await rule("invalid-email");
27
- * if (result.status === "failed") {
28
- * console.log(result.error); // Array of all errors
29
- * }
30
- * @caveats
31
- * - Rules are executed in parallel (using Promise.all)
32
- * - All rules are executed even if some fail
33
- * - Cloning behavior follows this priority:
34
- * 1. Uses shallowClone if options.shallowClone = true
35
- * 2. Uses structuredClone if available and options.structuredClone = true
36
- * 3. Falls back to JSON clone otherwise
37
- */
38
- export const every = <TInput, TError = string, TContext = unknown>(
39
- rules: Rule<TInput, TError, TContext>[],
40
- options: CompositionOptions<TError> = {},
41
- ): Rule<TInput, TError[], TContext> => {
42
- return async (input: TInput, context?: TContext) => {
43
- const cloneFn = getCloneFn(options);
44
- const currentContext = options?.cloneContext ? cloneFn(context) : context;
45
- const normalizedRules = getNormalizedRules(rules, options);
46
-
47
- const results = await Promise.all(
48
- normalizedRules.map((rule) => rule(input, currentContext)),
49
- );
50
-
51
- const errors = results.flatMap((r) =>
52
- r.status === "failed" ? [r.error] : [],
53
- );
54
-
55
- return errors.length > 0 ? fail(errors) : pass();
56
- };
57
- };
@@ -1,82 +0,0 @@
1
- import { describe, vi, beforeEach, it, expect } from "vitest";
2
- import { pass, fail } from "../../helpers";
3
- import type { Rule } from "../../types";
4
- import { ifElse } from "./if-else";
5
-
6
- describe("branch", () => {
7
- const mockTruePredicate = vi.fn(() => true);
8
- const mockFalsePredicate = vi.fn(() => false);
9
- const asyncTruePredicate = vi.fn(async () => true);
10
- const mockThrowingPredicate = vi.fn(() => {
11
- throw new Error("Boom!");
12
- });
13
-
14
- const passingRule: Rule<string> = vi.fn(() => pass());
15
- const failingRule: Rule<string> = vi.fn(() => fail("Failed rule"));
16
- const contextAwareRule: Rule<string, string, { mode: string }> = vi.fn(
17
- (_, ctx) => (ctx?.mode === "test" ? pass() : fail("Invalid context")),
18
- );
19
-
20
- beforeEach(() => {
21
- vi.clearAllMocks();
22
- });
23
-
24
- it("should execute ifRule when predicate returns true", async () => {
25
- const rule = ifElse(mockTruePredicate, passingRule);
26
- const result = await rule("input");
27
- expect(result.status).toBe("passed");
28
- expect(mockTruePredicate).toHaveBeenCalledWith("input", undefined);
29
- expect(passingRule).toHaveBeenCalled();
30
- });
31
-
32
- it("should execute elseRule when provided and predicate returns false", async () => {
33
- const rule = ifElse(mockFalsePredicate, failingRule, passingRule);
34
- const result = await rule("input");
35
- expect(result.status).toBe("passed");
36
- expect(passingRule).toHaveBeenCalled();
37
- });
38
-
39
- it("should return pass() when no elseRule provided and predicate returns false", async () => {
40
- const rule = ifElse(mockFalsePredicate, failingRule);
41
- const result = await rule("input");
42
- expect(result.status).toBe("passed");
43
- expect(failingRule).not.toHaveBeenCalled();
44
- });
45
-
46
- it("should work with async predicates", async () => {
47
- const rule = ifElse(asyncTruePredicate, passingRule);
48
- const result = await rule("input");
49
- expect(result.status).toBe("passed");
50
- expect(asyncTruePredicate).toHaveBeenCalled();
51
- expect(passingRule).toHaveBeenCalled();
52
- });
53
-
54
- it("should pass context to both predicate and rules", async () => {
55
- const context = { mode: "test" };
56
- const rule = ifElse((_, ctx) => ctx?.mode === "test", contextAwareRule);
57
- const result = await rule("input", context);
58
- expect(result.status).toBe("passed");
59
- expect(contextAwareRule).toHaveBeenCalledWith("input", context);
60
- });
61
-
62
- it("should handle failing ifRule", async () => {
63
- const rule = ifElse(mockTruePredicate, failingRule);
64
- const result = await rule("input");
65
- expect(result.status).toBe("failed");
66
- expect(result).toEqual(fail("Failed rule"));
67
- });
68
-
69
- it("should handle failing elseRule", async () => {
70
- const rule = ifElse(mockFalsePredicate, passingRule, failingRule);
71
- const result = await rule("input");
72
- expect(result.status).toBe("failed");
73
- expect(result).toEqual(fail("Failed rule"));
74
- });
75
-
76
- it("should handle throwing predicate", async () => {
77
- const rule = ifElse(mockThrowingPredicate, passingRule, failingRule);
78
- const result = await rule("input");
79
- expect(result.status).toBe("failed");
80
- expect(result).toEqual(fail(new Error("Boom!")));
81
- });
82
- });
@@ -1,64 +0,0 @@
1
- import { fail, getNormalizedRules, pass } from "../../helpers";
2
- import type { Predicate, Rule } from "../../types";
3
- import type { SafetyOptions } from "../../types/safety-options";
4
- import { withSafePredicate } from "../utility";
5
-
6
- /**
7
- * Conditionally executes one of two rules based on a predicate
8
- * @template TInput - The type of the input to validate
9
- * @template TError - The type of the error (defaults to string)
10
- * @template TContext - The type of the context object (optional)
11
- * @param predicate - Function that determines which rule to execute
12
- * @param ifRule - Rule to execute when predicate returns true
13
- * @param elseRule - Rule to execute when predicate returns false (optional)
14
- * @param options - Configuration for error handling and predicate safety
15
- * @param options.errorHandlingMode - Determines how errors are handled:
16
- * - 'safe': (default) Converts thrown errors to validation failures
17
- * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
18
- * @param options.errorTransform - Custom transformation for caught errors
19
- * @param options.predicateErrorTransform - Special error handler for predicate failures
20
- * @returns A new rule that conditionally executes one of two rules
21
- * @example
22
- * const rule = ifElse(
23
- * (user) => user.age >= 18,
24
- * validateAdultAccount,
25
- * validateMinorAccount
26
- * );
27
- *
28
- * // Without elseRule (passes when predicate is false)
29
- * const adultOnlyRule = ifElse(
30
- * (user) => user.age >= 18,
31
- * validateAdultAccount
32
- * );
33
- */
34
- export const ifElse = <TInput, TError = string, TContext = unknown>(
35
- predicate: Predicate<TInput, TContext>,
36
- ifRule: Rule<TInput, TError, TContext>,
37
- elseRule?: Rule<TInput, TError, TContext>,
38
- options?: SafetyOptions<TError>,
39
- ): Rule<TInput, TError, TContext> => {
40
- return async (input: TInput, context?: TContext) => {
41
- const safePredicate = withSafePredicate<TInput, TError, TContext>(
42
- predicate,
43
- options?.predicateErrorTransform,
44
- );
45
- const safePredicateResult = await safePredicate(input, context);
46
-
47
- // Predicate fail to run or returned invalid result
48
- if (safePredicateResult.status === "failed") {
49
- return fail(safePredicateResult.error);
50
- }
51
-
52
- const [normalizedIfRule, normalizedElseRule] = getNormalizedRules(
53
- [ifRule, elseRule!],
54
- options,
55
- );
56
-
57
- const shouldBranch = safePredicateResult.value;
58
- return shouldBranch
59
- ? normalizedIfRule(input, context)
60
- : elseRule
61
- ? normalizedElseRule(input, context)
62
- : pass();
63
- };
64
- };
@@ -1,8 +0,0 @@
1
- export * from "./every";
2
- export * from "./if-else";
3
- export * from "./match";
4
- export * from "./not";
5
- export * from "./one-of";
6
- export * from "./unless";
7
- export * from "./when";
8
- export * from "./with-fallback";
@@ -1,186 +0,0 @@
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
- });