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.
Files changed (103) hide show
  1. package/package.json +7 -1
  2. package/.editorconfig +0 -15
  3. package/.github/CONTRIBUTING.md +0 -3
  4. package/.github/ISSUE_TEMPLATE.md +0 -9
  5. package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
  6. package/.github/workflows/docs.yml +0 -29
  7. package/.github/workflows/publish.yml +0 -25
  8. package/.github/workflows/test.yml +0 -37
  9. package/.prettierignore +0 -2
  10. package/.releaserc +0 -11
  11. package/eslint.config.mjs +0 -84
  12. package/examples/financial-transaction.example.ts +0 -188
  13. package/examples/model-deployment.example.ts +0 -136
  14. package/examples/user-registration.example.ts +0 -101
  15. package/src/lib/combinators/index.ts +0 -2
  16. package/src/lib/combinators/logic/every.spec.ts +0 -264
  17. package/src/lib/combinators/logic/every.ts +0 -57
  18. package/src/lib/combinators/logic/if-else.spec.ts +0 -82
  19. package/src/lib/combinators/logic/if-else.ts +0 -64
  20. package/src/lib/combinators/logic/index.ts +0 -8
  21. package/src/lib/combinators/logic/match.spec.ts +0 -186
  22. package/src/lib/combinators/logic/match.ts +0 -106
  23. package/src/lib/combinators/logic/not.spec.ts +0 -64
  24. package/src/lib/combinators/logic/not.ts +0 -34
  25. package/src/lib/combinators/logic/one-of.spec.ts +0 -68
  26. package/src/lib/combinators/logic/one-of.ts +0 -48
  27. package/src/lib/combinators/logic/unless.spec.ts +0 -61
  28. package/src/lib/combinators/logic/unless.ts +0 -50
  29. package/src/lib/combinators/logic/when.spec.ts +0 -119
  30. package/src/lib/combinators/logic/when.ts +0 -50
  31. package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
  32. package/src/lib/combinators/logic/with-fallback.ts +0 -46
  33. package/src/lib/combinators/utility/index.ts +0 -11
  34. package/src/lib/combinators/utility/inject.spec.ts +0 -55
  35. package/src/lib/combinators/utility/inject.ts +0 -25
  36. package/src/lib/combinators/utility/map-error.spec.ts +0 -63
  37. package/src/lib/combinators/utility/map-error.ts +0 -35
  38. package/src/lib/combinators/utility/tap.spec.ts +0 -102
  39. package/src/lib/combinators/utility/tap.ts +0 -28
  40. package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
  41. package/src/lib/combinators/utility/validate-field.ts +0 -66
  42. package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
  43. package/src/lib/combinators/utility/with-debug.ts +0 -55
  44. package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
  45. package/src/lib/combinators/utility/with-memoize.ts +0 -89
  46. package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
  47. package/src/lib/combinators/utility/with-retry.ts +0 -70
  48. package/src/lib/combinators/utility/with-safe-error.spec.ts +0 -137
  49. package/src/lib/combinators/utility/with-safe-error.ts +0 -56
  50. package/src/lib/combinators/utility/with-safe-predicate.spec.ts +0 -176
  51. package/src/lib/combinators/utility/with-safe-predicate.ts +0 -64
  52. package/src/lib/combinators/utility/with-tap.spec.ts +0 -104
  53. package/src/lib/combinators/utility/with-tap.ts +0 -46
  54. package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
  55. package/src/lib/combinators/utility/with-timeout.ts +0 -41
  56. package/src/lib/composition/compose-rules.spec.ts +0 -211
  57. package/src/lib/composition/compose-rules.ts +0 -55
  58. package/src/lib/composition/index.ts +0 -3
  59. package/src/lib/composition/pipe-rules.spec.ts +0 -220
  60. package/src/lib/composition/pipe-rules.ts +0 -52
  61. package/src/lib/composition/pipe.spec.ts +0 -47
  62. package/src/lib/composition/pipe.ts +0 -107
  63. package/src/lib/helpers/clone/clone.ts +0 -12
  64. package/src/lib/helpers/clone/getCloneFn.ts +0 -17
  65. package/src/lib/helpers/clone/shallowClone.ts +0 -12
  66. package/src/lib/helpers/context/has-context.ts +0 -13
  67. package/src/lib/helpers/context/index.ts +0 -3
  68. package/src/lib/helpers/context/require-context.spec.ts +0 -55
  69. package/src/lib/helpers/context/require-context.ts +0 -61
  70. package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
  71. package/src/lib/helpers/context/with-lazy-context.ts +0 -35
  72. package/src/lib/helpers/index.ts +0 -8
  73. package/src/lib/helpers/result/fail.ts +0 -15
  74. package/src/lib/helpers/result/index.ts +0 -2
  75. package/src/lib/helpers/result/pass.ts +0 -14
  76. package/src/lib/helpers/retry/calculate-delay.ts +0 -31
  77. package/src/lib/helpers/safety/get-normalized-rule.spec.ts +0 -209
  78. package/src/lib/helpers/safety/get-normalized-rule.ts +0 -14
  79. package/src/lib/helpers/safety/get-normalized-rules.spec.ts +0 -138
  80. package/src/lib/helpers/safety/get-normalized-rules.ts +0 -14
  81. package/src/lib/index.ts +0 -4
  82. package/src/lib/types/composition-options.ts +0 -32
  83. package/src/lib/types/debug-options.ts +0 -36
  84. package/src/lib/types/index.ts +0 -8
  85. package/src/lib/types/predicate-result.ts +0 -20
  86. package/src/lib/types/predicate-safe.ts +0 -10
  87. package/src/lib/types/predicate-safety-options.ts +0 -27
  88. package/src/lib/types/predicate.ts +0 -8
  89. package/src/lib/types/prettify.ts +0 -3
  90. package/src/lib/types/rule-result.ts +0 -16
  91. package/src/lib/types/rule-safety-options.ts +0 -34
  92. package/src/lib/types/rule.ts +0 -21
  93. package/src/lib/types/safety-options.ts +0 -7
  94. package/src/test/financial-transaction.spec.ts +0 -251
  95. package/src/test/helpers/get-rule-error.ts +0 -23
  96. package/src/test/integration.spec.ts +0 -285
  97. package/src/test/model-deployment.spec.ts +0 -209
  98. package/src/test/user-registration.spec.ts +0 -164
  99. package/tsconfig.json +0 -56
  100. package/tsup.config.ts +0 -36
  101. package/typedoc/tsconfig.typedoc.json +0 -15
  102. package/typedoc/typedoc.json +0 -14
  103. package/vitest.config.ts +0 -16
