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.
- package/.editorconfig +15 -0
- package/.eslintrc.json +66 -0
- package/.github/CONTRIBUTING.md +3 -0
- package/.github/ISSUE_TEMPLATE.md +9 -0
- package/.github/PULL_REQUEST_TEMPLATE.md +7 -0
- package/.github/workflows/docs.yml +29 -0
- package/.github/workflows/publish.yml +25 -0
- package/.github/workflows/test.yml +37 -0
- package/.prettierignore +2 -0
- package/.releaserc +11 -0
- package/LICENSE +21 -0
- package/README.md +625 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +634 -0
- package/dist/index.d.ts +634 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -0
- package/src/lib/combinators/index.ts +2 -0
- package/src/lib/combinators/logic/every.spec.ts +264 -0
- package/src/lib/combinators/logic/every.ts +47 -0
- package/src/lib/combinators/logic/if-else.spec.ts +72 -0
- package/src/lib/combinators/logic/if-else.ts +39 -0
- package/src/lib/combinators/logic/index.ts +8 -0
- package/src/lib/combinators/logic/match.spec.ts +186 -0
- package/src/lib/combinators/logic/match.ts +92 -0
- package/src/lib/combinators/logic/not.spec.ts +62 -0
- package/src/lib/combinators/logic/not.ts +25 -0
- package/src/lib/combinators/logic/one-of.spec.ts +68 -0
- package/src/lib/combinators/logic/one-of.ts +41 -0
- package/src/lib/combinators/logic/unless.spec.ts +61 -0
- package/src/lib/combinators/logic/unless.ts +27 -0
- package/src/lib/combinators/logic/when.spec.ts +123 -0
- package/src/lib/combinators/logic/when.ts +29 -0
- package/src/lib/combinators/logic/with-fallback.spec.ts +72 -0
- package/src/lib/combinators/logic/with-fallback.ts +37 -0
- package/src/lib/combinators/utility/index.ts +8 -0
- package/src/lib/combinators/utility/inject.spec.ts +55 -0
- package/src/lib/combinators/utility/inject.ts +25 -0
- package/src/lib/combinators/utility/map-error.spec.ts +63 -0
- package/src/lib/combinators/utility/map-error.ts +35 -0
- package/src/lib/combinators/utility/tap.spec.ts +102 -0
- package/src/lib/combinators/utility/tap.ts +38 -0
- package/src/lib/combinators/utility/validate-field.spec.ts +150 -0
- package/src/lib/combinators/utility/validate-field.ts +59 -0
- package/src/lib/combinators/utility/with-debug.spec.ts +71 -0
- package/src/lib/combinators/utility/with-debug.ts +55 -0
- package/src/lib/combinators/utility/with-memoize.spec.ts +82 -0
- package/src/lib/combinators/utility/with-memoize.ts +81 -0
- package/src/lib/combinators/utility/with-retry.spec.ts +220 -0
- package/src/lib/combinators/utility/with-retry.ts +68 -0
- package/src/lib/combinators/utility/with-timeout.spec.ts +115 -0
- package/src/lib/combinators/utility/with-timeout.ts +34 -0
- package/src/lib/composition/compose-rules.spec.ts +211 -0
- package/src/lib/composition/compose-rules.ts +47 -0
- package/src/lib/composition/index.ts +3 -0
- package/src/lib/composition/pipe-rules.spec.ts +220 -0
- package/src/lib/composition/pipe-rules.ts +44 -0
- package/src/lib/composition/pipe.spec.ts +47 -0
- package/src/lib/composition/pipe.ts +106 -0
- package/src/lib/helpers/context/has-context.ts +13 -0
- package/src/lib/helpers/context/index.ts +3 -0
- package/src/lib/helpers/context/require-context.spec.ts +55 -0
- package/src/lib/helpers/context/require-context.ts +61 -0
- package/src/lib/helpers/context/with-lazy-context.spec.ts +74 -0
- package/src/lib/helpers/context/with-lazy-context.ts +35 -0
- package/src/lib/helpers/index.ts +6 -0
- package/src/lib/helpers/result/fail.ts +15 -0
- package/src/lib/helpers/result/index.ts +2 -0
- package/src/lib/helpers/result/pass.ts +14 -0
- package/src/lib/helpers/retry/calculate-delay.ts +31 -0
- package/src/lib/index.ts +4 -0
- package/src/lib/types/composition-options.ts +7 -0
- package/src/lib/types/debug-options.ts +36 -0
- package/src/lib/types/index.ts +4 -0
- package/src/lib/types/rule-result.ts +16 -0
- package/src/lib/types/rule.ts +21 -0
- package/src/test/helpers/get-rule-error.ts +23 -0
- package/src/test/integration.spec.ts +285 -0
- package/tsconfig.json +55 -0
- package/tsup.config.ts +36 -0
- package/vitest.config.ts +16 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { pass } from "../../helpers/result/pass";
|
|
2
|
+
import { Rule } from "../../types/rule";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Conditionally executes a rule based on a predicate.
|
|
6
|
+
* Similar to branch but without an else case.
|
|
7
|
+
* @template TInput - The type of the input to validate
|
|
8
|
+
* @template TError - The type of the error (defaults to string)
|
|
9
|
+
* @param predicate - Function that determines whether to execute the rule
|
|
10
|
+
* @param rule - Rule to execute when predicate returns true
|
|
11
|
+
* @returns A new rule that conditionally executes the input rule
|
|
12
|
+
* @example
|
|
13
|
+
* const rule = when(
|
|
14
|
+
* (user) => user.role === "admin",
|
|
15
|
+
* validateAdminPrivileges
|
|
16
|
+
* );
|
|
17
|
+
* @caveats
|
|
18
|
+
* - The predicate can be async
|
|
19
|
+
* - If predicate returns false, the rule automatically passes
|
|
20
|
+
*/
|
|
21
|
+
export const when = <TInput, TError = string>(
|
|
22
|
+
predicate: (input: TInput) => boolean | Promise<boolean>,
|
|
23
|
+
rule: Rule<TInput, TError>,
|
|
24
|
+
): Rule<TInput, TError> => {
|
|
25
|
+
return async (input: TInput, context?: unknown) => {
|
|
26
|
+
const shouldRun = await predicate(input);
|
|
27
|
+
return shouldRun ? rule(input, context) : pass();
|
|
28
|
+
};
|
|
29
|
+
};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
+
import { fail, pass } from "../../helpers";
|
|
3
|
+
import { withFallback } from "./with-fallback";
|
|
4
|
+
|
|
5
|
+
describe("withFallback", () => {
|
|
6
|
+
const mockMainRule = vi.fn();
|
|
7
|
+
const mockFallback = vi.fn();
|
|
8
|
+
|
|
9
|
+
beforeEach(() => {
|
|
10
|
+
mockMainRule.mockReset();
|
|
11
|
+
mockFallback.mockReset();
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it("should execute fallback when main rule fails", async () => {
|
|
15
|
+
mockMainRule.mockResolvedValue(fail("Main failed"));
|
|
16
|
+
mockFallback.mockResolvedValue(pass());
|
|
17
|
+
|
|
18
|
+
const rule = withFallback(mockMainRule, mockFallback);
|
|
19
|
+
const result = await rule("test");
|
|
20
|
+
|
|
21
|
+
expect(mockMainRule).toHaveBeenCalledWith("test", undefined);
|
|
22
|
+
expect(mockFallback).toHaveBeenCalledWith("test", undefined);
|
|
23
|
+
expect(result).toEqual(pass());
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("should not execute fallback when main rule passes", async () => {
|
|
27
|
+
mockMainRule.mockResolvedValue(pass());
|
|
28
|
+
|
|
29
|
+
const rule = withFallback(mockMainRule, mockFallback);
|
|
30
|
+
const result = await rule("test");
|
|
31
|
+
|
|
32
|
+
expect(mockFallback).not.toHaveBeenCalled();
|
|
33
|
+
expect(result).toEqual(pass());
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it("should respect conditional fallback predicate", async () => {
|
|
37
|
+
mockMainRule.mockResolvedValue(fail({ code: "RETRYABLE" }));
|
|
38
|
+
mockFallback.mockResolvedValue(pass());
|
|
39
|
+
|
|
40
|
+
const rule = withFallback(mockMainRule, mockFallback, {
|
|
41
|
+
onlyFallbackOn: (err) => (err as any).code === "RETRYABLE",
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
await rule("test");
|
|
45
|
+
expect(mockFallback).toHaveBeenCalled();
|
|
46
|
+
|
|
47
|
+
mockMainRule.mockResolvedValue(fail({ code: "FATAL" }));
|
|
48
|
+
await rule("test");
|
|
49
|
+
expect(mockFallback).toHaveBeenCalledTimes(1); // Not called for FATAL
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("should preserve context", async () => {
|
|
53
|
+
const context = { auth: true };
|
|
54
|
+
mockMainRule.mockResolvedValue(fail("Failed"));
|
|
55
|
+
mockFallback.mockResolvedValue(pass());
|
|
56
|
+
|
|
57
|
+
const rule = withFallback(mockMainRule, mockFallback);
|
|
58
|
+
await rule("test", context);
|
|
59
|
+
|
|
60
|
+
expect(mockMainRule).toHaveBeenCalledWith("test", context);
|
|
61
|
+
expect(mockFallback).toHaveBeenCalledWith("test", context);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("should maintain type safety", async () => {
|
|
65
|
+
// Type test - no runtime assertion needed
|
|
66
|
+
const stringRule = (_: string) => pass();
|
|
67
|
+
const numberRule = (_: number) => pass();
|
|
68
|
+
|
|
69
|
+
// @ts-expect-error - Should fail type check
|
|
70
|
+
withFallback(stringRule, numberRule);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Rule } from "../../types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Creates a rule that falls back to an alternative rule if the main rule fails.
|
|
5
|
+
* @template TInput - Input type
|
|
6
|
+
* @template TError - Error type
|
|
7
|
+
* @template TContext - Context type
|
|
8
|
+
* @param mainRule - Primary rule to execute first
|
|
9
|
+
* @param fallbackRule - Rule to execute if main rule fails
|
|
10
|
+
* @param options - Configuration options
|
|
11
|
+
* @param options.onlyFallbackOn - Predicate to conditionally enable fallback
|
|
12
|
+
* @returns A new composite rule
|
|
13
|
+
* @example
|
|
14
|
+
* const rule = withFallback(
|
|
15
|
+
* premiumValidation,
|
|
16
|
+
* basicValidation,
|
|
17
|
+
* { onlyFallbackOn: err => err.code !== 'FATAL' }
|
|
18
|
+
* );
|
|
19
|
+
*/
|
|
20
|
+
export const withFallback = <TInput, TError, TContext>(
|
|
21
|
+
mainRule: Rule<TInput, TError, TContext>,
|
|
22
|
+
fallbackRule: Rule<TInput, TError, TContext>,
|
|
23
|
+
options: {
|
|
24
|
+
onlyFallbackOn?: (error: TError) => boolean;
|
|
25
|
+
} = {},
|
|
26
|
+
): Rule<TInput, TError, TContext> => {
|
|
27
|
+
return async (input: TInput, context?: TContext) => {
|
|
28
|
+
const result = await mainRule(input, context);
|
|
29
|
+
if (
|
|
30
|
+
result.status === "failed" &&
|
|
31
|
+
(!options.onlyFallbackOn || options.onlyFallbackOn(result.error))
|
|
32
|
+
) {
|
|
33
|
+
return fallbackRule(input, context);
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { describe, vi, beforeEach, it, expect } from "vitest";
|
|
2
|
+
import { pass, fail } from "../../helpers";
|
|
3
|
+
import { inject } from "./inject";
|
|
4
|
+
|
|
5
|
+
describe("inject (basic)", () => {
|
|
6
|
+
const mockRule = vi.fn((input: string) =>
|
|
7
|
+
input === "valid" ? pass() : fail("Invalid input"),
|
|
8
|
+
);
|
|
9
|
+
|
|
10
|
+
const mockFactory = (dep: { prefix: string }) => {
|
|
11
|
+
return (input: string) =>
|
|
12
|
+
input.startsWith(dep.prefix) ? pass() : fail("Missing prefix");
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
vi.clearAllMocks();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("injects dependencies into rule factory", async () => {
|
|
20
|
+
const rule = inject({ prefix: "test_" }, mockFactory);
|
|
21
|
+
const result = await rule("test_valid");
|
|
22
|
+
expect(result.status).toBe("passed");
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("passes through failures", async () => {
|
|
26
|
+
const rule = inject({ prefix: "test_" }, mockFactory);
|
|
27
|
+
const result = await rule("invalid");
|
|
28
|
+
expect(result.status).toBe("failed");
|
|
29
|
+
expect(result).toEqual(fail("Missing prefix"));
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("preserves original rule behavior", async () => {
|
|
33
|
+
const rule = inject({}, () => mockRule);
|
|
34
|
+
const validResult = await rule("valid");
|
|
35
|
+
const invalidResult = await rule("invalid");
|
|
36
|
+
|
|
37
|
+
expect(validResult.status).toBe("passed");
|
|
38
|
+
expect(invalidResult).toEqual(fail("Invalid input"));
|
|
39
|
+
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("works with async dependencies", async () => {
|
|
43
|
+
const asyncFactory = (dep: Promise<{ timeout: number }>) => {
|
|
44
|
+
return async (_: string) => {
|
|
45
|
+
const config = await dep;
|
|
46
|
+
await new Promise((resolve) => setTimeout(resolve, config.timeout));
|
|
47
|
+
return pass();
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const rule = inject(Promise.resolve({ timeout: 10 }), asyncFactory);
|
|
52
|
+
const result = await rule("any");
|
|
53
|
+
expect(result.status).toBe("passed");
|
|
54
|
+
});
|
|
55
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Rule } from "../../types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Injects a dependency into a rule creation function, returning a configured rule.
|
|
5
|
+
* @template TInput - The type of the input to validate
|
|
6
|
+
* @template TError - The type of the error
|
|
7
|
+
* @template TDep - The type of the dependency to inject
|
|
8
|
+
* @param dependency - The dependency to inject
|
|
9
|
+
* @param rule - A function that creates a rule when given the dependency
|
|
10
|
+
* @returns A configured rule that uses the injected dependency
|
|
11
|
+
* @example
|
|
12
|
+
* const createDbRule = (db: Database) => (input: string) =>
|
|
13
|
+
* db.exists(input) ? pass() : fail("Not found");
|
|
14
|
+
*
|
|
15
|
+
* const dbRule = inject(database, createDbRule);
|
|
16
|
+
* @caveats
|
|
17
|
+
* - The dependency is injected at rule creation time, not execution time
|
|
18
|
+
*/
|
|
19
|
+
export const inject = <TInput, TError, TDep>(
|
|
20
|
+
dependency: TDep,
|
|
21
|
+
rule: (dep: TDep) => Rule<TInput, TError>,
|
|
22
|
+
): Rule<TInput, TError> => {
|
|
23
|
+
const configuredRule = rule(dependency);
|
|
24
|
+
return (input) => configuredRule(input);
|
|
25
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { describe, beforeEach, it, expect, vi } from "vitest";
|
|
2
|
+
import { fail, pass } from "../../helpers";
|
|
3
|
+
import { mapError } from "./map-error";
|
|
4
|
+
|
|
5
|
+
describe("mapError combinator", () => {
|
|
6
|
+
const mockTransform = vi.fn((err: string) => `Mapped: ${err}`);
|
|
7
|
+
|
|
8
|
+
beforeEach(() => {
|
|
9
|
+
vi.clearAllMocks();
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it("should pass through successful results", async () => {
|
|
13
|
+
const passingRule = () => pass();
|
|
14
|
+
const mappedRule = mapError(passingRule, mockTransform);
|
|
15
|
+
const result = await mappedRule({});
|
|
16
|
+
|
|
17
|
+
expect(result).toEqual(pass());
|
|
18
|
+
expect(mockTransform).not.toHaveBeenCalled();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it("should transform failed results", async () => {
|
|
22
|
+
const failingRule = () => fail("Original error");
|
|
23
|
+
const mappedRule = mapError(failingRule, mockTransform);
|
|
24
|
+
const result = await mappedRule({});
|
|
25
|
+
|
|
26
|
+
expect(result).toEqual(fail("Mapped: Original error"));
|
|
27
|
+
expect(mockTransform).toHaveBeenCalledWith("Original error");
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it("should preserve context", async () => {
|
|
31
|
+
const context = { userId: 123 };
|
|
32
|
+
const contextAwareRule = vi.fn((_, ctx) =>
|
|
33
|
+
ctx?.userId === 123 ? fail("Original") : pass(),
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
const mappedRule = mapError(contextAwareRule, mockTransform);
|
|
37
|
+
await mappedRule({}, context);
|
|
38
|
+
|
|
39
|
+
expect(contextAwareRule).toHaveBeenCalledWith({}, context);
|
|
40
|
+
expect(mockTransform).toHaveBeenCalledWith("Original");
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("should handle async rules", async () => {
|
|
44
|
+
const asyncRule = async () => {
|
|
45
|
+
await Promise.resolve();
|
|
46
|
+
return fail("Async error");
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const mappedRule = mapError(asyncRule, mockTransform);
|
|
50
|
+
const result = await mappedRule({});
|
|
51
|
+
|
|
52
|
+
expect(result).toEqual(fail("Mapped: Async error"));
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("should propagate rule errors (uncaught exceptions)", async () => {
|
|
56
|
+
const errorRule = () => {
|
|
57
|
+
throw new Error("Boom!");
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const mappedRule = mapError(errorRule, mockTransform);
|
|
61
|
+
await expect(mappedRule({})).rejects.toThrow("Boom!");
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { fail, pass } from "../../helpers";
|
|
2
|
+
import { Rule } from "../../types";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Transforms the error of a rule using a mapping function.
|
|
6
|
+
* @template TInput - The type of the input to validate
|
|
7
|
+
* @template TError - The original error type
|
|
8
|
+
* @template TNewError - The new error type
|
|
9
|
+
* @param rule - The rule whose errors should be transformed
|
|
10
|
+
* @param transform - Function to transform the error
|
|
11
|
+
* @returns A new rule that produces transformed errors
|
|
12
|
+
* @example
|
|
13
|
+
* const rule = mapError(
|
|
14
|
+
* validateEmail,
|
|
15
|
+
* (error) => `Validation failed: ${error}`
|
|
16
|
+
* );
|
|
17
|
+
*
|
|
18
|
+
* // Can also change error types:
|
|
19
|
+
* const numericErrorRule = mapError(
|
|
20
|
+
* stringErrorRule,
|
|
21
|
+
* (error) => error.length // Convert string error to number
|
|
22
|
+
* );
|
|
23
|
+
* @caveats
|
|
24
|
+
* - Only transforms failed results, passes successful results through unchanged
|
|
25
|
+
* - The transform function is not called for successful results
|
|
26
|
+
*/
|
|
27
|
+
export const mapError = <TInput, TError, TNewError>(
|
|
28
|
+
rule: Rule<TInput, TError>,
|
|
29
|
+
transform: (error: TError) => TNewError,
|
|
30
|
+
): Rule<TInput, TNewError> => {
|
|
31
|
+
return async (input: TInput, context?: unknown) => {
|
|
32
|
+
const result = await rule(input, context);
|
|
33
|
+
return result.status === "failed" ? fail(transform(result.error)) : pass();
|
|
34
|
+
};
|
|
35
|
+
};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { describe, vi, beforeEach, it, expect } from "vitest";
|
|
2
|
+
import { pipeRules } from "../../composition/pipe-rules";
|
|
3
|
+
import { fail, pass } from "../../helpers";
|
|
4
|
+
import { Rule } from "../../types";
|
|
5
|
+
import { tap } from "./tap";
|
|
6
|
+
|
|
7
|
+
describe("tap (standalone)", () => {
|
|
8
|
+
const mockEffect = vi.fn();
|
|
9
|
+
const mockRule = vi.fn(() => pass());
|
|
10
|
+
const mockContext = { logger: console };
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
vi.clearAllMocks();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
// Basic functionality
|
|
17
|
+
it("should call effect without modifying rule result", async () => {
|
|
18
|
+
const tappedRule = tap(mockEffect)(mockRule);
|
|
19
|
+
const input = { test: "value" };
|
|
20
|
+
const result = await tappedRule(input);
|
|
21
|
+
|
|
22
|
+
expect(result).toEqual(pass());
|
|
23
|
+
expect(mockEffect).toHaveBeenCalledWith(input, pass(), undefined);
|
|
24
|
+
expect(mockRule).toHaveBeenCalledWith(input, undefined);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// Error handling
|
|
28
|
+
it("should not propagate effect errors", async () => {
|
|
29
|
+
const errorEffect = vi.fn(() => {
|
|
30
|
+
throw new Error("Effect failed");
|
|
31
|
+
});
|
|
32
|
+
const tappedRule = tap(errorEffect)(mockRule);
|
|
33
|
+
|
|
34
|
+
await expect(tappedRule({})).resolves.toEqual(pass());
|
|
35
|
+
expect(errorEffect).toHaveBeenCalled();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// Context handling
|
|
39
|
+
it("should pass context to both rule and effect", async () => {
|
|
40
|
+
const tappedRule = tap(mockEffect)(mockRule);
|
|
41
|
+
await tappedRule({}, mockContext);
|
|
42
|
+
|
|
43
|
+
expect(mockRule).toHaveBeenCalledWith({}, mockContext);
|
|
44
|
+
expect(mockEffect).toHaveBeenCalledWith({}, pass(), mockContext);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
// Async effects
|
|
48
|
+
it("should handle async effects", async () => {
|
|
49
|
+
const asyncEffect = vi.fn(async () => {
|
|
50
|
+
await Promise.resolve();
|
|
51
|
+
});
|
|
52
|
+
const tappedRule = tap(asyncEffect)(mockRule);
|
|
53
|
+
await tappedRule({});
|
|
54
|
+
|
|
55
|
+
expect(asyncEffect).toHaveBeenCalled();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Composition
|
|
59
|
+
it("should work with manual composition", async () => {
|
|
60
|
+
const rule1 = vi.fn(() => pass());
|
|
61
|
+
const rule2 = vi.fn(() => fail("Error"));
|
|
62
|
+
const effect1 = vi.fn();
|
|
63
|
+
const effect2 = vi.fn();
|
|
64
|
+
|
|
65
|
+
const pipeline = tap(effect2)(pipeRules([tap(effect1)(rule1), rule2]));
|
|
66
|
+
|
|
67
|
+
await pipeline({});
|
|
68
|
+
expect(effect1).toHaveBeenCalledWith({}, pass(), undefined);
|
|
69
|
+
expect(effect2).toHaveBeenCalledWith({}, fail("Error"), undefined);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// Type safety tests
|
|
73
|
+
it("should enforce input type matching", () => {
|
|
74
|
+
type StrictInput = { id: string };
|
|
75
|
+
const typedRule: Rule<StrictInput> = () => pass();
|
|
76
|
+
|
|
77
|
+
// Valid usage
|
|
78
|
+
tap((input: StrictInput) => console.log(input.id))(typedRule);
|
|
79
|
+
|
|
80
|
+
// @ts-expect-error - Should fail if effect expects wrong input type
|
|
81
|
+
tap((input: { other: number }) => {})(typedRule);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// Edge cases
|
|
85
|
+
it("should handle null/undefined inputs", async () => {
|
|
86
|
+
const effect = vi.fn();
|
|
87
|
+
const rule = () => pass();
|
|
88
|
+
const tappedRule = tap(effect)(rule);
|
|
89
|
+
|
|
90
|
+
await tappedRule(null as any);
|
|
91
|
+
expect(effect).toHaveBeenCalledWith(null, pass(), undefined);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("should handle effect returning Promise<void>", async () => {
|
|
95
|
+
const asyncEffect = async () => {
|
|
96
|
+
await Promise.resolve();
|
|
97
|
+
};
|
|
98
|
+
const tappedRule = tap(asyncEffect)(mockRule);
|
|
99
|
+
|
|
100
|
+
await expect(tappedRule({})).resolves.toEqual(pass());
|
|
101
|
+
});
|
|
102
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Rule, RuleResult } from "../../types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Creates a rule wrapper that performs side effects without modifying the result.
|
|
5
|
+
* @template TInput - The type of the input to validate
|
|
6
|
+
* @template TError - The type of the error (defaults to string)
|
|
7
|
+
* @template TContext - The type of the context object (optional)
|
|
8
|
+
* @param effect - Side effect function receiving input, result and context
|
|
9
|
+
* @returns A function that wraps a rule with the tap effect
|
|
10
|
+
* @example
|
|
11
|
+
* const withLogging = tap((input, result) => {
|
|
12
|
+
* console.log(`Validation result for ${input}:`, result);
|
|
13
|
+
* });
|
|
14
|
+
*
|
|
15
|
+
* const rule = withLogging(validateInput);
|
|
16
|
+
* @caveats
|
|
17
|
+
* - Errors in the effect are caught and logged but don't affect rule execution
|
|
18
|
+
* - Doesn't modify the rule's result
|
|
19
|
+
*/
|
|
20
|
+
export const tap = <TInput, TError = string, TContext = unknown>(
|
|
21
|
+
effect: (
|
|
22
|
+
input: TInput,
|
|
23
|
+
result: RuleResult<TError>,
|
|
24
|
+
context?: TContext,
|
|
25
|
+
) => Promise<void> | void,
|
|
26
|
+
): ((
|
|
27
|
+
rule: Rule<TInput, TError, TContext>,
|
|
28
|
+
) => Rule<TInput, TError, TContext>) => {
|
|
29
|
+
return (rule) => async (input, context) => {
|
|
30
|
+
const result = await rule(input, context);
|
|
31
|
+
try {
|
|
32
|
+
await effect(input, result, context);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
console.error("Tap effect failed:", error);
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
};
|
|
38
|
+
};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
+
import { validateField } from "./validate-field";
|
|
3
|
+
import { pass, fail } from "../../helpers";
|
|
4
|
+
import { Rule } from "../../types";
|
|
5
|
+
|
|
6
|
+
describe("validateField", () => {
|
|
7
|
+
interface TestUser {
|
|
8
|
+
name: string;
|
|
9
|
+
age?: number;
|
|
10
|
+
profile?: {
|
|
11
|
+
email: string;
|
|
12
|
+
verified?: boolean;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const mockUser: TestUser = {
|
|
17
|
+
name: "John Doe",
|
|
18
|
+
age: 30,
|
|
19
|
+
profile: {
|
|
20
|
+
email: "john@example.com",
|
|
21
|
+
verified: true,
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// Mock rule for testing
|
|
26
|
+
const mockRule = vi.fn((value: unknown) =>
|
|
27
|
+
value === true ? pass() : fail("Value must be true"),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
beforeEach(() => {
|
|
31
|
+
vi.clearAllMocks();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("should apply rule to extracted value", async () => {
|
|
35
|
+
const rule = validateField(
|
|
36
|
+
(user: TestUser) => user.profile?.verified,
|
|
37
|
+
mockRule,
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
const result = await rule(mockUser);
|
|
41
|
+
expect(mockRule).toHaveBeenCalledWith(true, undefined);
|
|
42
|
+
expect(result).toEqual(pass());
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("should fail when getter returns undefined with no default", async () => {
|
|
46
|
+
const rule = validateField(
|
|
47
|
+
(user: any) => user.profile.missingProp,
|
|
48
|
+
mockRule,
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
const result = await rule(mockUser);
|
|
52
|
+
expect(result).toEqual(fail("Missing required value"));
|
|
53
|
+
expect(mockRule).not.toHaveBeenCalled();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("should use default value when getter returns undefined", async () => {
|
|
57
|
+
const rule = validateField(
|
|
58
|
+
(user: any) => user.profile?.missingProp,
|
|
59
|
+
mockRule,
|
|
60
|
+
true, // default value
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
const result = await rule(mockUser);
|
|
64
|
+
expect(mockRule).toHaveBeenCalledWith(true, undefined);
|
|
65
|
+
expect(result).toEqual(pass());
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("should pass context to inner rule", async () => {
|
|
69
|
+
const context = { requestId: "123" };
|
|
70
|
+
const rule = validateField(
|
|
71
|
+
(user: TestUser) => user.profile?.verified,
|
|
72
|
+
mockRule,
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
await rule(mockUser, context);
|
|
76
|
+
expect(mockRule).toHaveBeenCalledWith(true, context);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("should handle null values same as undefined", async () => {
|
|
80
|
+
const nullUser: TestUser = {
|
|
81
|
+
name: "Null",
|
|
82
|
+
profile: null as any,
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const rule = validateField(
|
|
86
|
+
(user: TestUser) => user.profile?.verified,
|
|
87
|
+
mockRule,
|
|
88
|
+
true, // default
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
const result = await rule(nullUser);
|
|
92
|
+
expect(mockRule).toHaveBeenCalledWith(true, undefined);
|
|
93
|
+
expect(result).toEqual(pass());
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("should propagate errors from getter function", async () => {
|
|
97
|
+
const errorUser: TestUser = {
|
|
98
|
+
name: "Error",
|
|
99
|
+
get profile(): any {
|
|
100
|
+
throw new Error("Getter error");
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const rule = validateField(
|
|
105
|
+
(user: any) => user.profile.verified,
|
|
106
|
+
mockRule,
|
|
107
|
+
true, // default
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
expect(rule(errorUser)).rejects.toThrow("Getter error");
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("should fail when default value is undefined", async () => {
|
|
114
|
+
const rule = validateField(
|
|
115
|
+
(user: TestUser) => user.age,
|
|
116
|
+
(age: number) => (age > 18 ? pass() : fail("Too young")),
|
|
117
|
+
undefined, // explicit undefined default
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
const noAgeUser: TestUser = { name: "No Age" };
|
|
121
|
+
const result = await rule(noAgeUser);
|
|
122
|
+
expect(result).toEqual(fail("Missing required value"));
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("should work with falsy default values", async () => {
|
|
126
|
+
const rule = validateField(
|
|
127
|
+
(user: TestUser) => user.age,
|
|
128
|
+
(age: number) => (age === 0 ? pass() : fail("Not zero")),
|
|
129
|
+
0, // falsy default
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
const result = await rule({ name: "Test" });
|
|
133
|
+
expect(result).toEqual(pass());
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("should handle async rules", async () => {
|
|
137
|
+
const asyncRule: Rule<boolean> = async (value) => {
|
|
138
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
139
|
+
return value ? pass() : fail("Async failed");
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const rule = validateField(
|
|
143
|
+
(user: TestUser) => user.profile?.verified,
|
|
144
|
+
asyncRule,
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
const result = await rule(mockUser);
|
|
148
|
+
expect(result).toEqual(pass());
|
|
149
|
+
});
|
|
150
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { fail } from "../../helpers";
|
|
2
|
+
import { Rule } from "../../types";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Creates a rule that extracts a value using a getter function and validates it.
|
|
6
|
+
* @template TInput - The type of the input object
|
|
7
|
+
* @template TValue - The type of the extracted value
|
|
8
|
+
* @template TError - The type of the error
|
|
9
|
+
* @template TContext - The type of the context object
|
|
10
|
+
* @param getter - Function that extracts the value from input
|
|
11
|
+
* @param rule - Rule to apply to the extracted value
|
|
12
|
+
* @param defaultValue - Optional default value if getter returns undefined
|
|
13
|
+
* @returns A new rule that validates the extracted value
|
|
14
|
+
* @example
|
|
15
|
+
* const validateName = validateField(
|
|
16
|
+
* (user: User) => user.profile.name,
|
|
17
|
+
* (name) => name.length > 3 ? pass() : fail('Name too short')
|
|
18
|
+
* );
|
|
19
|
+
*
|
|
20
|
+
* const validateAge = validateField(
|
|
21
|
+
* (user: User) => user.age,
|
|
22
|
+
* (age) => age >= 18 ? pass() : fail('Must be adult'),
|
|
23
|
+
* 18 // default value
|
|
24
|
+
* );
|
|
25
|
+
*
|
|
26
|
+
* @caveats
|
|
27
|
+
* **Null/Undefined Handling**:
|
|
28
|
+
* - The getter function should handle optional properties (use optional chaining)
|
|
29
|
+
* - If getter returns undefined and no default is provided, the rule will fail
|
|
30
|
+
*
|
|
31
|
+
* **Type Safety**:
|
|
32
|
+
* - The rule's input type must match the getter's return type exactly
|
|
33
|
+
* - No automatic type narrowing (e.g., string | undefined won't become string even with default)
|
|
34
|
+
*
|
|
35
|
+
* **Default Values**:
|
|
36
|
+
* - Defaults are applied before rule execution (the rule sees the default value)
|
|
37
|
+
* - Default values aren't type-checked against potentially undefined returns
|
|
38
|
+
*/
|
|
39
|
+
export function validateField<
|
|
40
|
+
TInput,
|
|
41
|
+
TValue,
|
|
42
|
+
TError = string,
|
|
43
|
+
TContext = unknown,
|
|
44
|
+
>(
|
|
45
|
+
getter: (input: TInput) => TValue | undefined,
|
|
46
|
+
rule: Rule<TValue, TError, TContext>,
|
|
47
|
+
defaultValue?: TValue,
|
|
48
|
+
): Rule<TInput, TError, TContext> {
|
|
49
|
+
return async (input: TInput, context?: TContext) => {
|
|
50
|
+
const value = getter(input);
|
|
51
|
+
const finalValue = value !== undefined ? value : defaultValue;
|
|
52
|
+
|
|
53
|
+
if (finalValue === undefined) {
|
|
54
|
+
return fail("Missing required value" as unknown as TError);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return rule(finalValue, context);
|
|
58
|
+
};
|
|
59
|
+
}
|