ts-rules-composer 0.0.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +310 -42
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +335 -55
  5. package/dist/index.d.ts +335 -55
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +1 -1
  8. package/package.json +27 -6
  9. package/.editorconfig +0 -15
  10. package/.eslintrc.json +0 -66
  11. package/.github/CONTRIBUTING.md +0 -3
  12. package/.github/ISSUE_TEMPLATE.md +0 -9
  13. package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
  14. package/.github/workflows/docs.yml +0 -29
  15. package/.github/workflows/publish.yml +0 -25
  16. package/.github/workflows/test.yml +0 -37
  17. package/.prettierignore +0 -2
  18. package/.releaserc +0 -11
  19. package/src/lib/combinators/index.ts +0 -2
  20. package/src/lib/combinators/logic/every.spec.ts +0 -264
  21. package/src/lib/combinators/logic/every.ts +0 -47
  22. package/src/lib/combinators/logic/if-else.spec.ts +0 -72
  23. package/src/lib/combinators/logic/if-else.ts +0 -39
  24. package/src/lib/combinators/logic/index.ts +0 -8
  25. package/src/lib/combinators/logic/match.spec.ts +0 -186
  26. package/src/lib/combinators/logic/match.ts +0 -92
  27. package/src/lib/combinators/logic/not.spec.ts +0 -62
  28. package/src/lib/combinators/logic/not.ts +0 -25
  29. package/src/lib/combinators/logic/one-of.spec.ts +0 -68
  30. package/src/lib/combinators/logic/one-of.ts +0 -41
  31. package/src/lib/combinators/logic/unless.spec.ts +0 -61
  32. package/src/lib/combinators/logic/unless.ts +0 -27
  33. package/src/lib/combinators/logic/when.spec.ts +0 -123
  34. package/src/lib/combinators/logic/when.ts +0 -29
  35. package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
  36. package/src/lib/combinators/logic/with-fallback.ts +0 -37
  37. package/src/lib/combinators/utility/index.ts +0 -8
  38. package/src/lib/combinators/utility/inject.spec.ts +0 -55
  39. package/src/lib/combinators/utility/inject.ts +0 -25
  40. package/src/lib/combinators/utility/map-error.spec.ts +0 -63
  41. package/src/lib/combinators/utility/map-error.ts +0 -35
  42. package/src/lib/combinators/utility/tap.spec.ts +0 -102
  43. package/src/lib/combinators/utility/tap.ts +0 -38
  44. package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
  45. package/src/lib/combinators/utility/validate-field.ts +0 -59
  46. package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
  47. package/src/lib/combinators/utility/with-debug.ts +0 -55
  48. package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
  49. package/src/lib/combinators/utility/with-memoize.ts +0 -81
  50. package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
  51. package/src/lib/combinators/utility/with-retry.ts +0 -68
  52. package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
  53. package/src/lib/combinators/utility/with-timeout.ts +0 -34
  54. package/src/lib/composition/compose-rules.spec.ts +0 -211
  55. package/src/lib/composition/compose-rules.ts +0 -47
  56. package/src/lib/composition/index.ts +0 -3
  57. package/src/lib/composition/pipe-rules.spec.ts +0 -220
  58. package/src/lib/composition/pipe-rules.ts +0 -44
  59. package/src/lib/composition/pipe.spec.ts +0 -47
  60. package/src/lib/composition/pipe.ts +0 -106
  61. package/src/lib/helpers/context/has-context.ts +0 -13
  62. package/src/lib/helpers/context/index.ts +0 -3
  63. package/src/lib/helpers/context/require-context.spec.ts +0 -55
  64. package/src/lib/helpers/context/require-context.ts +0 -61
  65. package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
  66. package/src/lib/helpers/context/with-lazy-context.ts +0 -35
  67. package/src/lib/helpers/index.ts +0 -6
  68. package/src/lib/helpers/result/fail.ts +0 -15
  69. package/src/lib/helpers/result/index.ts +0 -2
  70. package/src/lib/helpers/result/pass.ts +0 -14
  71. package/src/lib/helpers/retry/calculate-delay.ts +0 -31
  72. package/src/lib/index.ts +0 -4
  73. package/src/lib/types/composition-options.ts +0 -7
  74. package/src/lib/types/debug-options.ts +0 -36
  75. package/src/lib/types/index.ts +0 -4
  76. package/src/lib/types/rule-result.ts +0 -16
  77. package/src/lib/types/rule.ts +0 -21
  78. package/src/test/helpers/get-rule-error.ts +0 -23
  79. package/src/test/integration.spec.ts +0 -285
  80. package/tsconfig.json +0 -55
  81. package/tsup.config.ts +0 -36
  82. package/vitest.config.ts +0 -16
@@ -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 { 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 { 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, 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
- });
@@ -1,38 +0,0 @@
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
- };
@@ -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 { 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,59 +0,0 @@
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
- }
@@ -1,71 +0,0 @@
1
- import { describe, vi, beforeEach, it, expect } from "vitest";
2
- import { pass, fail } from "../../helpers";
3
- import { 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
- });
@@ -1,55 +0,0 @@
1
- import { DebugOptions, Rule } from "../../types";
2
-
3
- /**
4
- * Wraps a rule with debugging capabilities.
5
- * @template TInput - The type of the input to validate
6
- * @template TError - The type of the error
7
- * @template TContext - The type of the context object
8
- * @param rule - The rule to wrap with debug capabilities
9
- * @param options - Debug configuration or simple name string
10
- * @param options.name - Name for the debug output
11
- * @param options.onStart - Callback when rule starts executing
12
- * @param options.onEnd - Callback when rule completes successfully
13
- * @param options.onError - Callback when rule throws an error
14
- * @returns A new rule with debug capabilities
15
- * @example
16
- * const rule = withDebug(expensiveValidation, {
17
- * name: "Expensive Validation",
18
- * onStart: (input) => console.log(`Starting with input: ${input}`),
19
- * onEnd: (input, result, ctx, { duration }) => {
20
- * console.log(`Completed in ${duration}ms`);
21
- * }
22
- * });
23
- * @caveats
24
- * - Debug callbacks are executed synchronously and may impact performance
25
- * - Errors in callbacks will propagate and potentially mask rule errors
26
- */
27
- export const withDebug = <TInput, TError, TContext>(
28
- rule: Rule<TInput, TError, TContext>,
29
- options: DebugOptions<TInput, TError, TContext> | string,
30
- ): Rule<TInput, TError, TContext> => {
31
- const config = typeof options === "string" ? { name: options } : options;
32
-
33
- return async (input, context) => {
34
- const startTime = performance.now();
35
- const ruleName = config.name || rule.name || "anonymous_rule";
36
-
37
- try {
38
- config.onStart?.(input, context);
39
- const result = await rule(input, context);
40
- const duration = performance.now() - startTime;
41
-
42
- config.onEnd?.(input, result, context, {
43
- ruleName,
44
- duration,
45
- startTime,
46
- });
47
-
48
- return result;
49
- } catch (error) {
50
- const duration = performance.now() - startTime;
51
- config.onError?.(error, input, context, duration);
52
- throw error; // Preserve original error throwing behavior
53
- }
54
- };
55
- };