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.
- package/README.md +87 -14
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +148 -176
- package/dist/index.d.ts +148 -176
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +40 -43
- package/.editorconfig +0 -15
- package/.github/CONTRIBUTING.md +0 -3
- package/.github/ISSUE_TEMPLATE.md +0 -9
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
- package/.github/workflows/docs.yml +0 -29
- package/.github/workflows/publish.yml +0 -25
- package/.github/workflows/test.yml +0 -37
- package/.prettierignore +0 -2
- package/.releaserc +0 -11
- package/eslint.config.mjs +0 -84
- package/examples/financial-transaction.example.ts +0 -188
- package/examples/model-deployment.example.ts +0 -136
- package/examples/user-registration.example.ts +0 -101
- package/src/lib/combinators/index.ts +0 -2
- package/src/lib/combinators/logic/every.spec.ts +0 -264
- package/src/lib/combinators/logic/every.ts +0 -57
- package/src/lib/combinators/logic/if-else.spec.ts +0 -82
- package/src/lib/combinators/logic/if-else.ts +0 -64
- package/src/lib/combinators/logic/index.ts +0 -8
- package/src/lib/combinators/logic/match.spec.ts +0 -186
- package/src/lib/combinators/logic/match.ts +0 -106
- package/src/lib/combinators/logic/not.spec.ts +0 -64
- package/src/lib/combinators/logic/not.ts +0 -34
- package/src/lib/combinators/logic/one-of.spec.ts +0 -68
- package/src/lib/combinators/logic/one-of.ts +0 -48
- package/src/lib/combinators/logic/unless.spec.ts +0 -61
- package/src/lib/combinators/logic/unless.ts +0 -50
- package/src/lib/combinators/logic/when.spec.ts +0 -119
- package/src/lib/combinators/logic/when.ts +0 -50
- package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
- package/src/lib/combinators/logic/with-fallback.ts +0 -46
- package/src/lib/combinators/utility/index.ts +0 -11
- package/src/lib/combinators/utility/inject.spec.ts +0 -55
- package/src/lib/combinators/utility/inject.ts +0 -25
- package/src/lib/combinators/utility/map-error.spec.ts +0 -63
- package/src/lib/combinators/utility/map-error.ts +0 -35
- package/src/lib/combinators/utility/tap.spec.ts +0 -102
- package/src/lib/combinators/utility/tap.ts +0 -28
- package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
- package/src/lib/combinators/utility/validate-field.ts +0 -66
- package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
- package/src/lib/combinators/utility/with-debug.ts +0 -55
- package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
- package/src/lib/combinators/utility/with-memoize.ts +0 -89
- package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
- package/src/lib/combinators/utility/with-retry.ts +0 -70
- package/src/lib/combinators/utility/with-safe-error.spec.ts +0 -137
- package/src/lib/combinators/utility/with-safe-error.ts +0 -56
- package/src/lib/combinators/utility/with-safe-predicate.spec.ts +0 -176
- package/src/lib/combinators/utility/with-safe-predicate.ts +0 -64
- package/src/lib/combinators/utility/with-tap.spec.ts +0 -104
- package/src/lib/combinators/utility/with-tap.ts +0 -46
- package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
- package/src/lib/combinators/utility/with-timeout.ts +0 -41
- package/src/lib/composition/compose-rules.spec.ts +0 -211
- package/src/lib/composition/compose-rules.ts +0 -55
- package/src/lib/composition/index.ts +0 -3
- package/src/lib/composition/pipe-rules.spec.ts +0 -220
- package/src/lib/composition/pipe-rules.ts +0 -52
- package/src/lib/composition/pipe.spec.ts +0 -47
- package/src/lib/composition/pipe.ts +0 -107
- package/src/lib/helpers/clone/clone.ts +0 -12
- package/src/lib/helpers/clone/getCloneFn.ts +0 -17
- package/src/lib/helpers/clone/shallowClone.ts +0 -12
- package/src/lib/helpers/context/has-context.ts +0 -13
- package/src/lib/helpers/context/index.ts +0 -3
- package/src/lib/helpers/context/require-context.spec.ts +0 -55
- package/src/lib/helpers/context/require-context.ts +0 -61
- package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
- package/src/lib/helpers/context/with-lazy-context.ts +0 -35
- package/src/lib/helpers/index.ts +0 -8
- package/src/lib/helpers/result/fail.ts +0 -15
- package/src/lib/helpers/result/index.ts +0 -2
- package/src/lib/helpers/result/pass.ts +0 -14
- package/src/lib/helpers/retry/calculate-delay.ts +0 -31
- package/src/lib/helpers/safety/get-normalized-rule.spec.ts +0 -209
- package/src/lib/helpers/safety/get-normalized-rule.ts +0 -14
- package/src/lib/helpers/safety/get-normalized-rules.spec.ts +0 -138
- package/src/lib/helpers/safety/get-normalized-rules.ts +0 -14
- package/src/lib/index.ts +0 -4
- package/src/lib/types/composition-options.ts +0 -32
- package/src/lib/types/debug-options.ts +0 -36
- package/src/lib/types/index.ts +0 -8
- package/src/lib/types/predicate-result.ts +0 -20
- package/src/lib/types/predicate-safe.ts +0 -10
- package/src/lib/types/predicate-safety-options.ts +0 -27
- package/src/lib/types/predicate.ts +0 -8
- package/src/lib/types/prettify.ts +0 -3
- package/src/lib/types/rule-result.ts +0 -16
- package/src/lib/types/rule-safety-options.ts +0 -34
- package/src/lib/types/rule.ts +0 -21
- package/src/lib/types/safety-options.ts +0 -7
- package/src/test/financial-transaction.spec.ts +0 -251
- package/src/test/helpers/get-rule-error.ts +0 -23
- package/src/test/integration.spec.ts +0 -285
- package/src/test/model-deployment.spec.ts +0 -209
- package/src/test/user-registration.spec.ts +0 -164
- package/tsconfig.json +0 -56
- package/tsup.config.ts +0 -36
- package/typedoc/tsconfig.typedoc.json +0 -15
- package/typedoc/typedoc.json +0 -14
- package/vitest.config.ts +0 -16
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import type { 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
|
-
};
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import { describe, vi, beforeEach, it, expect } from "vitest";
|
|
2
|
-
import type { Rule } from "../../types";
|
|
3
|
-
import { withMemoize } from "./with-memoize";
|
|
4
|
-
import { pass } from "../../helpers";
|
|
5
|
-
|
|
6
|
-
describe("withMemoize", () => {
|
|
7
|
-
const mockRule = vi.fn(() => pass());
|
|
8
|
-
const keyFn = (input: { id: string }) => input.id;
|
|
9
|
-
|
|
10
|
-
beforeEach(() => {
|
|
11
|
-
vi.clearAllMocks();
|
|
12
|
-
mockRule.mockClear();
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
it("should cache results", async () => {
|
|
16
|
-
const memoized = withMemoize(mockRule, keyFn);
|
|
17
|
-
const input = { id: "123" };
|
|
18
|
-
|
|
19
|
-
await memoized(input);
|
|
20
|
-
await memoized(input);
|
|
21
|
-
|
|
22
|
-
expect(mockRule).toHaveBeenCalledTimes(1);
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
it("should distinguish different inputs", async () => {
|
|
26
|
-
const memoized = withMemoize(mockRule, keyFn);
|
|
27
|
-
|
|
28
|
-
await memoized({ id: "123" });
|
|
29
|
-
await memoized({ id: "456" });
|
|
30
|
-
|
|
31
|
-
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
it("should handle async rules", async () => {
|
|
35
|
-
const asyncRule = vi.fn(async () => {
|
|
36
|
-
await Promise.resolve();
|
|
37
|
-
return pass();
|
|
38
|
-
});
|
|
39
|
-
const memoized = withMemoize(asyncRule, keyFn);
|
|
40
|
-
|
|
41
|
-
await memoized({ id: "123" });
|
|
42
|
-
await memoized({ id: "123" });
|
|
43
|
-
|
|
44
|
-
expect(asyncRule).toHaveBeenCalledTimes(1);
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
it("should respect TTL", async () => {
|
|
48
|
-
vi.useFakeTimers();
|
|
49
|
-
const memoized = withMemoize(mockRule, keyFn, { ttl: 1000 });
|
|
50
|
-
|
|
51
|
-
await memoized({ id: "123" });
|
|
52
|
-
vi.advanceTimersByTime(1500);
|
|
53
|
-
await memoized({ id: "123" });
|
|
54
|
-
|
|
55
|
-
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
56
|
-
vi.useRealTimers();
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
it("should enforce max size", async () => {
|
|
60
|
-
const memoized = withMemoize(mockRule, keyFn, { maxSize: 2 });
|
|
61
|
-
|
|
62
|
-
await memoized({ id: "1" });
|
|
63
|
-
await memoized({ id: "2" });
|
|
64
|
-
await memoized({ id: "3" }); // Evicts '1'
|
|
65
|
-
await memoized({ id: "1" }); // Cache miss
|
|
66
|
-
|
|
67
|
-
expect(mockRule).toHaveBeenCalledTimes(4);
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
it("should maintain type safety", () => {
|
|
71
|
-
type StrictInput = { id: string };
|
|
72
|
-
const typedRule: Rule<StrictInput, string> = () => pass();
|
|
73
|
-
|
|
74
|
-
// Valid usage
|
|
75
|
-
withMemoize(typedRule, (input) => input.id);
|
|
76
|
-
|
|
77
|
-
// @ts-expect-error - Should fail if keyFn doesn't match input type
|
|
78
|
-
withMemoize(typedRule, (input: { other: number }) =>
|
|
79
|
-
input.other.toString(),
|
|
80
|
-
);
|
|
81
|
-
});
|
|
82
|
-
});
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { getNormalizedRule } from "../../helpers";
|
|
2
|
-
import type { Rule, RuleResult, RuleSafetyOptions } from "../../types";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Creates a memoized version of a rule that caches results based on input keys.
|
|
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 rule - The rule to memoize
|
|
10
|
-
* @param keyFn - Function that generates a cache key from the input
|
|
11
|
-
* @param options - Memoization and safety options
|
|
12
|
-
* @param options.ttl - Time-to-live for cache entries in milliseconds
|
|
13
|
-
* @param options.maxSize - Maximum number of entries to keep in cache
|
|
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 memoized version of the rule
|
|
19
|
-
* @example
|
|
20
|
-
* const memoizedRule = withMemoize(
|
|
21
|
-
* expensiveValidationRule,
|
|
22
|
-
* (input) => input.id,
|
|
23
|
-
* { ttl: 60000, maxSize: 100 }
|
|
24
|
-
* );
|
|
25
|
-
* @caveats
|
|
26
|
-
* - Context changes don't invalidate cache by default
|
|
27
|
-
* - Cache cleanup happens during rule execution
|
|
28
|
-
* - Rejected promises are automatically evicted from cache
|
|
29
|
-
* - Successful results obey TTL rules
|
|
30
|
-
* - Cache is shared across rule instances
|
|
31
|
-
*/
|
|
32
|
-
export const withMemoize = <TInput, TError = string, TContext = unknown>(
|
|
33
|
-
rule: Rule<TInput, TError, TContext>,
|
|
34
|
-
keyFn: (input: TInput) => string,
|
|
35
|
-
options: {
|
|
36
|
-
ttl?: number; // Milliseconds
|
|
37
|
-
maxSize?: number;
|
|
38
|
-
} & RuleSafetyOptions<TError> = {},
|
|
39
|
-
): Rule<TInput, TError, TContext> => {
|
|
40
|
-
const cache = new Map<
|
|
41
|
-
string,
|
|
42
|
-
{
|
|
43
|
-
result: Promise<RuleResult<TError>> | RuleResult<TError>;
|
|
44
|
-
timestamp: number;
|
|
45
|
-
}
|
|
46
|
-
>();
|
|
47
|
-
|
|
48
|
-
return async (input: TInput, context?: TContext) => {
|
|
49
|
-
const key = keyFn(input);
|
|
50
|
-
const now = Date.now();
|
|
51
|
-
|
|
52
|
-
// Cache cleanup
|
|
53
|
-
if (options.ttl) {
|
|
54
|
-
for (const [key, entry] of cache) {
|
|
55
|
-
if (now - entry.timestamp > options.ttl) {
|
|
56
|
-
cache.delete(key);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// Size management
|
|
62
|
-
if (options.maxSize && cache.size >= options.maxSize) {
|
|
63
|
-
const oldestKey = cache.keys().next().value;
|
|
64
|
-
if (oldestKey) {
|
|
65
|
-
cache.delete(oldestKey);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// Cache hit
|
|
70
|
-
if (cache.has(key)) {
|
|
71
|
-
return cache.get(key)!.result;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Cache miss
|
|
75
|
-
const normalizedRule = getNormalizedRule(rule, options);
|
|
76
|
-
const result = normalizedRule(input, context);
|
|
77
|
-
cache.set(key, {
|
|
78
|
-
result,
|
|
79
|
-
timestamp: now,
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
// Handle Promise cleanup if rejected
|
|
83
|
-
if (result instanceof Promise) {
|
|
84
|
-
result.catch(() => cache.delete(key));
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
return result;
|
|
88
|
-
};
|
|
89
|
-
};
|
|
@@ -1,220 +0,0 @@
|
|
|
1
|
-
import { describe, vi, beforeEach, it, expect, afterEach } from "vitest";
|
|
2
|
-
import { fail, pass } from "../../helpers";
|
|
3
|
-
import type { Rule } from "../../types";
|
|
4
|
-
import { withRetry } from "./with-retry";
|
|
5
|
-
|
|
6
|
-
describe("withRetry combinator", () => {
|
|
7
|
-
const successOnThirdTry = vi
|
|
8
|
-
.fn()
|
|
9
|
-
.mockImplementationOnce(() => fail("First error"))
|
|
10
|
-
.mockImplementationOnce(() => fail("Second error"))
|
|
11
|
-
.mockImplementationOnce(() => pass());
|
|
12
|
-
|
|
13
|
-
beforeEach(() => {
|
|
14
|
-
vi.clearAllMocks();
|
|
15
|
-
vi.useFakeTimers();
|
|
16
|
-
});
|
|
17
|
-
|
|
18
|
-
afterEach(() => {
|
|
19
|
-
vi.useRealTimers();
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
it("should succeed if rule eventually passes", async () => {
|
|
23
|
-
const rule = withRetry(successOnThirdTry, {
|
|
24
|
-
attempts: 3,
|
|
25
|
-
delayMs: 100,
|
|
26
|
-
retryStrategy: "fixed",
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
const resultPromise = rule({});
|
|
30
|
-
|
|
31
|
-
// Advance through all retries
|
|
32
|
-
await vi.advanceTimersByTimeAsync(300);
|
|
33
|
-
const result = await resultPromise;
|
|
34
|
-
|
|
35
|
-
expect(result).toEqual(pass());
|
|
36
|
-
expect(successOnThirdTry).toHaveBeenCalledTimes(3);
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
it("should apply exponential backoff strategy", async () => {
|
|
40
|
-
const mockRule = vi.fn(() => fail("Error"));
|
|
41
|
-
const rule = withRetry(mockRule, {
|
|
42
|
-
attempts: 3,
|
|
43
|
-
delayMs: 100,
|
|
44
|
-
retryStrategy: "exponential", // 100ms, 200ms, 400ms
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
const resultPromise = rule({});
|
|
48
|
-
|
|
49
|
-
// First attempt (no delay)
|
|
50
|
-
expect(mockRule).toHaveBeenCalledTimes(1);
|
|
51
|
-
|
|
52
|
-
// First retry after 100ms
|
|
53
|
-
await vi.advanceTimersByTimeAsync(100);
|
|
54
|
-
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
55
|
-
|
|
56
|
-
// Second retry after 200ms (total 300ms)
|
|
57
|
-
await vi.advanceTimersByTimeAsync(200);
|
|
58
|
-
expect(mockRule).toHaveBeenCalledTimes(3);
|
|
59
|
-
|
|
60
|
-
await vi.advanceTimersByTimeAsync(400);
|
|
61
|
-
const result = await resultPromise;
|
|
62
|
-
expect(result).toEqual(fail("MAX_RETRIES_EXCEEDED"));
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
it("should apply linear backoff strategy", async () => {
|
|
66
|
-
const mockRule = vi.fn(() => fail("Error"));
|
|
67
|
-
const rule = withRetry(mockRule, {
|
|
68
|
-
attempts: 3,
|
|
69
|
-
delayMs: 50,
|
|
70
|
-
retryStrategy: "linear", // 50ms, 100ms, 150ms
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
const resultPromise = rule({});
|
|
74
|
-
|
|
75
|
-
await vi.advanceTimersByTimeAsync(50);
|
|
76
|
-
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
77
|
-
|
|
78
|
-
await vi.advanceTimersByTimeAsync(100);
|
|
79
|
-
expect(mockRule).toHaveBeenCalledTimes(3);
|
|
80
|
-
|
|
81
|
-
await vi.advanceTimersByTimeAsync(150);
|
|
82
|
-
const result = await resultPromise;
|
|
83
|
-
expect(result.status).toBe("failed");
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
it("should use custom strategy function", async () => {
|
|
87
|
-
const mockRule = vi.fn(() => fail("Error"));
|
|
88
|
-
const customStrategy = vi.fn((attempt) => attempt * 25);
|
|
89
|
-
|
|
90
|
-
const rule = withRetry(mockRule, {
|
|
91
|
-
attempts: 3,
|
|
92
|
-
delayMs: 25,
|
|
93
|
-
retryStrategy: customStrategy,
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
const resultPromise = rule({});
|
|
97
|
-
|
|
98
|
-
// First attempt (no delay)
|
|
99
|
-
expect(mockRule).toHaveBeenCalledTimes(1);
|
|
100
|
-
|
|
101
|
-
// First retry after 25ms (attempt 1 * 25ms)
|
|
102
|
-
await vi.advanceTimersByTimeAsync(25);
|
|
103
|
-
expect(customStrategy).toHaveBeenCalledWith(1); // Only expect attempt number
|
|
104
|
-
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
105
|
-
|
|
106
|
-
// Second retry after 50ms (attempt 2 * 25ms)
|
|
107
|
-
await vi.advanceTimersByTimeAsync(50);
|
|
108
|
-
expect(customStrategy).toHaveBeenCalledWith(2);
|
|
109
|
-
expect(mockRule).toHaveBeenCalledTimes(3);
|
|
110
|
-
|
|
111
|
-
await vi.advanceTimersByTimeAsync(75);
|
|
112
|
-
const result = await resultPromise;
|
|
113
|
-
expect(result.status).toBe("failed");
|
|
114
|
-
expect(customStrategy).toHaveBeenCalledTimes(2); // Called for attempts 1 and 2
|
|
115
|
-
});
|
|
116
|
-
it("should fail after max attempts", async () => {
|
|
117
|
-
const alwaysFails = vi.fn(() => fail("Persistent error"));
|
|
118
|
-
const rule = withRetry(alwaysFails, {
|
|
119
|
-
attempts: 2,
|
|
120
|
-
delayMs: 10,
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
const resultPromise = rule({});
|
|
124
|
-
await vi.runAllTimersAsync();
|
|
125
|
-
const result = await resultPromise;
|
|
126
|
-
|
|
127
|
-
expect(result).toEqual(fail("MAX_RETRIES_EXCEEDED"));
|
|
128
|
-
expect(alwaysFails).toHaveBeenCalledTimes(2);
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
it("should use shouldRetry predicate", async () => {
|
|
132
|
-
const mockRule = vi
|
|
133
|
-
.fn()
|
|
134
|
-
.mockImplementationOnce(() => fail("First error"))
|
|
135
|
-
.mockImplementationOnce(() => fail("Second error"));
|
|
136
|
-
|
|
137
|
-
const shouldRetry = vi
|
|
138
|
-
.fn()
|
|
139
|
-
.mockReturnValueOnce(true) // Retry first error
|
|
140
|
-
.mockReturnValue(false); // Don't retry second
|
|
141
|
-
|
|
142
|
-
const rule = withRetry(mockRule, {
|
|
143
|
-
attempts: 3,
|
|
144
|
-
shouldRetry,
|
|
145
|
-
delayMs: 10,
|
|
146
|
-
retryStrategy: "fixed", // Explicit strategy for predictability
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
// Run the test without waiting for actual delays
|
|
150
|
-
vi.spyOn(global, "setTimeout").mockImplementation((fn) => fn() as any);
|
|
151
|
-
|
|
152
|
-
const result = await rule({});
|
|
153
|
-
|
|
154
|
-
expect(result).toEqual(fail("Second error"));
|
|
155
|
-
expect(shouldRetry).toHaveBeenCalledWith("First error", 1);
|
|
156
|
-
expect(mockRule).toHaveBeenCalledTimes(2);
|
|
157
|
-
|
|
158
|
-
// Clean up
|
|
159
|
-
vi.restoreAllMocks();
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
it("should pass context to each attempt", async () => {
|
|
163
|
-
const context = { userId: 123 };
|
|
164
|
-
const rule = withRetry(successOnThirdTry, {
|
|
165
|
-
attempts: 3,
|
|
166
|
-
delayMs: 10,
|
|
167
|
-
});
|
|
168
|
-
|
|
169
|
-
// Run the test without waiting for actual delays
|
|
170
|
-
vi.spyOn(global, "setTimeout").mockImplementation((fn) => fn() as any);
|
|
171
|
-
|
|
172
|
-
await rule({}, context);
|
|
173
|
-
|
|
174
|
-
expect(successOnThirdTry).toHaveBeenCalledWith({}, context);
|
|
175
|
-
});
|
|
176
|
-
|
|
177
|
-
it("should handle thrown errors", async () => {
|
|
178
|
-
const errorRule = vi
|
|
179
|
-
.fn()
|
|
180
|
-
.mockRejectedValueOnce(new Error("Network error"))
|
|
181
|
-
.mockResolvedValueOnce(pass());
|
|
182
|
-
|
|
183
|
-
const rule = withRetry(errorRule, {
|
|
184
|
-
attempts: 2,
|
|
185
|
-
shouldRetry: (e) => (e as Error).message === "Network error",
|
|
186
|
-
});
|
|
187
|
-
|
|
188
|
-
// Run the test without waiting for actual delays
|
|
189
|
-
vi.spyOn(global, "setTimeout").mockImplementation((fn) => fn() as any);
|
|
190
|
-
|
|
191
|
-
const result = await rule({});
|
|
192
|
-
expect(result).toEqual(pass());
|
|
193
|
-
});
|
|
194
|
-
|
|
195
|
-
it("should fail on non-retryable thrown errors", async () => {
|
|
196
|
-
const errorRule = vi.fn().mockRejectedValue(new Error("Fatal"));
|
|
197
|
-
|
|
198
|
-
const rule = withRetry(errorRule, {
|
|
199
|
-
shouldRetry: (e) => (e as Error).message !== "Fatal",
|
|
200
|
-
});
|
|
201
|
-
|
|
202
|
-
const result = await rule({});
|
|
203
|
-
expect(result.status).toBe("failed");
|
|
204
|
-
expect((result as any).error.message).toBe("Fatal");
|
|
205
|
-
});
|
|
206
|
-
|
|
207
|
-
// Type safety tests
|
|
208
|
-
it("should preserve input types", () => {
|
|
209
|
-
type StrictInput = { id: string };
|
|
210
|
-
const typedRule: Rule<StrictInput, string> = () => pass();
|
|
211
|
-
|
|
212
|
-
// Valid usage
|
|
213
|
-
withRetry(typedRule, { attempts: 2 });
|
|
214
|
-
|
|
215
|
-
withRetry((_: { other: number }) => pass(), { attempts: 2 })({
|
|
216
|
-
// @ts-expect-error - Should fail if input types mismatch
|
|
217
|
-
id: "123",
|
|
218
|
-
});
|
|
219
|
-
});
|
|
220
|
-
});
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { calculateDelay, fail } from "../../helpers";
|
|
2
|
-
import type { Rule } from "../../types";
|
|
3
|
-
|
|
4
|
-
export type RetryStrategy =
|
|
5
|
-
| "fixed"
|
|
6
|
-
| "linear"
|
|
7
|
-
| "exponential"
|
|
8
|
-
| ((attempt: number) => number);
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Wraps a rule with retry logic for handling transient failures.
|
|
12
|
-
* @template TInput - The type of the input to validate
|
|
13
|
-
* @template TError - The type of the error (defaults to string)
|
|
14
|
-
* @template TContext - The type of the context object (optional)
|
|
15
|
-
* @param rule - The rule to wrap with retry logic
|
|
16
|
-
* @param options - Retry configuration
|
|
17
|
-
* @param options.attempts - Maximum number of attempts (default: 3)
|
|
18
|
-
* @param options.delayMs - Delay between attempts in milliseconds (default: 100)
|
|
19
|
-
* @param options.shouldRetry - Function to determine if a failure should be retried
|
|
20
|
-
* @returns A new rule with retry capability
|
|
21
|
-
* @example
|
|
22
|
-
* const rule = withRetry(apiCheckRule, {
|
|
23
|
-
* attempts: 5,
|
|
24
|
-
* delayMs: 500,
|
|
25
|
-
* shouldRetry: (error) => error.statusCode === 503
|
|
26
|
-
* });
|
|
27
|
-
* @caveats
|
|
28
|
-
* - Only retries on failed RuleResults, not on thrown exceptions
|
|
29
|
-
* - The final error will be "MAX_RETRIES_EXCEEDED" if all attempts fail
|
|
30
|
-
*/
|
|
31
|
-
export const withRetry = <TInput, TError = string, TContext = unknown>(
|
|
32
|
-
rule: Rule<TInput, TError, TContext>,
|
|
33
|
-
options: {
|
|
34
|
-
attempts?: number;
|
|
35
|
-
delayMs?: number;
|
|
36
|
-
retryStrategy?: RetryStrategy;
|
|
37
|
-
shouldRetry?: (error: TError | unknown, attempt: number) => boolean;
|
|
38
|
-
} = {},
|
|
39
|
-
): Rule<TInput, TError | "MAX_RETRIES_EXCEEDED", TContext> => {
|
|
40
|
-
const { attempts = 3, delayMs = 100, shouldRetry = () => true } = options;
|
|
41
|
-
|
|
42
|
-
return async (input, context) => {
|
|
43
|
-
let lastError: TError | unknown;
|
|
44
|
-
|
|
45
|
-
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
46
|
-
try {
|
|
47
|
-
const result = await rule(input, context);
|
|
48
|
-
if (result.status === "passed") {
|
|
49
|
-
return result;
|
|
50
|
-
}
|
|
51
|
-
lastError = result.error;
|
|
52
|
-
} catch (error) {
|
|
53
|
-
lastError = error;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// Check if we should retry the last error
|
|
57
|
-
if (!shouldRetry(lastError as TError, attempt)) {
|
|
58
|
-
return fail(lastError as TError);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// Delay if not the last attempt
|
|
62
|
-
if (attempt < attempts && delayMs > 0) {
|
|
63
|
-
const delay = calculateDelay(options?.retryStrategy, attempt, delayMs);
|
|
64
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
return fail("MAX_RETRIES_EXCEEDED" as const);
|
|
69
|
-
};
|
|
70
|
-
};
|
|
@@ -1,137 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
-
import { withSafeError } from "./with-safe-error";
|
|
3
|
-
import { pass, fail } from "../../helpers";
|
|
4
|
-
import type { Rule, RuleResult } from "../../types";
|
|
5
|
-
|
|
6
|
-
describe("withSafeError", () => {
|
|
7
|
-
// Mock rules for testing
|
|
8
|
-
const passingRule = vi.fn(() => pass());
|
|
9
|
-
const failingRule = vi.fn(() => fail("Expected error"));
|
|
10
|
-
const errorThrowingRule = vi.fn(() => {
|
|
11
|
-
throw new Error("Boom!");
|
|
12
|
-
});
|
|
13
|
-
const stringThrowingRule = vi.fn(() => {
|
|
14
|
-
throw "Just a string error";
|
|
15
|
-
});
|
|
16
|
-
const objectThrowingRule = vi.fn(() => {
|
|
17
|
-
throw { code: 500, message: "Custom error" };
|
|
18
|
-
});
|
|
19
|
-
const invalidRule = vi.fn(() => "not a RuleResult" as unknown as RuleResult);
|
|
20
|
-
|
|
21
|
-
beforeEach(() => {
|
|
22
|
-
vi.clearAllMocks();
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
// 1. Basic functionality tests
|
|
26
|
-
it("should pass through successful results unchanged", async () => {
|
|
27
|
-
const safeRule = withSafeError(passingRule);
|
|
28
|
-
const result = await safeRule({});
|
|
29
|
-
expect(result).toEqual(pass());
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
it("should pass through failed results unchanged", async () => {
|
|
33
|
-
const safeRule = withSafeError(failingRule);
|
|
34
|
-
const result = await safeRule({});
|
|
35
|
-
expect(result).toEqual(fail("Expected error"));
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
// 2. Error handling tests
|
|
39
|
-
it("should catch Error objects and use their message", async () => {
|
|
40
|
-
const safeRule = withSafeError(errorThrowingRule);
|
|
41
|
-
const result = await safeRule({});
|
|
42
|
-
expect(result).toEqual(fail(new Error("Boom!")));
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
it("should catch string errors and preserve them", async () => {
|
|
46
|
-
const safeRule = withSafeError(stringThrowingRule);
|
|
47
|
-
const result = await safeRule({});
|
|
48
|
-
expect(result).toEqual(fail("Just a string error"));
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
it("should preserve object error structure", async () => {
|
|
52
|
-
const safeRule = withSafeError(objectThrowingRule);
|
|
53
|
-
const result = await safeRule({});
|
|
54
|
-
expect(result).toEqual(fail({ code: 500, message: "Custom error" }));
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
// 3. Invalid rule behavior tests
|
|
58
|
-
it("should handle rules that return invalid results", async () => {
|
|
59
|
-
const safeRule = withSafeError(invalidRule);
|
|
60
|
-
const result = await safeRule({});
|
|
61
|
-
expect(result.status).toBe("failed");
|
|
62
|
-
expect((result as any).error).toEqual(
|
|
63
|
-
new Error("Invalid rule - did not return RuleResult"),
|
|
64
|
-
);
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
// 4. Custom error transformation tests
|
|
68
|
-
it("should use custom error transformation when provided", async () => {
|
|
69
|
-
const customTransform = vi.fn((error: unknown) => ({
|
|
70
|
-
code: 500,
|
|
71
|
-
message: String(error),
|
|
72
|
-
}));
|
|
73
|
-
|
|
74
|
-
const safeRule = withSafeError(errorThrowingRule, customTransform);
|
|
75
|
-
const result = await safeRule({});
|
|
76
|
-
|
|
77
|
-
expect(result).toEqual(
|
|
78
|
-
fail({
|
|
79
|
-
code: 500,
|
|
80
|
-
message: "Error: Boom!",
|
|
81
|
-
}),
|
|
82
|
-
);
|
|
83
|
-
expect(customTransform).toHaveBeenCalledWith(expect.any(Error));
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
// 5. Type safety tests
|
|
87
|
-
it("should preserve custom error types when specified", async () => {
|
|
88
|
-
interface CustomError {
|
|
89
|
-
code: number;
|
|
90
|
-
details: string;
|
|
91
|
-
}
|
|
92
|
-
const customError: CustomError = {
|
|
93
|
-
code: 400,
|
|
94
|
-
details: "Validation failed",
|
|
95
|
-
};
|
|
96
|
-
|
|
97
|
-
const customErrorRule: Rule<number, CustomError> = () => {
|
|
98
|
-
throw customError;
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
const safeRule = withSafeError<number, CustomError>(customErrorRule);
|
|
102
|
-
const result = await safeRule(123);
|
|
103
|
-
|
|
104
|
-
expect(result).toEqual(fail(customError));
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
// 6. Context handling tests
|
|
108
|
-
it("should pass context to the wrapped rule", async () => {
|
|
109
|
-
const context = { userId: 123 };
|
|
110
|
-
const contextAwareRule = vi.fn((_: unknown, ctx: any) =>
|
|
111
|
-
ctx?.userId === 123 ? pass() : fail("Wrong user"),
|
|
112
|
-
);
|
|
113
|
-
|
|
114
|
-
const safeRule = withSafeError(contextAwareRule);
|
|
115
|
-
await safeRule({}, context);
|
|
116
|
-
expect(contextAwareRule).toHaveBeenCalledWith({}, context);
|
|
117
|
-
});
|
|
118
|
-
|
|
119
|
-
// 7. Async behavior tests
|
|
120
|
-
it("should handle async rules that throw", async () => {
|
|
121
|
-
const asyncErrorRule = vi.fn(async () => {
|
|
122
|
-
await Promise.resolve();
|
|
123
|
-
throw new Error("Async boom!");
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
const safeRule = withSafeError(asyncErrorRule);
|
|
127
|
-
const result = await safeRule({});
|
|
128
|
-
expect(result).toEqual(fail(new Error("Async boom!")));
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
// 8. Edge case tests
|
|
132
|
-
it("should handle null/undefined input safely", async () => {
|
|
133
|
-
const safeRule = withSafeError(passingRule);
|
|
134
|
-
await expect(safeRule(null as any)).resolves.not.toThrow();
|
|
135
|
-
await expect(safeRule(undefined as any)).resolves.not.toThrow();
|
|
136
|
-
});
|
|
137
|
-
});
|