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.
- package/package.json +7 -1
- package/.editorconfig +0 -15
- package/.github/CONTRIBUTING.md +0 -3
- package/.github/ISSUE_TEMPLATE.md +0 -9
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
- package/.github/workflows/docs.yml +0 -29
- package/.github/workflows/publish.yml +0 -25
- package/.github/workflows/test.yml +0 -37
- package/.prettierignore +0 -2
- package/.releaserc +0 -11
- package/eslint.config.mjs +0 -84
- package/examples/financial-transaction.example.ts +0 -188
- package/examples/model-deployment.example.ts +0 -136
- package/examples/user-registration.example.ts +0 -101
- package/src/lib/combinators/index.ts +0 -2
- package/src/lib/combinators/logic/every.spec.ts +0 -264
- package/src/lib/combinators/logic/every.ts +0 -57
- package/src/lib/combinators/logic/if-else.spec.ts +0 -82
- package/src/lib/combinators/logic/if-else.ts +0 -64
- package/src/lib/combinators/logic/index.ts +0 -8
- package/src/lib/combinators/logic/match.spec.ts +0 -186
- package/src/lib/combinators/logic/match.ts +0 -106
- package/src/lib/combinators/logic/not.spec.ts +0 -64
- package/src/lib/combinators/logic/not.ts +0 -34
- package/src/lib/combinators/logic/one-of.spec.ts +0 -68
- package/src/lib/combinators/logic/one-of.ts +0 -48
- package/src/lib/combinators/logic/unless.spec.ts +0 -61
- package/src/lib/combinators/logic/unless.ts +0 -50
- package/src/lib/combinators/logic/when.spec.ts +0 -119
- package/src/lib/combinators/logic/when.ts +0 -50
- package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
- package/src/lib/combinators/logic/with-fallback.ts +0 -46
- package/src/lib/combinators/utility/index.ts +0 -11
- package/src/lib/combinators/utility/inject.spec.ts +0 -55
- package/src/lib/combinators/utility/inject.ts +0 -25
- package/src/lib/combinators/utility/map-error.spec.ts +0 -63
- package/src/lib/combinators/utility/map-error.ts +0 -35
- package/src/lib/combinators/utility/tap.spec.ts +0 -102
- package/src/lib/combinators/utility/tap.ts +0 -28
- package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
- package/src/lib/combinators/utility/validate-field.ts +0 -66
- package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
- package/src/lib/combinators/utility/with-debug.ts +0 -55
- package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
- package/src/lib/combinators/utility/with-memoize.ts +0 -89
- package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
- package/src/lib/combinators/utility/with-retry.ts +0 -70
- package/src/lib/combinators/utility/with-safe-error.spec.ts +0 -137
- package/src/lib/combinators/utility/with-safe-error.ts +0 -56
- package/src/lib/combinators/utility/with-safe-predicate.spec.ts +0 -176
- package/src/lib/combinators/utility/with-safe-predicate.ts +0 -64
- package/src/lib/combinators/utility/with-tap.spec.ts +0 -104
- package/src/lib/combinators/utility/with-tap.ts +0 -46
- package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
- package/src/lib/combinators/utility/with-timeout.ts +0 -41
- package/src/lib/composition/compose-rules.spec.ts +0 -211
- package/src/lib/composition/compose-rules.ts +0 -55
- package/src/lib/composition/index.ts +0 -3
- package/src/lib/composition/pipe-rules.spec.ts +0 -220
- package/src/lib/composition/pipe-rules.ts +0 -52
- package/src/lib/composition/pipe.spec.ts +0 -47
- package/src/lib/composition/pipe.ts +0 -107
- package/src/lib/helpers/clone/clone.ts +0 -12
- package/src/lib/helpers/clone/getCloneFn.ts +0 -17
- package/src/lib/helpers/clone/shallowClone.ts +0 -12
- package/src/lib/helpers/context/has-context.ts +0 -13
- package/src/lib/helpers/context/index.ts +0 -3
- package/src/lib/helpers/context/require-context.spec.ts +0 -55
- package/src/lib/helpers/context/require-context.ts +0 -61
- package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
- package/src/lib/helpers/context/with-lazy-context.ts +0 -35
- package/src/lib/helpers/index.ts +0 -8
- package/src/lib/helpers/result/fail.ts +0 -15
- package/src/lib/helpers/result/index.ts +0 -2
- package/src/lib/helpers/result/pass.ts +0 -14
- package/src/lib/helpers/retry/calculate-delay.ts +0 -31
- package/src/lib/helpers/safety/get-normalized-rule.spec.ts +0 -209
- package/src/lib/helpers/safety/get-normalized-rule.ts +0 -14
- package/src/lib/helpers/safety/get-normalized-rules.spec.ts +0 -138
- package/src/lib/helpers/safety/get-normalized-rules.ts +0 -14
- package/src/lib/index.ts +0 -4
- package/src/lib/types/composition-options.ts +0 -32
- package/src/lib/types/debug-options.ts +0 -36
- package/src/lib/types/index.ts +0 -8
- package/src/lib/types/predicate-result.ts +0 -20
- package/src/lib/types/predicate-safe.ts +0 -10
- package/src/lib/types/predicate-safety-options.ts +0 -27
- package/src/lib/types/predicate.ts +0 -8
- package/src/lib/types/prettify.ts +0 -3
- package/src/lib/types/rule-result.ts +0 -16
- package/src/lib/types/rule-safety-options.ts +0 -34
- package/src/lib/types/rule.ts +0 -21
- package/src/lib/types/safety-options.ts +0 -7
- package/src/test/financial-transaction.spec.ts +0 -251
- package/src/test/helpers/get-rule-error.ts +0 -23
- package/src/test/integration.spec.ts +0 -285
- package/src/test/model-deployment.spec.ts +0 -209
- package/src/test/user-registration.spec.ts +0 -164
- package/tsconfig.json +0 -56
- package/tsup.config.ts +0 -36
- package/typedoc/tsconfig.typedoc.json +0 -15
- package/typedoc/typedoc.json +0 -14
- package/vitest.config.ts +0 -16
|
@@ -1,211 +0,0 @@
|
|
|
1
|
-
import { composeRules } from "./compose-rules";
|
|
2
|
-
import { fail, pass } from "../helpers";
|
|
3
|
-
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
4
|
-
import type { 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
|
-
});
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { 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 in right-to-left order (fail-fast).
|
|
7
|
-
* Stops at the first failure and returns the error.
|
|
8
|
-
*
|
|
9
|
-
* @template TInput - The type of the input to validate
|
|
10
|
-
* @template TError - The type of the error (defaults to string)
|
|
11
|
-
* @template TContext - The type of the context object (optional)
|
|
12
|
-
* @param rules - Array of rules to compose
|
|
13
|
-
* @param options - Configuration options
|
|
14
|
-
* @param options.cloneContext - Whether to clone the context for each rule (default: false)
|
|
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
|
-
* @returns A new rule that composes all input rules
|
|
20
|
-
*
|
|
21
|
-
* @example
|
|
22
|
-
* const rule = composeRules([
|
|
23
|
-
* finalCheck,
|
|
24
|
-
* normalizeInput,
|
|
25
|
-
* validateBase
|
|
26
|
-
* ]);
|
|
27
|
-
*
|
|
28
|
-
* const result = await rule(input);
|
|
29
|
-
*
|
|
30
|
-
* @caveats
|
|
31
|
-
* - Rules are executed from **right to left**
|
|
32
|
-
* - Rules are executed sequentially (not in parallel)
|
|
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 composeRules = <TInput, TError = string, TContext = unknown>(
|
|
39
|
-
rules: Rule<TInput, TError, TContext>[],
|
|
40
|
-
options: CompositionOptions = {},
|
|
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);
|
|
46
|
-
|
|
47
|
-
for (let i = normalizedRules.length - 1; i >= 0; i--) {
|
|
48
|
-
const result = await normalizedRules[i](input, currentContext);
|
|
49
|
-
if (result.status === "failed") {
|
|
50
|
-
return result;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return pass();
|
|
54
|
-
};
|
|
55
|
-
};
|
|
@@ -1,220 +0,0 @@
|
|
|
1
|
-
import { pipeRules } from "./pipe-rules";
|
|
2
|
-
import { fail, pass } from "../helpers";
|
|
3
|
-
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
4
|
-
import type { 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
|
-
});
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { getNormalizedRules, pass } from "../helpers";
|
|
2
|
-
import { getCloneFn } from "../helpers/clone/getCloneFn";
|
|
3
|
-
import type { CompositionOptions, Rule } from "../types";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Pipes multiple rules into a single rule that runs them sequentially (fail-fast).
|
|
7
|
-
* Stops at the first failure and returns the error.
|
|
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
|
-
* @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 pipes all input rules
|
|
19
|
-
* @example
|
|
20
|
-
* const rule = pipeRules([
|
|
21
|
-
* validateString,
|
|
22
|
-
* validateLength,
|
|
23
|
-
* validateFormat
|
|
24
|
-
* ]);
|
|
25
|
-
*
|
|
26
|
-
* const result = await rule("test@example.com");
|
|
27
|
-
* @caveats
|
|
28
|
-
* - Rules are execute from left to right
|
|
29
|
-
* - Rules are executed in sequence, not in parallel
|
|
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
|
|
34
|
-
*/
|
|
35
|
-
export const pipeRules = <TInput, TError = string, TContext = unknown>(
|
|
36
|
-
rules: Rule<TInput, TError, TContext>[],
|
|
37
|
-
options: CompositionOptions = {},
|
|
38
|
-
): Rule<TInput, TError, TContext> => {
|
|
39
|
-
return async (input: TInput, context?: TContext) => {
|
|
40
|
-
const cloneFn = getCloneFn(options);
|
|
41
|
-
const currentContext = options?.cloneContext ? cloneFn(context) : context;
|
|
42
|
-
const normalizedRules = getNormalizedRules(rules);
|
|
43
|
-
|
|
44
|
-
for (const rule of normalizedRules) {
|
|
45
|
-
const result = await rule(input, currentContext);
|
|
46
|
-
if (result.status === "failed") {
|
|
47
|
-
return result;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
return pass();
|
|
51
|
-
};
|
|
52
|
-
};
|
|
@@ -1,47 +0,0 @@
|
|
|
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
|
-
});
|
|
@@ -1,107 +0,0 @@
|
|
|
1
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2
|
-
type AnyFunction = (...args: any[]) => any;
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Pipes a value through a series of functions (left-to-right composition).
|
|
6
|
-
* @template A - The input type
|
|
7
|
-
* @template B - The output type after first function
|
|
8
|
-
* @param value - The initial value
|
|
9
|
-
* @param fns - Functions to apply sequentially
|
|
10
|
-
* @returns The result of applying all functions to the initial value
|
|
11
|
-
* @example
|
|
12
|
-
* const result = pipe(
|
|
13
|
-
* 5,
|
|
14
|
-
* (x) => x * 2,
|
|
15
|
-
* (x) => x + 3,
|
|
16
|
-
* (x) => `Result: ${x}`
|
|
17
|
-
* ); // "Result: 13"
|
|
18
|
-
* @caveats
|
|
19
|
-
* - Currently supports up to 10 functions with proper type inference
|
|
20
|
-
* - For more functions, type information will be lost
|
|
21
|
-
*/
|
|
22
|
-
export function pipe<A>(value: A): A;
|
|
23
|
-
export function pipe<A, B>(value: A, fn1: (arg: A) => B): B;
|
|
24
|
-
export function pipe<A, B, C>(
|
|
25
|
-
value: A,
|
|
26
|
-
fn1: (arg: A) => B,
|
|
27
|
-
fn2: (arg: B) => C,
|
|
28
|
-
): C;
|
|
29
|
-
export function pipe<A, B, C, D>(
|
|
30
|
-
value: A,
|
|
31
|
-
fn1: (arg: A) => B,
|
|
32
|
-
fn2: (arg: B) => C,
|
|
33
|
-
fn3: (arg: C) => D,
|
|
34
|
-
): D;
|
|
35
|
-
export function pipe<A, B, C, D, E>(
|
|
36
|
-
value: A,
|
|
37
|
-
fn1: (arg: A) => B,
|
|
38
|
-
fn2: (arg: B) => C,
|
|
39
|
-
fn3: (arg: C) => D,
|
|
40
|
-
fn4: (arg: D) => E,
|
|
41
|
-
): E;
|
|
42
|
-
export function pipe<A, B, C, D, E, F>(
|
|
43
|
-
value: A,
|
|
44
|
-
fn1: (arg: A) => B,
|
|
45
|
-
fn2: (arg: B) => C,
|
|
46
|
-
fn3: (arg: C) => D,
|
|
47
|
-
fn4: (arg: D) => E,
|
|
48
|
-
fn5: (arg: E) => F,
|
|
49
|
-
): F;
|
|
50
|
-
export function pipe<A, B, C, D, E, F, G>(
|
|
51
|
-
value: A,
|
|
52
|
-
fn1: (arg: A) => B,
|
|
53
|
-
fn2: (arg: B) => C,
|
|
54
|
-
fn3: (arg: C) => D,
|
|
55
|
-
fn4: (arg: D) => E,
|
|
56
|
-
fn5: (arg: E) => F,
|
|
57
|
-
fn6: (arg: F) => G,
|
|
58
|
-
): G;
|
|
59
|
-
export function pipe<A, B, C, D, E, F, G, H>(
|
|
60
|
-
value: A,
|
|
61
|
-
fn1: (arg: A) => B,
|
|
62
|
-
fn2: (arg: B) => C,
|
|
63
|
-
fn3: (arg: C) => D,
|
|
64
|
-
fn4: (arg: D) => E,
|
|
65
|
-
fn5: (arg: E) => F,
|
|
66
|
-
fn6: (arg: F) => G,
|
|
67
|
-
fn7: (arg: G) => H,
|
|
68
|
-
): H;
|
|
69
|
-
export function pipe<A, B, C, D, E, F, G, H, I>(
|
|
70
|
-
value: A,
|
|
71
|
-
fn1: (arg: A) => B,
|
|
72
|
-
fn2: (arg: B) => C,
|
|
73
|
-
fn3: (arg: C) => D,
|
|
74
|
-
fn4: (arg: D) => E,
|
|
75
|
-
fn5: (arg: E) => F,
|
|
76
|
-
fn6: (arg: F) => G,
|
|
77
|
-
fn7: (arg: G) => H,
|
|
78
|
-
fn8: (arg: H) => I,
|
|
79
|
-
): I;
|
|
80
|
-
export function pipe<A, B, C, D, E, F, G, H, I, J>(
|
|
81
|
-
value: A,
|
|
82
|
-
fn1: (arg: A) => B,
|
|
83
|
-
fn2: (arg: B) => C,
|
|
84
|
-
fn3: (arg: C) => D,
|
|
85
|
-
fn4: (arg: D) => E,
|
|
86
|
-
fn5: (arg: E) => F,
|
|
87
|
-
fn6: (arg: F) => G,
|
|
88
|
-
fn7: (arg: G) => H,
|
|
89
|
-
fn8: (arg: H) => I,
|
|
90
|
-
fn9: (arg: I) => J,
|
|
91
|
-
): J;
|
|
92
|
-
export function pipe<A, B, C, D, E, F, G, H, I, J, K>(
|
|
93
|
-
value: A,
|
|
94
|
-
fn1: (arg: A) => B,
|
|
95
|
-
fn2: (arg: B) => C,
|
|
96
|
-
fn3: (arg: C) => D,
|
|
97
|
-
fn4: (arg: D) => E,
|
|
98
|
-
fn5: (arg: E) => F,
|
|
99
|
-
fn6: (arg: F) => G,
|
|
100
|
-
fn7: (arg: G) => H,
|
|
101
|
-
fn8: (arg: H) => I,
|
|
102
|
-
fn9: (arg: I) => J,
|
|
103
|
-
fn10: (arg: J) => K,
|
|
104
|
-
): K;
|
|
105
|
-
export function pipe(value: unknown, ...fns: AnyFunction[]): unknown {
|
|
106
|
-
return fns.reduce((acc, fn) => fn(acc), value);
|
|
107
|
-
}
|