ts-rules-composer 1.0.0 → 1.0.2

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 (110) hide show
  1. package/README.md +87 -14
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +148 -176
  5. package/dist/index.d.ts +148 -176
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +1 -1
  8. package/package.json +40 -43
  9. package/.editorconfig +0 -15
  10. package/.github/CONTRIBUTING.md +0 -3
  11. package/.github/ISSUE_TEMPLATE.md +0 -9
  12. package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
  13. package/.github/workflows/docs.yml +0 -29
  14. package/.github/workflows/publish.yml +0 -25
  15. package/.github/workflows/test.yml +0 -37
  16. package/.prettierignore +0 -2
  17. package/.releaserc +0 -11
  18. package/eslint.config.mjs +0 -84
  19. package/examples/financial-transaction.example.ts +0 -188
  20. package/examples/model-deployment.example.ts +0 -136
  21. package/examples/user-registration.example.ts +0 -101
  22. package/src/lib/combinators/index.ts +0 -2
  23. package/src/lib/combinators/logic/every.spec.ts +0 -264
  24. package/src/lib/combinators/logic/every.ts +0 -57
  25. package/src/lib/combinators/logic/if-else.spec.ts +0 -82
  26. package/src/lib/combinators/logic/if-else.ts +0 -64
  27. package/src/lib/combinators/logic/index.ts +0 -8
  28. package/src/lib/combinators/logic/match.spec.ts +0 -186
  29. package/src/lib/combinators/logic/match.ts +0 -106
  30. package/src/lib/combinators/logic/not.spec.ts +0 -64
  31. package/src/lib/combinators/logic/not.ts +0 -34
  32. package/src/lib/combinators/logic/one-of.spec.ts +0 -68
  33. package/src/lib/combinators/logic/one-of.ts +0 -48
  34. package/src/lib/combinators/logic/unless.spec.ts +0 -61
  35. package/src/lib/combinators/logic/unless.ts +0 -50
  36. package/src/lib/combinators/logic/when.spec.ts +0 -119
  37. package/src/lib/combinators/logic/when.ts +0 -50
  38. package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
  39. package/src/lib/combinators/logic/with-fallback.ts +0 -46
  40. package/src/lib/combinators/utility/index.ts +0 -11
  41. package/src/lib/combinators/utility/inject.spec.ts +0 -55
  42. package/src/lib/combinators/utility/inject.ts +0 -25
  43. package/src/lib/combinators/utility/map-error.spec.ts +0 -63
  44. package/src/lib/combinators/utility/map-error.ts +0 -35
  45. package/src/lib/combinators/utility/tap.spec.ts +0 -102
  46. package/src/lib/combinators/utility/tap.ts +0 -28
  47. package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
  48. package/src/lib/combinators/utility/validate-field.ts +0 -66
  49. package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
  50. package/src/lib/combinators/utility/with-debug.ts +0 -55
  51. package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
  52. package/src/lib/combinators/utility/with-memoize.ts +0 -89
  53. package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
  54. package/src/lib/combinators/utility/with-retry.ts +0 -70
  55. package/src/lib/combinators/utility/with-safe-error.spec.ts +0 -137
  56. package/src/lib/combinators/utility/with-safe-error.ts +0 -56
  57. package/src/lib/combinators/utility/with-safe-predicate.spec.ts +0 -176
  58. package/src/lib/combinators/utility/with-safe-predicate.ts +0 -64
  59. package/src/lib/combinators/utility/with-tap.spec.ts +0 -104
  60. package/src/lib/combinators/utility/with-tap.ts +0 -46
  61. package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
  62. package/src/lib/combinators/utility/with-timeout.ts +0 -41
  63. package/src/lib/composition/compose-rules.spec.ts +0 -211
  64. package/src/lib/composition/compose-rules.ts +0 -55
  65. package/src/lib/composition/index.ts +0 -3
  66. package/src/lib/composition/pipe-rules.spec.ts +0 -220
  67. package/src/lib/composition/pipe-rules.ts +0 -52
  68. package/src/lib/composition/pipe.spec.ts +0 -47
  69. package/src/lib/composition/pipe.ts +0 -107
  70. package/src/lib/helpers/clone/clone.ts +0 -12
  71. package/src/lib/helpers/clone/getCloneFn.ts +0 -17
  72. package/src/lib/helpers/clone/shallowClone.ts +0 -12
  73. package/src/lib/helpers/context/has-context.ts +0 -13
  74. package/src/lib/helpers/context/index.ts +0 -3
  75. package/src/lib/helpers/context/require-context.spec.ts +0 -55
  76. package/src/lib/helpers/context/require-context.ts +0 -61
  77. package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
  78. package/src/lib/helpers/context/with-lazy-context.ts +0 -35
  79. package/src/lib/helpers/index.ts +0 -8
  80. package/src/lib/helpers/result/fail.ts +0 -15
  81. package/src/lib/helpers/result/index.ts +0 -2
  82. package/src/lib/helpers/result/pass.ts +0 -14
  83. package/src/lib/helpers/retry/calculate-delay.ts +0 -31
  84. package/src/lib/helpers/safety/get-normalized-rule.spec.ts +0 -209
  85. package/src/lib/helpers/safety/get-normalized-rule.ts +0 -14
  86. package/src/lib/helpers/safety/get-normalized-rules.spec.ts +0 -138
  87. package/src/lib/helpers/safety/get-normalized-rules.ts +0 -14
  88. package/src/lib/index.ts +0 -4
  89. package/src/lib/types/composition-options.ts +0 -32
  90. package/src/lib/types/debug-options.ts +0 -36
  91. package/src/lib/types/index.ts +0 -8
  92. package/src/lib/types/predicate-result.ts +0 -20
  93. package/src/lib/types/predicate-safe.ts +0 -10
  94. package/src/lib/types/predicate-safety-options.ts +0 -27
  95. package/src/lib/types/predicate.ts +0 -8
  96. package/src/lib/types/prettify.ts +0 -3
  97. package/src/lib/types/rule-result.ts +0 -16
  98. package/src/lib/types/rule-safety-options.ts +0 -34
  99. package/src/lib/types/rule.ts +0 -21
  100. package/src/lib/types/safety-options.ts +0 -7
  101. package/src/test/financial-transaction.spec.ts +0 -251
  102. package/src/test/helpers/get-rule-error.ts +0 -23
  103. package/src/test/integration.spec.ts +0 -285
  104. package/src/test/model-deployment.spec.ts +0 -209
  105. package/src/test/user-registration.spec.ts +0 -164
  106. package/tsconfig.json +0 -56
  107. package/tsup.config.ts +0 -36
  108. package/typedoc/tsconfig.typedoc.json +0 -15
  109. package/typedoc/typedoc.json +0 -14
  110. package/vitest.config.ts +0 -16
