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.
- package/package.json +7 -1
- 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,106 +0,0 @@
|
|
|
1
|
-
import { fail, getNormalizedRule } from "../../helpers";
|
|
2
|
-
import type { Rule, RuleResult, RuleSafetyOptions } from "../../types";
|
|
3
|
-
|
|
4
|
-
const isRule = <TInput, TError, TContext>(
|
|
5
|
-
value: unknown,
|
|
6
|
-
): value is Rule<TInput, TError, TContext> => {
|
|
7
|
-
return typeof value === "function";
|
|
8
|
-
};
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Pattern-matching combinator that selects a rule based on a key extracted from input.
|
|
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
|
-
* @template TKey - The type of the branch key (must be string | number | symbol)
|
|
16
|
-
* @param accessor - Function that extracts the match key from input
|
|
17
|
-
* @param cases - Object mapping keys to their corresponding rules
|
|
18
|
-
* @param defaultCase - Optional default rule or error when no match is found
|
|
19
|
-
* @param options - Configuration for error handling safety
|
|
20
|
-
* @param options.errorHandlingMode - Determines how errors are handled:
|
|
21
|
-
* - 'safe': (default) Converts thrown errors to validation failures
|
|
22
|
-
* - 'unsafe': Lets errors propagate (use only in performance-critical paths)
|
|
23
|
-
* @param options.errorTransform - Custom transformation for caught errors
|
|
24
|
-
* @returns A new rule that executes the matching case's rule
|
|
25
|
-
* @example
|
|
26
|
-
* // Basic usage with string error type
|
|
27
|
-
* const validatePayment = match(
|
|
28
|
-
* (order) => order.paymentMethod,
|
|
29
|
-
* {
|
|
30
|
-
* credit: validateCreditCard,
|
|
31
|
-
* paypal: validatePayPal,
|
|
32
|
-
* crypto: validateCrypto
|
|
33
|
-
* },
|
|
34
|
-
* "Unsupported payment method"
|
|
35
|
-
* );
|
|
36
|
-
*
|
|
37
|
-
* @example
|
|
38
|
-
* // With custom error type
|
|
39
|
-
* interface ValidationError { code: number; message: string }
|
|
40
|
-
* const validateStatus = match<Order, ValidationError>(
|
|
41
|
-
* (order) => order.status,
|
|
42
|
-
* {
|
|
43
|
-
* pending: validatePendingOrder,
|
|
44
|
-
* completed: validateCompletedOrder
|
|
45
|
-
* },
|
|
46
|
-
* { code: 400, message: "Invalid status" }
|
|
47
|
-
* );
|
|
48
|
-
*
|
|
49
|
-
* @example
|
|
50
|
-
* // With default rule instead of error
|
|
51
|
-
* const validateProduct = match(
|
|
52
|
-
* (product) => product.type,
|
|
53
|
-
* {
|
|
54
|
-
* book: validateBook,
|
|
55
|
-
* digital: validateDigitalProduct
|
|
56
|
-
* },
|
|
57
|
-
* validateGenericProduct
|
|
58
|
-
* );
|
|
59
|
-
*
|
|
60
|
-
* @caveats
|
|
61
|
-
* - The accessor function should return a primitive value (string/number/symbol)
|
|
62
|
-
* - If no matching case is found and no default is provided, returns a failed result with:
|
|
63
|
-
* - A string error when TError is string (default)
|
|
64
|
-
* - A type-asserted error when TError is custom (may require type casting)
|
|
65
|
-
* - All case rules must have compatible input/context types
|
|
66
|
-
* - For conditional branching (true/false), consider using `branch` instead
|
|
67
|
-
*/
|
|
68
|
-
export const match = <
|
|
69
|
-
TInput,
|
|
70
|
-
TError = string,
|
|
71
|
-
TContext = unknown,
|
|
72
|
-
TKey extends string | number | symbol = string,
|
|
73
|
-
>(
|
|
74
|
-
accessor: (input: TInput, context?: TContext) => TKey | Promise<TKey>,
|
|
75
|
-
cases: Record<TKey, Rule<TInput, TError, TContext>>,
|
|
76
|
-
defaultCase?: Rule<TInput, TError, TContext> | TError,
|
|
77
|
-
options?: RuleSafetyOptions<TError>,
|
|
78
|
-
): Rule<TInput, TError, TContext> => {
|
|
79
|
-
return async (
|
|
80
|
-
input: TInput,
|
|
81
|
-
context?: TContext,
|
|
82
|
-
): Promise<RuleResult<TError>> => {
|
|
83
|
-
const key = await accessor(input, context);
|
|
84
|
-
const matchedRule = cases[key];
|
|
85
|
-
|
|
86
|
-
if (matchedRule) {
|
|
87
|
-
const safeMatchedRule = getNormalizedRule(matchedRule, options);
|
|
88
|
-
return safeMatchedRule(input, context);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
if (defaultCase !== undefined) {
|
|
92
|
-
// if default case is not a rule, fail the error/messae directly
|
|
93
|
-
if (!isRule<TInput, TError, TContext>(defaultCase)) {
|
|
94
|
-
return fail(defaultCase);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const safeDefaultCase = getNormalizedRule(
|
|
98
|
-
defaultCase as Rule<TInput, TError, TContext>,
|
|
99
|
-
options,
|
|
100
|
-
);
|
|
101
|
-
return safeDefaultCase(input, context);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
return fail(`No matching rule for key: ${String(key)}` as TError);
|
|
105
|
-
};
|
|
106
|
-
};
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
-
import { fail, pass } from "../../helpers";
|
|
3
|
-
import { not } from "./not";
|
|
4
|
-
|
|
5
|
-
describe("not combinator", () => {
|
|
6
|
-
const mockRule = vi.fn(() => pass());
|
|
7
|
-
const errorMsg = "Inverted error";
|
|
8
|
-
|
|
9
|
-
beforeEach(() => {
|
|
10
|
-
vi.clearAllMocks();
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
it("should invert pass to fail", async () => {
|
|
14
|
-
const invertedRule = not(mockRule, errorMsg);
|
|
15
|
-
const result = await invertedRule({});
|
|
16
|
-
|
|
17
|
-
expect(result).toEqual(fail(errorMsg));
|
|
18
|
-
expect(mockRule).toHaveBeenCalled();
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
it("should invert fail to pass", async () => {
|
|
22
|
-
const failingRule = vi.fn(() => fail("Original error"));
|
|
23
|
-
const invertedRule = not(failingRule, errorMsg);
|
|
24
|
-
const result = await invertedRule({});
|
|
25
|
-
|
|
26
|
-
expect(result).toEqual(pass());
|
|
27
|
-
expect(failingRule).toHaveBeenCalled();
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
it("should preserve context", async () => {
|
|
31
|
-
const context = { userId: 123 };
|
|
32
|
-
const contextAwareRule = vi.fn((_, ctx) =>
|
|
33
|
-
ctx?.userId === 123 ? pass() : fail("Wrong user"),
|
|
34
|
-
);
|
|
35
|
-
|
|
36
|
-
const invertedRule = not(contextAwareRule, errorMsg);
|
|
37
|
-
await invertedRule({}, context);
|
|
38
|
-
|
|
39
|
-
expect(contextAwareRule).toHaveBeenCalledWith({}, context);
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
it("should handle async rules", async () => {
|
|
43
|
-
const asyncRule = vi.fn(async () => {
|
|
44
|
-
await Promise.resolve();
|
|
45
|
-
return pass();
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
const invertedRule = not(asyncRule, errorMsg);
|
|
49
|
-
const result = await invertedRule({});
|
|
50
|
-
|
|
51
|
-
expect(result).toEqual(fail(errorMsg));
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
it("should propagate rule errors", async () => {
|
|
55
|
-
const errorRule = vi.fn(() => {
|
|
56
|
-
throw new Error("Boom!");
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
const invertedRule = not(errorRule, errorMsg, {
|
|
60
|
-
errorHandlingMode: "unsafe",
|
|
61
|
-
});
|
|
62
|
-
await expect(invertedRule({})).rejects.toThrow("Boom!");
|
|
63
|
-
});
|
|
64
|
-
});
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { pass, fail, getNormalizedRule } from "../../helpers";
|
|
2
|
-
import type { RuleSafetyOptions } from "../../types";
|
|
3
|
-
import type { Rule } from "../../types/rule";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Inverts the logic of a rule - passes when original fails and vice versa.
|
|
7
|
-
* @template TInput - The type of the input to validate
|
|
8
|
-
* @template TError - The type of the error (defaults to string)
|
|
9
|
-
* @param rule - The rule to invert
|
|
10
|
-
* @param error - The error to return when original rule passes
|
|
11
|
-
* @param options - Configuration for error handling safety
|
|
12
|
-
* @param options.errorHandlingMode - Determines how errors are handled:
|
|
13
|
-
* - 'safe': (default) Converts thrown errors to validation failures
|
|
14
|
-
* - 'unsafe': Lets errors propagate (use only in performance-critical paths)
|
|
15
|
-
* @param options.errorTransform - Custom transformation for caught errors
|
|
16
|
-
* @returns A new rule with inverted logic
|
|
17
|
-
* @example
|
|
18
|
-
* const isNotAdmin = not(isAdmin, "User must not be admin");
|
|
19
|
-
* @caveats
|
|
20
|
-
* - The original rule's error is discarded when it fails
|
|
21
|
-
* - Always uses the provided error when original passes
|
|
22
|
-
*/
|
|
23
|
-
export const not = <TInput, TError = string>(
|
|
24
|
-
rule: Rule<TInput, TError>,
|
|
25
|
-
error: TError,
|
|
26
|
-
options?: RuleSafetyOptions<TError>,
|
|
27
|
-
): Rule<TInput, TError> => {
|
|
28
|
-
return async (input: TInput, context?: unknown) => {
|
|
29
|
-
const normalizedRule = getNormalizedRule(rule, options);
|
|
30
|
-
|
|
31
|
-
const result = await normalizedRule(input, context);
|
|
32
|
-
return result.status === "passed" ? fail(error) : pass();
|
|
33
|
-
};
|
|
34
|
-
};
|
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import { describe, beforeEach, it, expect, vi } from "vitest";
|
|
2
|
-
import { fail, pass } from "../../helpers";
|
|
3
|
-
import type { Rule } from "../../types";
|
|
4
|
-
import { oneOf } from "./one-of";
|
|
5
|
-
|
|
6
|
-
describe("oneOf combinator", () => {
|
|
7
|
-
const passingRule = vi.fn(() => pass());
|
|
8
|
-
const failingRule1 = vi.fn(() => fail("Error 1"));
|
|
9
|
-
const failingRule2 = vi.fn(() => fail("Error 2"));
|
|
10
|
-
|
|
11
|
-
beforeEach(() => {
|
|
12
|
-
vi.clearAllMocks();
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
it("should pass if any rule passes", async () => {
|
|
16
|
-
const validator = oneOf([failingRule1, passingRule, failingRule2]);
|
|
17
|
-
const result = await validator({});
|
|
18
|
-
|
|
19
|
-
expect(result).toEqual(pass());
|
|
20
|
-
expect(failingRule1).toHaveBeenCalled();
|
|
21
|
-
expect(passingRule).toHaveBeenCalled();
|
|
22
|
-
expect(failingRule2).not.toHaveBeenCalled(); // Short-circuits
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
it("should fail with all errors if no rules pass", async () => {
|
|
26
|
-
const validator = oneOf([failingRule1, failingRule2]);
|
|
27
|
-
const result = await validator({});
|
|
28
|
-
|
|
29
|
-
expect(result).toEqual(fail(["Error 1", "Error 2"]));
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
it("should handle empty rules array", async () => {
|
|
33
|
-
const validator = oneOf([]);
|
|
34
|
-
const result = await validator({});
|
|
35
|
-
|
|
36
|
-
expect(result).toEqual(pass()); // Vacuous truth
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
it("should pass context to all rules", async () => {
|
|
40
|
-
const context = { userId: 123 };
|
|
41
|
-
const rule = vi.fn(() => pass());
|
|
42
|
-
|
|
43
|
-
await oneOf([rule])({}, context);
|
|
44
|
-
expect(rule).toHaveBeenCalledWith({}, context);
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
it("should work with async rules", async () => {
|
|
48
|
-
const asyncRule = vi.fn(async () => {
|
|
49
|
-
await Promise.resolve();
|
|
50
|
-
return pass();
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
const result = await oneOf([asyncRule])({});
|
|
54
|
-
expect(result).toEqual(pass());
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
// Type safety tests
|
|
58
|
-
it("should enforce rule type matching", () => {
|
|
59
|
-
type StrictInput = { id: string };
|
|
60
|
-
const typedRule: Rule<StrictInput, string> = () => pass();
|
|
61
|
-
|
|
62
|
-
// Valid usage
|
|
63
|
-
oneOf([typedRule, () => fail("Error")]);
|
|
64
|
-
|
|
65
|
-
// @ts-expect-error - Should fail if input types mismatch
|
|
66
|
-
oneOf(typedRule, (input: { other: number }) => pass());
|
|
67
|
-
});
|
|
68
|
-
});
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { fail, getNormalizedRules, pass } from "../../helpers";
|
|
2
|
-
import type { Rule, RuleSafetyOptions } from "../../types";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Creates a rule that passes if any of the provided rules pass (short-circuiting).
|
|
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 rules - Rules to try (in order)
|
|
10
|
-
* @param options - Configuration for error handling
|
|
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 rule that passes if any rule passes, or fails with all errors
|
|
16
|
-
* @example
|
|
17
|
-
* const rule = oneOf(
|
|
18
|
-
* validateEmail,
|
|
19
|
-
* validatePhone,
|
|
20
|
-
* validateUsername
|
|
21
|
-
* );
|
|
22
|
-
* @caveats
|
|
23
|
-
* - Rules are executed in sequence until one passes
|
|
24
|
-
* - Returns all errors if all rules fail
|
|
25
|
-
*/
|
|
26
|
-
export const oneOf = <TInput, TError = string, TContext = unknown>(
|
|
27
|
-
rules: Rule<TInput, TError, TContext>[],
|
|
28
|
-
options?: RuleSafetyOptions<TError>,
|
|
29
|
-
): Rule<TInput, TError[], TContext> => {
|
|
30
|
-
return async (input: TInput, context?: TContext) => {
|
|
31
|
-
const normalizedRules = getNormalizedRules(rules, options);
|
|
32
|
-
const errors: TError[] = [];
|
|
33
|
-
|
|
34
|
-
if (!rules || rules.length === 0) {
|
|
35
|
-
return pass();
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
for (const rule of normalizedRules) {
|
|
39
|
-
const result = await rule(input, context);
|
|
40
|
-
if (result.status === "passed") {
|
|
41
|
-
return pass();
|
|
42
|
-
}
|
|
43
|
-
errors.push(result.error);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
return fail(errors);
|
|
47
|
-
};
|
|
48
|
-
};
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import { describe, vi, beforeEach, it, expect } from "vitest";
|
|
2
|
-
import { fail, pass } from "../../helpers";
|
|
3
|
-
import type { Rule } from "../../types";
|
|
4
|
-
import { unless } from "./unless";
|
|
5
|
-
|
|
6
|
-
describe("unless combinator", () => {
|
|
7
|
-
const mockRule = vi.fn(() => fail("Rule executed"));
|
|
8
|
-
const isAdmin = (input: { role: string }) => input.role === "admin";
|
|
9
|
-
|
|
10
|
-
beforeEach(() => {
|
|
11
|
-
vi.clearAllMocks();
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
it("should skip rule when predicate is true", async () => {
|
|
15
|
-
const validateUnlessAdmin = unless(isAdmin, mockRule);
|
|
16
|
-
const result = await validateUnlessAdmin({ role: "admin" });
|
|
17
|
-
|
|
18
|
-
expect(result).toEqual(pass());
|
|
19
|
-
expect(mockRule).not.toHaveBeenCalled();
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
it("should run rule when predicate is false", async () => {
|
|
23
|
-
const validateUnlessAdmin = unless(isAdmin, mockRule);
|
|
24
|
-
const result = await validateUnlessAdmin({ role: "user" });
|
|
25
|
-
|
|
26
|
-
expect(result).toEqual(fail("Rule executed"));
|
|
27
|
-
expect(mockRule).toHaveBeenCalled();
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
it("should pass context to the rule", async () => {
|
|
31
|
-
const context = { logger: console };
|
|
32
|
-
const rule = vi.fn(() => pass());
|
|
33
|
-
const validator = unless(() => false, rule);
|
|
34
|
-
|
|
35
|
-
await validator({}, context);
|
|
36
|
-
expect(rule).toHaveBeenCalledWith({}, context);
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
it("should handle async predicates", async () => {
|
|
40
|
-
const asyncPredicate = async (input: { id: number }) => {
|
|
41
|
-
await Promise.resolve();
|
|
42
|
-
return input.id > 10;
|
|
43
|
-
};
|
|
44
|
-
const validator = unless(asyncPredicate, mockRule);
|
|
45
|
-
|
|
46
|
-
await validator({ id: 5 });
|
|
47
|
-
expect(mockRule).toHaveBeenCalled();
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
// Type safety tests
|
|
51
|
-
it("should enforce predicate input type", () => {
|
|
52
|
-
type StrictInput = { id: string };
|
|
53
|
-
const typedRule: Rule<StrictInput> = () => pass();
|
|
54
|
-
|
|
55
|
-
// Valid usage
|
|
56
|
-
unless((input: StrictInput) => !!input.id, typedRule);
|
|
57
|
-
|
|
58
|
-
// @ts-expect-error - Should fail if predicate expects wrong type
|
|
59
|
-
unless((input: { other: number }) => true, typedRule);
|
|
60
|
-
});
|
|
61
|
-
});
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { fail, getNormalizedRule, pass } from "../../helpers";
|
|
2
|
-
import type { Predicate, Rule } from "../../types";
|
|
3
|
-
import type { SafetyOptions } from "../../types/safety-options";
|
|
4
|
-
import { withSafePredicate } from "../utility";
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Executes a rule only if the predicate returns false.
|
|
8
|
-
* @template TInput - The type of the input to validate
|
|
9
|
-
* @template TError - The type of the error (defaults to string)
|
|
10
|
-
* @template TContext - The type of the context object (optional)
|
|
11
|
-
* @param predicate - Condition to check
|
|
12
|
-
* @param rule - Rule to execute when predicate is false
|
|
13
|
-
* @param options - Configuration for error handling and predicate 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
|
-
* @param options.predicateErrorTransform - Special error handler for predicate failures
|
|
19
|
-
* @returns A rule that conditionally executes based on the predicate
|
|
20
|
-
* @example
|
|
21
|
-
* const rule = unless(
|
|
22
|
-
* (user) => user.isVerified,
|
|
23
|
-
* requireVerification
|
|
24
|
-
* );
|
|
25
|
-
* @caveats
|
|
26
|
-
* - Opposite behavior of `when`
|
|
27
|
-
* - Automatically passes when predicate is true
|
|
28
|
-
*/
|
|
29
|
-
export const unless = <TInput, TError = string, TContext = unknown>(
|
|
30
|
-
predicate: Predicate<TInput, TContext>,
|
|
31
|
-
rule: Rule<TInput, TError, TContext>,
|
|
32
|
-
options?: SafetyOptions<TError>,
|
|
33
|
-
): Rule<TInput, TError, TContext> => {
|
|
34
|
-
return async (input: TInput, context?: TContext) => {
|
|
35
|
-
const normalizedRule = getNormalizedRule(rule, options);
|
|
36
|
-
const safePredicate = withSafePredicate<TInput, TError, TContext>(
|
|
37
|
-
predicate,
|
|
38
|
-
options?.predicateErrorTransform,
|
|
39
|
-
);
|
|
40
|
-
|
|
41
|
-
const safePredicateResult = await safePredicate(input, context);
|
|
42
|
-
|
|
43
|
-
// Predicate fail to run or returned invalid result
|
|
44
|
-
if (safePredicateResult.status === "failed") {
|
|
45
|
-
return fail(safePredicateResult.error);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
return safePredicateResult.value ? pass() : normalizedRule(input, context);
|
|
49
|
-
};
|
|
50
|
-
};
|
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
-
import { when } from "./when";
|
|
3
|
-
import { pass } from "../../helpers/result/pass";
|
|
4
|
-
import { fail } from "../../helpers/result/fail";
|
|
5
|
-
|
|
6
|
-
describe("when combinator", () => {
|
|
7
|
-
const mockRule = vi.fn(() => pass());
|
|
8
|
-
const mockPredicateTrue = vi.fn((_: any) => true);
|
|
9
|
-
const mockPredicateFalse = vi.fn((_: any) => false);
|
|
10
|
-
|
|
11
|
-
beforeEach(() => {
|
|
12
|
-
vi.clearAllMocks();
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
// Basic functionality
|
|
16
|
-
it("should apply rule when condition is true", async () => {
|
|
17
|
-
const conditionalRule = when(mockPredicateTrue, mockRule);
|
|
18
|
-
const input = { active: true };
|
|
19
|
-
|
|
20
|
-
await conditionalRule(input);
|
|
21
|
-
|
|
22
|
-
expect(mockPredicateTrue).toHaveBeenCalledWith(input, undefined);
|
|
23
|
-
expect(mockRule).toHaveBeenCalledWith(input, undefined);
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
it("should skip rule when condition is false", async () => {
|
|
27
|
-
const conditionalRule = when(mockPredicateFalse, mockRule);
|
|
28
|
-
const input = { active: false };
|
|
29
|
-
const result = await conditionalRule(input);
|
|
30
|
-
|
|
31
|
-
expect(mockPredicateFalse).toHaveBeenCalledWith(input, undefined);
|
|
32
|
-
expect(result).toEqual(pass());
|
|
33
|
-
expect(mockRule).not.toHaveBeenCalled();
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
it("should work with async predicates", async () => {
|
|
37
|
-
const conditionalRule = when(async (input: { id: number }) => {
|
|
38
|
-
await Promise.resolve();
|
|
39
|
-
return input.id > 10;
|
|
40
|
-
}, mockRule);
|
|
41
|
-
|
|
42
|
-
await conditionalRule({ id: 20 });
|
|
43
|
-
expect(mockRule).toHaveBeenCalled();
|
|
44
|
-
|
|
45
|
-
mockRule.mockClear();
|
|
46
|
-
await conditionalRule({ id: 5 });
|
|
47
|
-
expect(mockRule).not.toHaveBeenCalled();
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
it("should handle mixed async predicates with sync rules", async () => {
|
|
51
|
-
const conditionalRule = when(async (input: { value: number }) => {
|
|
52
|
-
await Promise.resolve();
|
|
53
|
-
return input.value > 5;
|
|
54
|
-
}, mockRule);
|
|
55
|
-
|
|
56
|
-
await conditionalRule({ value: 10 });
|
|
57
|
-
expect(mockRule).toHaveBeenCalled();
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
it("should handle falsy conditions", async () => {
|
|
61
|
-
const testCases = [
|
|
62
|
-
{ condition: false, shouldRun: false },
|
|
63
|
-
{ condition: 0, shouldRun: false },
|
|
64
|
-
{ condition: "", shouldRun: false },
|
|
65
|
-
{ condition: null, shouldRun: false },
|
|
66
|
-
{ condition: undefined, shouldRun: false },
|
|
67
|
-
];
|
|
68
|
-
|
|
69
|
-
for (const { condition, shouldRun } of testCases) {
|
|
70
|
-
const conditionalRule = when(() => condition as any, mockRule);
|
|
71
|
-
await conditionalRule({});
|
|
72
|
-
expect(mockRule.mock.calls.length).toBe(shouldRun ? 1 : 0);
|
|
73
|
-
mockRule.mockClear();
|
|
74
|
-
}
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
it("should work with async rules needing context", async () => {
|
|
78
|
-
const context = {
|
|
79
|
-
db: {
|
|
80
|
-
findUser: async (_id: string) => true,
|
|
81
|
-
},
|
|
82
|
-
};
|
|
83
|
-
const validate = when(
|
|
84
|
-
(input: { id: string }) => !!input.id,
|
|
85
|
-
async (input, ctx: any) => {
|
|
86
|
-
const exists = await ctx.db.findUser(input.id);
|
|
87
|
-
return exists ? pass() : fail("Not found");
|
|
88
|
-
},
|
|
89
|
-
);
|
|
90
|
-
|
|
91
|
-
await validate({ id: "123" }, context);
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
// Error cases
|
|
95
|
-
it("should propagate condition errors", async () => {
|
|
96
|
-
const errorCondition = () => {
|
|
97
|
-
throw new Error("Condition failed");
|
|
98
|
-
};
|
|
99
|
-
const conditionalRule = when(errorCondition, mockRule, {
|
|
100
|
-
errorHandlingMode: "unsafe",
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
expect(conditionalRule({})).resolves.toEqual(
|
|
104
|
-
fail(new Error("Condition failed")),
|
|
105
|
-
);
|
|
106
|
-
expect(mockRule).not.toHaveBeenCalled();
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
it("should propagate rule errors when condition passes", async () => {
|
|
110
|
-
const errorRule = () => {
|
|
111
|
-
throw new Error("Rule failed");
|
|
112
|
-
};
|
|
113
|
-
const conditionalRule = when(() => true, errorRule, {
|
|
114
|
-
errorHandlingMode: "unsafe",
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
expect(conditionalRule({})).rejects.toThrow("Rule failed");
|
|
118
|
-
});
|
|
119
|
-
});
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { fail, getNormalizedRule } from "../../helpers";
|
|
2
|
-
import { pass } from "../../helpers/result/pass";
|
|
3
|
-
import type { Predicate } from "../../types";
|
|
4
|
-
import type { Rule } from "../../types/rule";
|
|
5
|
-
import type { SafetyOptions } from "../../types/safety-options";
|
|
6
|
-
import { withSafePredicate } from "../utility";
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Conditionally executes a rule based on a predicate.
|
|
10
|
-
* Similar to branch but without an else case.
|
|
11
|
-
* @template TInput - The type of the input to validate
|
|
12
|
-
* @template TError - The type of the error (defaults to string)
|
|
13
|
-
* @param predicate - Function that determines whether to execute the rule
|
|
14
|
-
* @param rule - Rule to execute when predicate returns true
|
|
15
|
-
* @param options - Configuration for error handling and predicate safety
|
|
16
|
-
* @param options.errorHandlingMode - Determines how errors are handled:
|
|
17
|
-
* - 'safe': (default) Converts thrown errors to validation failures
|
|
18
|
-
* - 'unsafe': Lets errors propagate (use only in performance-critical paths)
|
|
19
|
-
* @param options.errorTransform - Custom transformation for caught errors
|
|
20
|
-
* @param options.predicateErrorTransform - Special error handler for predicate failures
|
|
21
|
-
* @returns A new rule that conditionally executes the input rule
|
|
22
|
-
* @example
|
|
23
|
-
* const rule = when(
|
|
24
|
-
* (user) => user.role === "admin",
|
|
25
|
-
* validateAdminPrivileges
|
|
26
|
-
* );
|
|
27
|
-
* @caveats
|
|
28
|
-
* - The predicate can be async
|
|
29
|
-
* - If predicate returns false, the rule automatically passes
|
|
30
|
-
*/
|
|
31
|
-
export const when = <TInput, TError = string, TContext = unknown>(
|
|
32
|
-
predicate: Predicate<TInput, TContext>,
|
|
33
|
-
rule: Rule<TInput, TError, TContext>,
|
|
34
|
-
options?: SafetyOptions<TError>,
|
|
35
|
-
): Rule<TInput, TError, TContext> => {
|
|
36
|
-
return async (input: TInput, context?: TContext) => {
|
|
37
|
-
const normalizedRule = getNormalizedRule(rule, options);
|
|
38
|
-
const safePredicate = withSafePredicate<TInput, TError, TContext>(
|
|
39
|
-
predicate,
|
|
40
|
-
options?.predicateErrorTransform,
|
|
41
|
-
);
|
|
42
|
-
|
|
43
|
-
const safePredicateResult = await safePredicate(input, context);
|
|
44
|
-
if (safePredicateResult.status === "failed") {
|
|
45
|
-
return fail(safePredicateResult.error);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
return safePredicateResult.value ? normalizedRule(input, context) : pass();
|
|
49
|
-
};
|
|
50
|
-
};
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
-
import { fail, pass } from "../../helpers";
|
|
3
|
-
import { withFallback } from "./with-fallback";
|
|
4
|
-
|
|
5
|
-
describe("withFallback", () => {
|
|
6
|
-
const mockMainRule = vi.fn();
|
|
7
|
-
const mockFallback = vi.fn();
|
|
8
|
-
|
|
9
|
-
beforeEach(() => {
|
|
10
|
-
mockMainRule.mockReset();
|
|
11
|
-
mockFallback.mockReset();
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
it("should execute fallback when main rule fails", async () => {
|
|
15
|
-
mockMainRule.mockResolvedValue(fail("Main failed"));
|
|
16
|
-
mockFallback.mockResolvedValue(pass());
|
|
17
|
-
|
|
18
|
-
const rule = withFallback(mockMainRule, mockFallback);
|
|
19
|
-
const result = await rule("test");
|
|
20
|
-
|
|
21
|
-
expect(mockMainRule).toHaveBeenCalledWith("test", undefined);
|
|
22
|
-
expect(mockFallback).toHaveBeenCalledWith("test", undefined);
|
|
23
|
-
expect(result).toEqual(pass());
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
it("should not execute fallback when main rule passes", async () => {
|
|
27
|
-
mockMainRule.mockResolvedValue(pass());
|
|
28
|
-
|
|
29
|
-
const rule = withFallback(mockMainRule, mockFallback);
|
|
30
|
-
const result = await rule("test");
|
|
31
|
-
|
|
32
|
-
expect(mockFallback).not.toHaveBeenCalled();
|
|
33
|
-
expect(result).toEqual(pass());
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
it("should respect conditional fallback predicate", async () => {
|
|
37
|
-
mockMainRule.mockResolvedValue(fail({ code: "RETRYABLE" }));
|
|
38
|
-
mockFallback.mockResolvedValue(pass());
|
|
39
|
-
|
|
40
|
-
const rule = withFallback(mockMainRule, mockFallback, {
|
|
41
|
-
onlyFallbackOn: (err) => (err as any).code === "RETRYABLE",
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
await rule("test");
|
|
45
|
-
expect(mockFallback).toHaveBeenCalled();
|
|
46
|
-
|
|
47
|
-
mockMainRule.mockResolvedValue(fail({ code: "FATAL" }));
|
|
48
|
-
await rule("test");
|
|
49
|
-
expect(mockFallback).toHaveBeenCalledTimes(1); // Not called for FATAL
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
it("should preserve context", async () => {
|
|
53
|
-
const context = { auth: true };
|
|
54
|
-
mockMainRule.mockResolvedValue(fail("Failed"));
|
|
55
|
-
mockFallback.mockResolvedValue(pass());
|
|
56
|
-
|
|
57
|
-
const rule = withFallback(mockMainRule, mockFallback);
|
|
58
|
-
await rule("test", context);
|
|
59
|
-
|
|
60
|
-
expect(mockMainRule).toHaveBeenCalledWith("test", context);
|
|
61
|
-
expect(mockFallback).toHaveBeenCalledWith("test", context);
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
it("should maintain type safety", async () => {
|
|
65
|
-
// Type test - no runtime assertion needed
|
|
66
|
-
const stringRule = (_: string) => pass();
|
|
67
|
-
const numberRule = (_: number) => pass();
|
|
68
|
-
|
|
69
|
-
// @ts-expect-error - Should fail type check
|
|
70
|
-
withFallback(stringRule, numberRule);
|
|
71
|
-
});
|
|
72
|
-
});
|