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,34 @@
1
+ import { fail } from "../../helpers";
2
+ import { Rule, RuleResult } from "../../types";
3
+
4
+ /**
5
+ * Wraps a rule with timeout functionality.
6
+ * @template TInput - The type of the input to validate
7
+ * @template TError - The type of the error
8
+ * @template TContext - The type of the context object
9
+ * @param rule - The rule to wrap with timeout
10
+ * @param timeoutMs - Timeout duration in milliseconds
11
+ * @param timeoutError - Error to return if timeout occurs
12
+ * @returns A new rule that fails with timeoutError if execution takes longer than timeoutMs
13
+ * @example
14
+ * const rule = withTimeout(
15
+ * slowNetworkRequestRule,
16
+ * 5000, // 5 seconds
17
+ * "Request timed out"
18
+ * );
19
+ * @caveats
20
+ * - The original rule's execution isn't aborted when timeout occurs
21
+ * - Only fails if the rule doesn't complete before timeout, not if it fails before timeout
22
+ */
23
+ export const withTimeout = <TInput, TError, TContext>(
24
+ rule: Rule<TInput, TError, TContext>,
25
+ timeoutMs: number,
26
+ timeoutError: TError,
27
+ ): Rule<TInput, TError, TContext> => {
28
+ return async (input, context) => {
29
+ const timeout = new Promise<RuleResult<TError>>((resolve) =>
30
+ setTimeout(() => resolve(fail(timeoutError)), timeoutMs),
31
+ );
32
+ return Promise.race([rule(input, context), timeout]);
33
+ };
34
+ };
@@ -0,0 +1,211 @@
1
+ import { composeRules } from "./compose-rules";
2
+ import { fail, pass } from "../helpers";
3
+ import { beforeEach, describe, expect, it, vi } from "vitest";
4
+ import { Rule } from "../types";
5
+
6
+ describe("composeRules", () => {
7
+ const alwaysPass = vi.fn(() => pass());
8
+ const failWithMsg = (msg: string) => vi.fn(() => fail(msg));
9
+
10
+ beforeEach(() => {
11
+ vi.clearAllMocks();
12
+ });
13
+
14
+ it("should return pass if no rules are provided", async () => {
15
+ const result = await composeRules([])({});
16
+ expect(result).toEqual(pass());
17
+ });
18
+
19
+ it("should return pass if all rules pass", async () => {
20
+ const rule1 = alwaysPass;
21
+ const rule2 = alwaysPass;
22
+ const validator = composeRules([rule1, rule2]);
23
+ const input = { foo: "bar" };
24
+
25
+ const result = await validator(input);
26
+
27
+ expect(result).toEqual(pass());
28
+ expect(rule2).toHaveBeenCalledWith(input, undefined); // called last
29
+ expect(rule1).toHaveBeenCalledWith(input, undefined); // called first
30
+ });
31
+
32
+ it("should fail fast on first failure (right-to-left)", async () => {
33
+ const errorMsg = "First error";
34
+ const rule1 = failWithMsg(errorMsg);
35
+ const rule2 = alwaysPass;
36
+ const validator = composeRules([rule2, rule1]); // rule1 runs first (right-to-left)
37
+
38
+ const result = await validator({});
39
+
40
+ expect(result).toEqual(fail(errorMsg));
41
+ expect(rule1).toHaveBeenCalled();
42
+ expect(rule2).not.toHaveBeenCalled(); // skipped
43
+ });
44
+
45
+ it("should pass context to all rules", async () => {
46
+ const rule1 = vi.fn(() => pass());
47
+ const rule2 = vi.fn(() => pass());
48
+ const validator = composeRules([rule1, rule2]);
49
+ const context = { some: "ctx" };
50
+ await validator({}, context);
51
+ expect(rule1).toHaveBeenCalledWith({}, context);
52
+ expect(rule2).toHaveBeenCalledWith({}, context);
53
+ });
54
+
55
+ it("should preserve custom error types", async () => {
56
+ type CustomError = { code: number };
57
+ const rule: Rule<unknown, CustomError> = () => fail({ code: 123 });
58
+
59
+ const validator = composeRules([rule]);
60
+ const result = await validator({});
61
+
62
+ expect(result).toEqual(fail({ code: 123 }));
63
+ });
64
+
65
+ it("should handle 1000+ rules without stack overflow", async () => {
66
+ const manyRules = Array(1000).fill(() => pass());
67
+ const validator = composeRules(manyRules);
68
+ await expect(validator({})).resolves.toEqual(pass());
69
+ });
70
+
71
+ describe("Context behavior tests", () => {
72
+ const countingRule = vi.fn((_: unknown, ctx: any) => {
73
+ ctx.count = (ctx.count || 0) + 1;
74
+ return pass();
75
+ });
76
+
77
+ const expectCountRule = (expected: number) =>
78
+ vi.fn((_: unknown, ctx: any) =>
79
+ ctx.count === expected
80
+ ? pass()
81
+ : fail(`Expected count ${expected}, got ${ctx.count}`),
82
+ );
83
+
84
+ beforeEach(() => {
85
+ vi.clearAllMocks();
86
+ });
87
+
88
+ it("should allow context mutation by default", async () => {
89
+ const context = { count: 0 };
90
+ const validator = composeRules([
91
+ expectCountRule(2),
92
+ countingRule,
93
+ countingRule,
94
+ ]);
95
+
96
+ const result = await validator({}, context);
97
+ expect(result).toEqual(pass());
98
+ expect(context.count).toBe(2);
99
+ });
100
+
101
+ it("should prevent context mutations when cloneContext=true", async () => {
102
+ const context = { count: 0 };
103
+ const validator = composeRules([expectCountRule(1), countingRule], {
104
+ cloneContext: true,
105
+ });
106
+
107
+ const result = await validator({}, context);
108
+ expect(result).toEqual(pass());
109
+ expect(context.count).toBe(0);
110
+ });
111
+
112
+ it("should deep clone complex context", async () => {
113
+ const context = { nested: { value: 0 } };
114
+ const mutateNested = vi.fn((_, ctx) => {
115
+ ctx.nested.value++;
116
+ return pass();
117
+ });
118
+
119
+ const validator = composeRules([mutateNested, mutateNested], {
120
+ cloneContext: true,
121
+ });
122
+
123
+ await validator({}, context);
124
+
125
+ expect(context.nested.value).toBe(0);
126
+ expect(mutateNested.mock.calls[0][1].nested.value).toBe(2);
127
+ expect(mutateNested.mock.calls[1][1].nested.value).toBe(2);
128
+ });
129
+
130
+ it("should handle null/undefined context safely", async () => {
131
+ const validator = composeRules([], { cloneContext: true });
132
+ await expect(validator({}, null)).resolves.not.toThrow();
133
+ await expect(validator({}, undefined)).resolves.not.toThrow();
134
+ });
135
+
136
+ it("should shallow clone flat objects", async () => {
137
+ const context = { simple: "abc" };
138
+ const validator = composeRules(
139
+ [
140
+ (_, ctx: any) => {
141
+ ctx.simple = "modified";
142
+ return pass();
143
+ },
144
+ ],
145
+ { cloneContext: true },
146
+ );
147
+
148
+ await validator({}, context);
149
+ expect(context.simple).toBe("abc");
150
+ });
151
+ });
152
+
153
+ it("should prevent accidental context mutation", async () => {
154
+ const context = { count: 0 };
155
+
156
+ const rule1 = (_: any, ctx: any) => {
157
+ ctx.count++;
158
+ return pass();
159
+ };
160
+
161
+ const rule2 = (_: any, ctx: any) => {
162
+ if (ctx.count !== 0) {
163
+ return fail("Context mutated");
164
+ }
165
+ return pass();
166
+ };
167
+
168
+ const validator = composeRules([rule2, rule1]);
169
+ const result = await validator({}, context);
170
+ expect(result).toEqual(fail("Context mutated"));
171
+ });
172
+
173
+ it("should preserve custom generics", async () => {
174
+ type Input = { id: string };
175
+ type Error = { level: number };
176
+
177
+ const rule: Rule<Input, Error> = (input) =>
178
+ input.id ? pass() : fail({ level: 2 });
179
+
180
+ const validator = composeRules([rule]);
181
+
182
+ const valid = await validator({ id: "1" });
183
+ const invalid = await validator({} as Input);
184
+
185
+ expect(valid).toEqual(pass());
186
+ expect(invalid).toEqual(fail({ level: 2 }));
187
+ });
188
+
189
+ it("should not retain rule references post-execution", async () => {
190
+ let heavy = new Array(1e6).fill("x");
191
+ const rule = () => {
192
+ heavy = null!;
193
+ return pass();
194
+ };
195
+
196
+ const validator = composeRules([rule]);
197
+ await validator({});
198
+
199
+ expect(() => heavy.length).toThrow();
200
+ });
201
+
202
+ it("should handle circular reference errors", async () => {
203
+ const obj: any = { self: null };
204
+ obj.self = obj;
205
+
206
+ const validator = composeRules([() => fail(obj)]);
207
+ const result = await validator({});
208
+ expect(result.status).toBe("failed");
209
+ expect((result as any).error.self).toBe((result as any).error);
210
+ });
211
+ });
@@ -0,0 +1,47 @@
1
+ import { pass } from "../helpers";
2
+ import { CompositionOptions, Rule } from "../types";
3
+
4
+ /**
5
+ * Composes multiple rules into a single rule that runs them in right-to-left order (fail-fast).
6
+ * Stops at the first failure and returns the error.
7
+ *
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 rules - Array of rules to compose
12
+ * @param options - Configuration options
13
+ * @param options.cloneContext - Whether to clone the context for each rule (default: false)
14
+ * @returns A new rule that composes all input rules
15
+ *
16
+ * @example
17
+ * const rule = composeRules([
18
+ * finalCheck,
19
+ * normalizeInput,
20
+ * validateBase
21
+ * ]);
22
+ *
23
+ * const result = await rule(input);
24
+ *
25
+ * @caveats
26
+ * - Rules are executed from **right to left**
27
+ * - Rules are executed sequentially (not in parallel)
28
+ * - Context clone uses structuredClone from Node.js
29
+ */
30
+ export const composeRules = <TInput, TError = string, TContext = unknown>(
31
+ rules: Rule<TInput, TError, TContext>[],
32
+ options: CompositionOptions = {},
33
+ ): Rule<TInput, TError, TContext> => {
34
+ return async (input: TInput, context?: TContext) => {
35
+ const currentContext = options?.cloneContext
36
+ ? structuredClone(context)
37
+ : context;
38
+
39
+ for (let i = rules.length - 1; i >= 0; i--) {
40
+ const result = await rules[i](input, currentContext);
41
+ if (result.status === "failed") {
42
+ return result;
43
+ }
44
+ }
45
+ return pass();
46
+ };
47
+ };
@@ -0,0 +1,3 @@
1
+ export * from "./compose-rules";
2
+ export * from "./pipe-rules";
3
+ export * from "./pipe";
@@ -0,0 +1,220 @@
1
+ import { pipeRules } from "./pipe-rules";
2
+ import { fail, pass } from "../helpers";
3
+ import { beforeEach, describe, expect, it, vi } from "vitest";
4
+ import { Rule } from "../types";
5
+
6
+ describe("pipeRules", () => {
7
+ // Mock rules
8
+ const alwaysPass = vi.fn(() => pass());
9
+ const failWithMsg = (msg: string) => vi.fn(() => fail(msg));
10
+
11
+ beforeEach(() => {
12
+ vi.clearAllMocks();
13
+ });
14
+
15
+ it("should return pass if no rules are provided", async () => {
16
+ const result = await pipeRules([])({});
17
+ expect(result).toEqual(pass());
18
+ });
19
+
20
+ it("should return pass if all rules pass", async () => {
21
+ const rule1 = alwaysPass;
22
+ const rule2 = alwaysPass;
23
+ const validator = pipeRules([rule1, rule2]);
24
+ const input = { foo: "bar" };
25
+
26
+ const result = await validator(input);
27
+
28
+ expect(result).toEqual(pass());
29
+ expect(rule1).toHaveBeenCalledWith(input, undefined);
30
+ expect(rule2).toHaveBeenCalledWith(input, undefined);
31
+ });
32
+
33
+ it("should fail fast on first failure", async () => {
34
+ const errorMsg = "First error";
35
+ const rule1 = failWithMsg(errorMsg);
36
+ const rule2 = alwaysPass; // Should never be called
37
+ const validator = pipeRules([rule1, rule2]);
38
+ const input = { foo: "bar" };
39
+
40
+ const result = await validator(input);
41
+
42
+ expect(result).toEqual(fail(errorMsg));
43
+ expect(rule1).toHaveBeenCalledWith(input, undefined);
44
+ expect(rule2).not.toHaveBeenCalled();
45
+ });
46
+
47
+ it("should pass context to all rules", async () => {
48
+ const rule1 = vi.fn(() => pass());
49
+ const rule2 = vi.fn(() => pass());
50
+ const validator = pipeRules([rule1, rule2]);
51
+ const input = { foo: "bar" };
52
+ const context = { userId: 123 };
53
+
54
+ await validator(input, context);
55
+
56
+ expect(rule1).toHaveBeenCalledWith(input, context);
57
+ expect(rule2).toHaveBeenCalledWith(input, context);
58
+ });
59
+ });
60
+
61
+ // Error type propagation
62
+ it("should preserve custom error types", async () => {
63
+ type CustomError = { code: number; message: string };
64
+ const rule: Rule<unknown, CustomError> = () =>
65
+ fail({ code: 400, message: "Bad" });
66
+
67
+ const validator = pipeRules([rule]);
68
+ const result = await validator({});
69
+
70
+ expect(result).toEqual(fail({ code: 400, message: "Bad" }));
71
+ });
72
+
73
+ it("should handle 1000+ rules without stack overflow", async () => {
74
+ const manyRules = Array(1000).fill(() => pass());
75
+ const validator = pipeRules(manyRules);
76
+ await expect(validator({})).resolves.toEqual(pass());
77
+ });
78
+
79
+ describe("Context behavior tests", () => {
80
+ const countingRule = vi.fn((_: unknown, ctx: any) => {
81
+ ctx.count = (ctx.count || 0) + 1;
82
+ return pass();
83
+ });
84
+
85
+ // Context checker rule
86
+ const expectCountRule = (expected: number) =>
87
+ vi.fn((_: unknown, ctx: any) =>
88
+ ctx.count === expected
89
+ ? pass()
90
+ : fail(`Expected count ${expected}, got ${ctx.count}`),
91
+ );
92
+
93
+ beforeEach(() => {
94
+ vi.clearAllMocks();
95
+ });
96
+
97
+ it("should allow context mutation by default (shared reference)", async () => {
98
+ const context = { count: 0 };
99
+ const validator = pipeRules(
100
+ [countingRule, countingRule, expectCountRule(2)], // Expect both mutations to apply
101
+ );
102
+
103
+ const result = await validator({}, context);
104
+
105
+ expect(result).toEqual(pass());
106
+ expect(context.count).toBe(2); // Original context modified
107
+ });
108
+
109
+ it("should prevent context mutations when cloneContext=true", async () => {
110
+ const context = { count: 0 };
111
+ const validator = pipeRules([countingRule, expectCountRule(1)], {
112
+ cloneContext: true,
113
+ });
114
+
115
+ const result = await validator({}, context);
116
+
117
+ expect(result).toEqual(pass());
118
+ expect(context.count).toBe(0); // Original context untouched
119
+ expect(countingRule.mock.calls[0][1].count).toBe(1); // First clone
120
+ });
121
+
122
+ it("should deep clone complex context objects", async () => {
123
+ const context = { nested: { value: 0 } };
124
+ const mutateNested = vi.fn((_, ctx) => {
125
+ ctx.nested.value++;
126
+ return pass();
127
+ });
128
+
129
+ const validator = pipeRules([mutateNested, mutateNested], {
130
+ cloneContext: true,
131
+ });
132
+
133
+ await validator({}, context);
134
+
135
+ expect(context.nested.value).toBe(0); // Original unchanged
136
+ expect(mutateNested.mock.calls[0][1].nested.value).toBe(2); // First clone
137
+ expect(mutateNested.mock.calls[1][1].nested.value).toBe(2); // Fresh clone
138
+ });
139
+
140
+ it("should handle null/undefined context", async () => {
141
+ const nullValidator = pipeRules([], { cloneContext: true });
142
+ await expect(nullValidator({}, null)).resolves.not.toThrow();
143
+ await expect(nullValidator({}, undefined)).resolves.not.toThrow();
144
+ });
145
+
146
+ it("should shallow clone when possible for performance", async () => {
147
+ const context = { simple: "value" };
148
+ const validator = pipeRules(
149
+ [
150
+ (_, ctx) => {
151
+ (ctx as any).simple = "changed";
152
+ return pass();
153
+ },
154
+ ],
155
+ { cloneContext: true },
156
+ );
157
+
158
+ await validator({}, context);
159
+ expect(context.simple).toBe("value"); // Original unchanged
160
+ });
161
+ });
162
+
163
+ it("should prevent accidental context mutation", async () => {
164
+ const context = { count: 0 };
165
+
166
+ const rule1 = (_: any, ctx: any) => {
167
+ (ctx as any).count++; // Bad practice but test should handle
168
+ return pass();
169
+ };
170
+
171
+ const rule2 = (_: any, ctx: any) => {
172
+ if ((ctx as any).count !== 0) {
173
+ return fail("Context mutated");
174
+ }
175
+ return pass();
176
+ };
177
+
178
+ const validator = pipeRules([rule1, rule2]);
179
+ await expect(validator({}, context)).resolves.toEqual(
180
+ fail("Context mutated"),
181
+ );
182
+ });
183
+
184
+ it("should preserve custom generic types through composition", async () => {
185
+ type CustomInput = { id: string };
186
+ type CustomError = { severity: number };
187
+
188
+ const rule: Rule<CustomInput, CustomError> = (input) =>
189
+ input.id ? pass() : fail({ severity: 5 });
190
+
191
+ const validator = pipeRules([rule]);
192
+ const result1 = await validator({ id: "test" });
193
+ const result2 = await validator({} as CustomInput);
194
+
195
+ expect(result1).toEqual(pass());
196
+ expect(result2).toEqual(fail({ severity: 5 }));
197
+ });
198
+
199
+ it("should not retain rule references after execution", async () => {
200
+ let heavyObject = new Array(1e6).fill(0); // 1MB object
201
+ const rule = () => {
202
+ heavyObject = null!; // Simulate cleanup
203
+ return pass();
204
+ };
205
+
206
+ const validator = pipeRules([rule]);
207
+ await validator({});
208
+
209
+ // This would fail if composition held references
210
+ expect(() => heavyObject.length).toThrow();
211
+ });
212
+
213
+ it("should handle circular reference errors", async () => {
214
+ const obj: any = { self: null };
215
+ obj.self = obj;
216
+ const validator = pipeRules([() => fail(obj)]);
217
+ const result = await validator({});
218
+ expect(result.status).toBe("failed");
219
+ expect((result as any).error.self).toBe((result as any).error);
220
+ });
@@ -0,0 +1,44 @@
1
+ import { pass } from "../helpers";
2
+ import { CompositionOptions, Rule } from "../types";
3
+
4
+ /**
5
+ * Pipes multiple rules into a single rule that runs them sequentially (fail-fast).
6
+ * Stops at the first failure and returns the error.
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
+ * @returns A new rule that pipes all input rules
14
+ * @example
15
+ * const rule = pipeRules([
16
+ * validateString,
17
+ * validateLength,
18
+ * validateFormat
19
+ * ]);
20
+ *
21
+ * const result = await rule("test@example.com");
22
+ * @caveats
23
+ * - Rules are execute from left to right
24
+ * - Rules are executed in sequence, not in parallel
25
+ * - Context clone uses structuredClone Nodejs implementation
26
+ */
27
+ export const pipeRules = <TInput, TError = string, TContext = unknown>(
28
+ rules: Rule<TInput, TError, TContext>[],
29
+ options: CompositionOptions = {},
30
+ ): Rule<TInput, TError, TContext> => {
31
+ return async (input: TInput, context?: TContext) => {
32
+ const currentContext = options?.cloneContext
33
+ ? structuredClone(context)
34
+ : context;
35
+
36
+ for (const rule of rules) {
37
+ const result = await rule(input, currentContext);
38
+ if (result.status === "failed") {
39
+ return result;
40
+ }
41
+ }
42
+ return pass();
43
+ };
44
+ };
@@ -0,0 +1,47 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { pipe } from "./pipe";
3
+
4
+ describe("pipe", () => {
5
+ it("should return input when no functions provided", () => {
6
+ expect(pipe(42)).toBe(42);
7
+ });
8
+
9
+ it("should apply single function", () => {
10
+ const result = pipe(2, (x) => x * 3);
11
+ expect(result).toBe(6);
12
+ });
13
+
14
+ it("should chain multiple functions", () => {
15
+ const result = pipe(
16
+ 5,
17
+ (x) => x + 1,
18
+ (x) => x * 2,
19
+ String,
20
+ );
21
+ expect(result).toBe("12");
22
+ });
23
+
24
+ it("should maintain type safety", () => {
25
+ const length = (s: string) => s.length;
26
+ const double = (n: number) => n * 2;
27
+
28
+ // Valid usage
29
+ const result = pipe("hello", length, double);
30
+ expect(result).toBe(10);
31
+
32
+ pipe(
33
+ // @ts-expect-error - Should fail if types don't line up
34
+ "hello",
35
+ double, // Can't apply number operation to string
36
+ );
37
+ });
38
+
39
+ it("should work with rule combinators", () => {
40
+ const add1 = (x: number) => x + 1;
41
+ const times2 = (x: number) => x * 2;
42
+ const toString = (x: number) => x.toString();
43
+
44
+ const result = pipe(3, add1, times2, toString);
45
+ expect(result).toBe("8");
46
+ });
47
+ });