@@ -1,56 +0,0 @@
1
- import { fail } from "../../helpers";
2
- import type { Rule, RuleResult } from "../../types";
3
-
4
- /**
5
- * Wraps a rule to catch errors and convert them to failed RuleResults
6
- * @template TInput - The input type
7
- * @template TError - The error type (defaults to string)
8
- * @template TContext - The context type
9
- * @param rule - The rule to protect
10
- * @param errorMapper - Optional error transformation logic
11
- * @returns A protected version of the rule
12
- * @example
13
- * // Basic usage with default error handling
14
- * const safeRule = withSafeError(riskyRule);
15
- *
16
- * // With custom error transformation
17
- * const customSafeRule = withSafeError(riskyRule, e => ({
18
- * code: 500,
19
- * message: String(e)
20
- * }));
21
- *
22
- * @caveats
23
- *
24
- * - Generic parameters must be explicitly set for custom error types
25
- * - Doesn't verify error types match TError at runtime
26
- */
27
- export const withSafeError = <TInput, TError = string, TContext = unknown>(
28
- rule: Rule<TInput, TError, TContext>,
29
- errorTransform: (error: unknown) => TError = (e) => {
30
- // Preserve object structure if TError is object-like
31
- if (typeof e === "object" && e !== null) return e as TError;
32
- // Default to string for primitives/errors
33
- return (e instanceof Error ? e.message : String(e)) as TError;
34
- },
35
- ): Rule<TInput, TError, TContext> => {
36
- return async (
37
- input: TInput,
38
- context?: TContext,
39
- ): Promise<RuleResult<TError>> => {
40
- try {
41
- const result = await rule(input, context);
42
-
43
- // Preserve existing RuleResults
44
- if (result && typeof result === "object" && "status" in result) {
45
- return result;
46
- }
47
-
48
- // Handle invalid rule implementations that don't return RuleResult
49
- return fail(
50
- errorTransform(new Error(`Invalid rule - did not return RuleResult`)),
51
- );
52
- } catch (error) {
53
- return fail(errorTransform(error));
54
- }
55
- };
56
- };
@@ -1,176 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { withSafePredicate } from "./with-safe-predicate";
3
-
4
- describe("withSafePredicate", () => {
5
- const mockPredicate = vi.fn();
6
- const mockErrorTransform = vi.fn();
7
-
8
- beforeEach(() => {
9
- vi.clearAllMocks();
10
- mockErrorTransform.mockImplementation((e) => `Transformed: ${String(e)}`);
11
- });
12
-
13
- describe("Basic functionality", () => {
14
- it("should pass through boolean results (true)", async () => {
15
- mockPredicate.mockResolvedValue(true);
16
- const safePred = withSafePredicate(mockPredicate);
17
- const result = await safePred("test");
18
-
19
- expect(result).toEqual({ status: "passed", value: true });
20
- expect(mockPredicate).toHaveBeenCalledWith("test", undefined);
21
- });
22
-
23
- it("should pass through boolean results (false)", async () => {
24
- mockPredicate.mockResolvedValue(false);
25
- const safePred = withSafePredicate(mockPredicate);
26
- const result = await safePred("test");
27
-
28
- expect(result).toEqual({ status: "passed", value: false });
29
- });
30
-
31
- it("should handle sync predicates", async () => {
32
- mockPredicate.mockReturnValue(true);
33
- const safePred = withSafePredicate(mockPredicate);
34
- const result = await safePred("test");
35
-
36
- expect(result).toEqual({ status: "passed", value: true });
37
- });
38
- });
39
-
40
- describe("Error handling", () => {
41
- it("should catch thrown errors", async () => {
42
- mockPredicate.mockImplementation(() => {
43
- throw new Error("Boom!");
44
- });
45
- const safePred = withSafePredicate(mockPredicate);
46
- const result = await safePred("test");
47
-
48
- expect(result.status).toBe("failed");
49
- expect((result as any).error).toEqual(new Error("Boom!"));
50
- });
51
-
52
- it("should catch rejected promises", async () => {
53
- mockPredicate.mockRejectedValue(new Error("Async boom!"));
54
- const safePred = withSafePredicate(mockPredicate);
55
- const result = await safePred("test");
56
-
57
- expect(result.status).toBe("failed");
58
- expect((result as any).error).toEqual(new Error("Async boom!"));
59
- });
60
-
61
- it("should handle non-Error throws", async () => {
62
- mockPredicate.mockImplementation(() => {
63
- throw "String error";
64
- });
65
- const safePred = withSafePredicate(mockPredicate);
66
- const result = await safePred("test");
67
-
68
- expect(result.status).toBe("failed");
69
- expect((result as any).error).toBe("String error");
70
- });
71
-
72
- it("should use custom error transform", async () => {
73
- mockPredicate.mockRejectedValue(new Error("Original"));
74
- const safePred = withSafePredicate(mockPredicate, mockErrorTransform);
75
- const result = await safePred("test");
76
-
77
- expect(result.status).toBe("failed");
78
- expect((result as any).error).toBe("Transformed: Error: Original");
79
- expect(mockErrorTransform).toHaveBeenCalledWith(expect.any(Error));
80
- });
81
- });
82
-
83
- describe("Type safety enforcement", () => {
84
- it("should fail on non-boolean returns (undefined)", async () => {
85
- mockPredicate.mockResolvedValue(undefined);
86
- const safePred = withSafePredicate(mockPredicate);
87
- const result = await safePred("test");
88
-
89
- expect(result.status).toBe("failed");
90
- expect((result as any).error.message).toContain(
91
- "Predicate must return boolean",
92
- );
93
- });
94
-
95
- it("should fail on non-boolean returns (object)", async () => {
96
- mockPredicate.mockResolvedValue({ not: "boolean" });
97
- const safePred = withSafePredicate(mockPredicate);
98
- const result = await safePred("test");
99
-
100
- expect(result.status).toBe("failed");
101
- expect((result as any).error.message).toContain("got object");
102
- });
103
-
104
- it("should fail on non-boolean returns (null)", async () => {
105
- mockPredicate.mockResolvedValue(null);
106
- const safePred = withSafePredicate(mockPredicate);
107
- const result = await safePred("test");
108
-
109
- expect(result.status).toBe("failed");
110
- expect((result as any).error.message).toContain("got object");
111
- });
112
- });
113
-
114
- describe("Context handling", () => {
115
- it("should pass context to predicate", async () => {
116
- const context = { auth: true };
117
- mockPredicate.mockResolvedValue(true);
118
- const safePred = withSafePredicate(mockPredicate);
119
- await safePred("test", context);
120
-
121
- expect(mockPredicate).toHaveBeenCalledWith("test", context);
122
- });
123
-
124
- it("should handle undefined context", async () => {
125
- mockPredicate.mockResolvedValue(true);
126
- const safePred = withSafePredicate(mockPredicate);
127
- await safePred("test");
128
-
129
- expect(mockPredicate).toHaveBeenCalledWith("test", undefined);
130
- });
131
- });
132
-
133
- describe("Edge cases", () => {
134
- it("should handle custom error types", async () => {
135
- interface CustomError {
136
- code: number;
137
- details: string;
138
- }
139
- const errorTransform = (e: unknown): CustomError => ({
140
- code: 500,
141
- details: String(e),
142
- });
143
-
144
- mockPredicate.mockRejectedValue(new Error("Test"));
145
- const safePred = withSafePredicate(mockPredicate, errorTransform);
146
- const result = await safePred("test");
147
-
148
- expect(result.status).toBe("failed");
149
- expect((result as any).error).toEqual({
150
- code: 500,
151
- details: "Error: Test",
152
- });
153
- });
154
-
155
- it("should preserve object error structure when configured", async () => {
156
- const originalError = { code: 400, message: "Bad request" };
157
- mockPredicate.mockRejectedValue(originalError);
158
-
159
- // No transform - should preserve object structure
160
- const safePred = withSafePredicate(mockPredicate);
161
- const result = await safePred("test");
162
-
163
- expect(result.status).toBe("failed");
164
- expect((result as any).error).toEqual(originalError);
165
- });
166
-
167
- it("should handle falsy values (empty string)", async () => {
168
- mockPredicate.mockImplementation(() => "");
169
- const safePred = withSafePredicate(mockPredicate);
170
- const result = await safePred("test");
171
-
172
- expect(result.status).toBe("failed");
173
- expect((result as any).error.message).toContain("got string");
174
- });
175
- });
176
- });
@@ -1,64 +0,0 @@
1
- import type { Predicate, PredicateSafe, PredicateResult } from "../../types";
2
-
3
- /**
4
- * Wraps a predicate function with error handling and type safety.
5
- * @template TInput - The input type
6
- * @template TError - The error type (defaults to string)
7
- * @template TContext - The context type
8
- * @param predicate - The predicate function to wrap
9
- * @param errorTransform - Optional function to transform errors
10
- * @returns A safe predicate that never throws
11
- *
12
- * @example
13
- * const safePredicate = withSafePredicate(
14
- * (input: string) => input.length > 5,
15
- * (err) => `Predicate failed: ${String(err)}`
16
- * );
17
- *
18
- * @caveats
19
- * **Error Handling Behavior**:
20
- * - Will catch both synchronous throws and Promise rejections
21
- * - Errors in the errorTransform itself will propagate (not caught)
22
- * - The default transformer converts all errors to strings except Error objects
23
- *
24
- * **Edge Cases**:
25
- * - Returns failed result for non-boolean returns (including null/undefined)
26
- * - Returns failed result for Promise<non-boolean> resolutions
27
- * - Returns failed result for Promise rejections (transformed via errorTransform)
28
- * - Returns failed result for thrown non-Error values (like `throw "string"`)
29
- */
30
- export const withSafePredicate = <TInput, TError = string, TContext = unknown>(
31
- predicate: Predicate<TInput, TContext>,
32
- errorTransform: (error: unknown) => TError = (e) => {
33
- // Preserve object structure if TError is object-like
34
- if (typeof e === "object" && e !== null) return e as TError;
35
- // Default to string for primitives/errors
36
- return (e instanceof Error ? e.message : String(e)) as TError;
37
- },
38
- ): PredicateSafe<TInput, TError, TContext> => {
39
- return async (
40
- input: TInput,
41
- context?: TContext,
42
- ): Promise<PredicateResult<TError>> => {
43
- try {
44
- const result = await predicate(input, context);
45
-
46
- // Check if result is a boolean
47
- if (typeof result === "boolean") {
48
- return { status: "passed", value: result };
49
- }
50
-
51
- return {
52
- status: "failed",
53
- error: errorTransform(
54
- new Error(`Predicate must return boolean, got ${typeof result}`),
55
- ),
56
- };
57
- } catch (error) {
58
- return {
59
- status: "failed",
60
- error: errorTransform(error),
61
- };
62
- }
63
- };
64
- };
@@ -1,104 +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 type { Rule } from "../../types";
5
- import { withTap } from "./with-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 = withTap(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 = withTap(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 = withTap(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 = withTap(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 = withTap(effect2)(
66
- pipeRules([withTap(effect1)(rule1), rule2]),
67
- );
68
-
69
- await pipeline({});
70
- expect(effect1).toHaveBeenCalledWith({}, pass(), undefined);
71
- expect(effect2).toHaveBeenCalledWith({}, fail("Error"), undefined);
72
- });
73
-
74
- // Type safety tests
75
- it("should enforce input type matching", () => {
76
- type StrictInput = { id: string };
77
- const typedRule: Rule<StrictInput> = () => pass();
78
-
79
- // Valid usage
80
- withTap((input: StrictInput) => console.log(input.id))(typedRule);
81
-
82
- // @ts-expect-error - Should fail if effect expects wrong input type
83
- withTap((input: { other: number }) => {})(typedRule);
84
- });
85
-
86
- // Edge cases
87
- it("should handle null/undefined inputs", async () => {
88
- const effect = vi.fn();
89
- const rule = () => pass();
90
- const tappedRule = withTap(effect)(rule);
91
-
92
- await tappedRule(null as any);
93
- expect(effect).toHaveBeenCalledWith(null, pass(), undefined);
94
- });
95
-
96
- it("should handle effect returning Promise<void>", async () => {
97
- const asyncEffect = async () => {
98
- await Promise.resolve();
99
- };
100
- const tappedRule = withTap(asyncEffect)(mockRule);
101
-
102
- await expect(tappedRule({})).resolves.toEqual(pass());
103
- });
104
- });
@@ -1,46 +0,0 @@
1
- import { getNormalizedRule } from "../../helpers";
2
- import type { Rule, RuleResult, RuleSafetyOptions } from "../../types";
3
-
4
- /**
5
- * Creates a rule wrapper that performs side effects without modifying the result.
6
- * @template TInput - The type of the input to validate
7
- * @template TError - The type of the error (defaults to string)
8
- * @template TContext - The type of the context object (optional)
9
- * @param effect - Side effect function receiving input, result and context
10
- * @param options - Configuration for error handling safety
11
- * @param options.errorHandlingMode - Determines how errors are handled:
12
- * - 'safe': (default) Converts thrown errors to validation failures
13
- * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
14
- * @param options.errorTransform - Custom transformation for caught errors
15
- * @returns A function that wraps a rule with the tap effect
16
- * @example
17
- * const withLogging = tap((input, result) => {
18
- * console.log(`Validation result for ${input}:`, result);
19
- * });
20
- *
21
- * const rule = withLogging(validateInput);
22
- * @caveats
23
- * - Errors in the effect are caught and logged but don't affect rule execution
24
- * - Doesn't modify the rule's result
25
- */
26
- export const withTap = <TInput, TError = string, TContext = unknown>(
27
- effect: (
28
- input: TInput,
29
- result: RuleResult<TError>,
30
- context?: TContext,
31
- ) => Promise<void> | void,
32
- options?: RuleSafetyOptions<TError>,
33
- ): ((
34
- rule: Rule<TInput, TError, TContext>,
35
- ) => Rule<TInput, TError, TContext>) => {
36
- return (rule) => async (input, context) => {
37
- const safeRule = getNormalizedRule(rule, options);
38
- const result = await safeRule(input, context);
39
- try {
40
- await effect(input, result, context);
41
- } catch (error) {
42
- console.error("Tap effect failed:", error);
43
- }
44
- return result;
45
- };
46
- };
@@ -1,115 +0,0 @@
1
- import {
2
- describe,
3
- beforeAll,
4
- vi,
5
- afterEach,
6
- afterAll,
7
- it,
8
- expect,
9
- } from "vitest";
10
- import { pass, fail } from "../../helpers";
11
- import type { Rule } from "../../types";
12
- import { withTimeout } from "./with-timeout";
13
- import { getRuleError } from "../../../test/helpers/get-rule-error";
14
-
15
- describe("withTimeout", () => {
16
- beforeAll(() => {
17
- vi.useFakeTimers();
18
- });
19
-
20
- afterEach(() => {
21
- vi.clearAllTimers();
22
- });
23
-
24
- afterAll(() => {
25
- vi.useRealTimers();
26
- });
27
-
28
- // Mock rules
29
- const mockPassingRule: Rule<string> = vi.fn(() => Promise.resolve(pass()));
30
- const mockFailingRule: Rule<string> = vi.fn(() =>
31
- Promise.resolve(fail("Expected error")),
32
- );
33
- const createSlowRule = (delayMs: number): Rule<string> =>
34
- vi.fn(async () => {
35
- await new Promise((resolve) => setTimeout(resolve, delayMs));
36
- return pass();
37
- });
38
-
39
- it("should pass through immediate success", async () => {
40
- const rule = withTimeout(mockPassingRule, 100, "Timeout error");
41
- const resultPromise = rule("input");
42
-
43
- // Advance just enough to let microtasks run
44
- await Promise.resolve();
45
- vi.advanceTimersByTime(0);
46
-
47
- const result = await resultPromise;
48
- expect(result.status).toBe("passed");
49
- expect(mockPassingRule).toHaveBeenCalledWith("input", undefined);
50
- });
51
-
52
- it("should pass through immediate failure", async () => {
53
- const rule = withTimeout(mockFailingRule, 100, "Timeout error");
54
- const resultPromise = rule("input");
55
-
56
- await Promise.resolve();
57
- vi.advanceTimersByTime(0);
58
-
59
- const result = await resultPromise;
60
- expect(result.status).toBe("failed");
61
- expect(getRuleError(result)).toBe("Expected error");
62
- });
63
-
64
- it("should timeout when rule exceeds limit", async () => {
65
- const slowRule = createSlowRule(200);
66
- const rule = withTimeout(slowRule, 100, "Timeout exceeded");
67
-
68
- const resultPromise = rule("input");
69
- vi.advanceTimersByTime(100); // Trigger timeout
70
-
71
- const result = await resultPromise;
72
- expect(result.status).toBe("failed");
73
-
74
- expect(getRuleError(result)).toBe("Timeout exceeded");
75
- });
76
-
77
- it("should complete successfully if finished before timeout", async () => {
78
- const slowRule = createSlowRule(50);
79
- const rule = withTimeout(slowRule, 100, "Timeout error");
80
-
81
- const resultPromise = rule("input");
82
- vi.advanceTimersByTime(50); // Rule completes
83
-
84
- const result = await resultPromise;
85
- expect(result.status).toBe("passed");
86
- });
87
-
88
- it("should handle context correctly", async () => {
89
- const contextRule: Rule<string, string, { id: number }> = vi.fn(
90
- async (_, ctx) => (ctx?.id === 1 ? pass() : fail("Invalid context")),
91
- );
92
-
93
- const rule = withTimeout(contextRule, 100, "Timeout error");
94
- const resultPromise = rule("input", { id: 1 });
95
-
96
- await Promise.resolve();
97
- vi.advanceTimersByTime(0);
98
-
99
- const result = await resultPromise;
100
- expect(result.status).toBe("passed");
101
- expect(contextRule).toHaveBeenCalledWith("input", { id: 1 });
102
- });
103
-
104
- it("should work with immediate timeout (0ms)", async () => {
105
- const slowRule = createSlowRule(10);
106
- const rule = withTimeout(slowRule, 0, "Instant error");
107
-
108
- const resultPromise = rule("input");
109
- vi.advanceTimersByTime(0); // Trigger immediate timeout
110
-
111
- const result = await resultPromise;
112
- expect(result.status).toBe("failed");
113
- expect(getRuleError(result)).toBe("Instant error");
114
- });
115
- });
@@ -1,41 +0,0 @@
1
- import { fail, getNormalizedRule } from "../../helpers";
2
- import type { Rule, RuleResult, RuleSafetyOptions } from "../../types";
3
-
4
- /**
5
- * Wraps a rule with timeout functionality.
6
- * @template TInput - The type of the input to validate
7
- * @template TError - The type of the error
8
- * @template TContext - The type of the context object
9
- * @param rule - The rule to wrap with timeout
10
- * @param timeoutMs - Timeout duration in milliseconds
11
- * @param timeoutError - Error to return if timeout occurs
12
- * @param options - Configuration for error handling safety
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 rule that fails with timeoutError if execution takes longer than timeoutMs
18
- * @example
19
- * const rule = withTimeout(
20
- * slowNetworkRequestRule,
21
- * 5000, // 5 seconds
22
- * "Request timed out"
23
- * );
24
- * @caveats
25
- * - The original rule's execution isn't aborted when timeout occurs
26
- * - Only fails if the rule doesn't complete before timeout, not if it fails before timeout
27
- */
28
- export const withTimeout = <TInput, TError, TContext>(
29
- rule: Rule<TInput, TError, TContext>,
30
- timeoutMs: number,
31
- timeoutError: TError,
32
- options?: RuleSafetyOptions<TError>,
33
- ): Rule<TInput, TError, TContext> => {
34
- return async (input, context) => {
35
- const safeRule = getNormalizedRule(rule, options);
36
- const timeout = new Promise<RuleResult<TError>>((resolve) =>
37
- setTimeout(() => resolve(fail(timeoutError)), timeoutMs),
38
- );
39
- return Promise.race([safeRule(input, context), timeout]);
40
- };
41
- };