@@ -1,46 +0,0 @@
1
- import { getNormalizedRules } from "../../helpers";
2
- import type { Rule, RuleSafetyOptions } from "../../types";
3
-
4
- /**
5
- * Creates a rule that falls back to an alternative rule if the main rule fails.
6
- * @template TInput - Input type
7
- * @template TError - Error type
8
- * @template TContext - Context type
9
- * @param mainRule - Primary rule to execute first
10
- * @param fallbackRule - Rule to execute if main rule fails
11
- * @param options - Configuration options
12
- * @param options.onlyFallbackOn - Predicate to conditionally enable fallback
13
- * @param options.errorHandlingMode - Determines how errors are handled:
14
- * - 'safe': (default) Converts thrown errors to validation failures
15
- * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
16
- * @param options.errorTransform - Custom transformation for caught errors
17
- * @returns A new composite rule
18
- * @example
19
- * const rule = withFallback(
20
- * premiumValidation,
21
- * basicValidation,
22
- * { onlyFallbackOn: err => err.code !== 'FATAL' }
23
- * );
24
- */
25
- export const withFallback = <TInput, TError, TContext>(
26
- mainRule: Rule<TInput, TError, TContext>,
27
- fallbackRule: Rule<TInput, TError, TContext>,
28
- options: RuleSafetyOptions<TError> & {
29
- onlyFallbackOn?: (error: TError) => boolean;
30
- } = {},
31
- ): Rule<TInput, TError, TContext> => {
32
- return async (input: TInput, context?: TContext) => {
33
- const [mainSafeRule, fallbackSafeRule] = getNormalizedRules([
34
- mainRule,
35
- fallbackRule,
36
- ]);
37
- const result = await mainSafeRule(input, context);
38
- if (
39
- result.status === "failed" &&
40
- (!options.onlyFallbackOn || options.onlyFallbackOn(result.error))
41
- ) {
42
- return fallbackSafeRule(input, context);
43
- }
44
- return result;
45
- };
46
- };
@@ -1,11 +0,0 @@
1
- export * from "./inject";
2
- export * from "./map-error";
3
- export * from "./tap";
4
- export * from "./with-tap";
5
- export * from "./validate-field";
6
- export * from "./with-debug";
7
- export * from "./with-memoize";
8
- export * from "./with-retry";
9
- export * from "./with-safe-error";
10
- export * from "./with-safe-predicate";
11
- export * from "./with-timeout";
@@ -1,55 +0,0 @@
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
- });
@@ -1,25 +0,0 @@
1
- import type { 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
- };
@@ -1,63 +0,0 @@
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
- });
@@ -1,35 +0,0 @@
1
- import { fail, pass } from "../../helpers";
2
- import type { 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
- };
@@ -1,102 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { tap } from "./tap";
3
- import { pass } from "../../helpers";
4
- import { pipeRules } from "../../composition";
5
-
6
- describe("tap", () => {
7
- const mockEffect = vi.fn();
8
- const mockContext = { requestId: "123" };
9
-
10
- beforeEach(() => {
11
- vi.clearAllMocks();
12
- });
13
-
14
- // 1. Basic functionality
15
- it("should execute effect without modifying validation result", async () => {
16
- const input = { id: "test" };
17
- const rule = tap(mockEffect);
18
- const result = await rule(input);
19
-
20
- expect(result).toEqual(pass());
21
- expect(mockEffect).toHaveBeenCalledWith(input, undefined);
22
- });
23
-
24
- // 2. Context handling
25
- it("should pass context to the effect", async () => {
26
- const input = { id: "test" };
27
- const rule = tap(mockEffect);
28
- await rule(input, mockContext);
29
-
30
- expect(mockEffect).toHaveBeenCalledWith(input, mockContext);
31
- });
32
-
33
- // 3. Error isolation
34
- it("should not propagate effect errors", async () => {
35
- const errorEffect = vi.fn().mockRejectedValue(new Error("Effect failed"));
36
- const input = { id: "test" };
37
- const rule = tap(errorEffect);
38
-
39
- await expect(rule(input)).resolves.toEqual(pass());
40
- expect(errorEffect).toHaveBeenCalled();
41
- });
42
-
43
- // 4. Async effects
44
- it("should handle async effects", async () => {
45
- const asyncEffect = vi.fn().mockImplementation(async (input: any) => {
46
- await Promise.resolve();
47
- console.log(input);
48
- });
49
- const input = { id: "test" };
50
- const rule = tap(asyncEffect);
51
-
52
- await expect(rule(input)).resolves.toEqual(pass());
53
- expect(asyncEffect).toHaveBeenCalledWith(input, undefined);
54
- });
55
-
56
- // 5. Integration with pipeRules
57
- it("should work in composition pipelines", async () => {
58
- const mockRule = vi.fn().mockResolvedValue(pass());
59
- const input = { id: "test" };
60
- const pipeline = pipeRules([tap(mockEffect), mockRule]);
61
-
62
- await pipeline(input);
63
- expect(mockEffect).toHaveBeenCalledBefore(mockRule);
64
- expect(mockRule).toHaveBeenCalledWith(input, undefined);
65
- });
66
-
67
- // 6. Type safety tests
68
- it("should enforce input type matching", async () => {
69
- type StrictInput = { id: string };
70
- const typedEffect = vi.fn((_: StrictInput) => {});
71
-
72
- // Valid usage
73
- tap(typedEffect)({ id: "123" });
74
-
75
- // @ts-expect-error - Should fail if input types mismatch
76
- tap(typedEffect)({ notId: "123" });
77
- });
78
-
79
- // 8. Effect error handling
80
- it("should log effect errors to console", async () => {
81
- const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
82
- const error = new Error("Test error");
83
- const errorEffect = vi.fn().mockRejectedValue(error);
84
- const rule = tap(errorEffect);
85
-
86
- await rule({});
87
- expect(consoleSpy).toHaveBeenCalledWith("Tap effect failed: ", error);
88
- consoleSpy.mockRestore();
89
- });
90
-
91
- // 9. Multiple taps in pipeline
92
- it("should allow multiple taps in sequence", async () => {
93
- const effect1 = vi.fn();
94
- const effect2 = vi.fn();
95
- const input = { id: "test" };
96
-
97
- const pipeline = pipeRules([tap(effect1), tap(effect2)]);
98
-
99
- await pipeline(input);
100
- expect(effect1).toHaveBeenCalledBefore(effect2);
101
- });
102
- });
@@ -1,28 +0,0 @@
1
- import { pass } from "../../helpers";
2
- import type { Rule } from "../../types";
3
-
4
- /**
5
- * Creates a standalone tap effect for use in composition pipelines
6
- * @template TInput - Input type
7
- * @template TError - Error type
8
- * @template TContext - Context type
9
- * @param effect - Side effect function receiving (input, context)
10
- * @returns A rule that passes through input unchanged
11
- * @example
12
- * pipeRules([
13
- * tap((input) => console.log('Processing:', input)),
14
- * validateInput
15
- * ])
16
- */
17
- export const tap = <TInput, TError = string, TContext = unknown>(
18
- effect: (input: TInput, context?: TContext) => Promise<void> | void,
19
- ): Rule<TInput, TError, TContext> => {
20
- return async (input, context) => {
21
- try {
22
- await effect(input, context);
23
- } catch (error) {
24
- console.error("Tap effect failed: ", error);
25
- }
26
- return pass();
27
- };
28
- };
@@ -1,150 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { validateField } from "./validate-field";
3
- import { pass, fail } from "../../helpers";
4
- import type { 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
- });
@@ -1,66 +0,0 @@
1
- import { fail, getNormalizedRule } from "../../helpers";
2
- import type { Rule, RuleSafetyOptions } 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
- * @param options - Configuration for error handling safety
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 validates the extracted value
19
- * @example
20
- * const validateName = validateField(
21
- * (user: User) => user.profile.name,
22
- * (name) => name.length > 3 ? pass() : fail('Name too short')
23
- * );
24
- *
25
- * const validateAge = validateField(
26
- * (user: User) => user.age,
27
- * (age) => age >= 18 ? pass() : fail('Must be adult'),
28
- * 18 // default value
29
- * );
30
- *
31
- * @caveats
32
- * **Null/Undefined Handling**:
33
- * - The getter function should handle optional properties (use optional chaining)
34
- * - If getter returns undefined and no default is provided, the rule will fail
35
- *
36
- * **Type Safety**:
37
- * - The rule's input type must match the getter's return type exactly
38
- * - No automatic type narrowing (e.g., string | undefined won't become string even with default)
39
- *
40
- * **Default Values**:
41
- * - Defaults are applied before rule execution (the rule sees the default value)
42
- * - Default values aren't type-checked against potentially undefined returns
43
- */
44
- export function validateField<
45
- TInput,
46
- TValue,
47
- TError = string,
48
- TContext = unknown,
49
- >(
50
- getter: (input: TInput) => TValue | undefined,
51
- rule: Rule<TValue, TError, TContext>,
52
- defaultValue?: TValue,
53
- options?: RuleSafetyOptions<TError>,
54
- ): Rule<TInput, TError, TContext> {
55
- return async (input: TInput, context?: TContext) => {
56
- const value = getter(input);
57
- const finalValue = value !== undefined ? value : defaultValue;
58
- const safeRule = getNormalizedRule(rule, options);
59
-
60
- if (finalValue === undefined) {
61
- return fail("Missing required value" as unknown as TError);
62
- }
63
-
64
- return safeRule(finalValue, context);
65
- };
66
- }
@@ -1,71 +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 { withDebug } from "./with-debug";
5
-
6
- describe("withDebug", () => {
7
- const mockRule = vi.fn((input: string) =>
8
- input === "valid" ? pass() : fail("Invalid input"),
9
- );
10
-
11
- beforeEach(() => {
12
- vi.clearAllMocks();
13
- });
14
-
15
- it("should call onStart and onEnd for successful rules", async () => {
16
- const onStart = vi.fn();
17
- const onEnd = vi.fn();
18
-
19
- const rule = withDebug(mockRule, {
20
- name: "test-rule",
21
- onStart,
22
- onEnd,
23
- });
24
-
25
- const result = await rule("valid");
26
-
27
- expect(onStart).toHaveBeenCalledWith("valid", undefined);
28
- expect(onEnd).toHaveBeenCalledWith(
29
- "valid",
30
- pass(),
31
- undefined,
32
- expect.objectContaining({
33
- duration: expect.any(Number),
34
- }),
35
- );
36
- expect(result.status).toBe("passed");
37
- });
38
-
39
- it("should handle errors with onError callback", async () => {
40
- const error = new Error("Boom!");
41
- const failingRule = vi.fn(() => {
42
- throw error;
43
- });
44
- const onError = vi.fn();
45
-
46
- const rule = withDebug(failingRule, {
47
- onError,
48
- });
49
-
50
- await expect(rule("input")).rejects.toThrow("Boom!");
51
- expect(onError).toHaveBeenCalled();
52
- });
53
-
54
- it("should preserve context", async () => {
55
- const contextRule: Rule<string, string, { userId: number }> = (
56
- _input,
57
- ctx,
58
- ) => (ctx?.userId === 42 ? pass() : fail("Invalid"));
59
-
60
- const onEnd = vi.fn();
61
- const rule = withDebug(contextRule, { onEnd });
62
-
63
- await rule("test", { userId: 42 });
64
- expect(onEnd).toHaveBeenCalledWith(
65
- "test",
66
- pass(),
67
- { userId: 42 },
68
- expect.anything(),
69
- );
70
- });
71
- });