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,138 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
-
import { getNormalizedRules } from "./get-normalized-rules";
|
|
3
|
-
import type { Rule, RuleSafetyOptions } from "../../types";
|
|
4
|
-
import { pass, fail } from "../../helpers";
|
|
5
|
-
|
|
6
|
-
describe("getNormalizedRules", () => {
|
|
7
|
-
// Mock rules for testing
|
|
8
|
-
interface CustomError {
|
|
9
|
-
code: number;
|
|
10
|
-
message: string;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
const passingRule: Rule<string> = vi.fn(() => pass());
|
|
14
|
-
const errorThrowingRule: Rule<string> = vi.fn(() => {
|
|
15
|
-
throw new Error("Boom!");
|
|
16
|
-
});
|
|
17
|
-
const objectThrowingRule: Rule<string, { code: number }> = vi.fn(() => {
|
|
18
|
-
throw { code: 500 };
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
const passingRuleCustom: Rule<string, CustomError> = vi.fn(() =>
|
|
22
|
-
pass(),
|
|
23
|
-
) as Rule<string, CustomError>;
|
|
24
|
-
const errorThrowingRuleCustom: Rule<string, CustomError> = vi.fn(() => {
|
|
25
|
-
throw new Error("Boom!");
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
beforeEach(() => {
|
|
29
|
-
vi.clearAllMocks();
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
describe("with errorHandlingMode = 'safe' (default)", () => {
|
|
33
|
-
const defaultOptions: RuleSafetyOptions = {};
|
|
34
|
-
|
|
35
|
-
it("should return original rules when they don't throw", async () => {
|
|
36
|
-
const rules = [passingRule, passingRule];
|
|
37
|
-
const normalized = getNormalizedRules(rules, defaultOptions);
|
|
38
|
-
|
|
39
|
-
expect(normalized).toHaveLength(2);
|
|
40
|
-
|
|
41
|
-
// Verify behavior instead of function reference
|
|
42
|
-
const result1 = await normalized[0]("test");
|
|
43
|
-
expect(result1).toEqual(pass());
|
|
44
|
-
expect(passingRule).toHaveBeenCalledWith("test", undefined);
|
|
45
|
-
|
|
46
|
-
const result2 = await normalized[1]("test");
|
|
47
|
-
expect(result2).toEqual(pass());
|
|
48
|
-
expect(passingRule).toHaveBeenCalledWith("test", undefined);
|
|
49
|
-
});
|
|
50
|
-
it("should wrap throwing rules with safe handlers", async () => {
|
|
51
|
-
const rules = [errorThrowingRule];
|
|
52
|
-
const normalized = getNormalizedRules(rules, defaultOptions);
|
|
53
|
-
|
|
54
|
-
const result = await normalized[0]("test");
|
|
55
|
-
expect(result.status).toBe("failed");
|
|
56
|
-
expect((result as any).error.message).toBe("Boom!");
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
it("should handle empty rules array", () => {
|
|
60
|
-
const normalized = getNormalizedRules([], defaultOptions);
|
|
61
|
-
expect(normalized).toEqual([]);
|
|
62
|
-
});
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
describe("with errorHandlingMode = 'unsafe'", () => {
|
|
66
|
-
const unsafeOptions: RuleSafetyOptions = { errorHandlingMode: "unsafe" };
|
|
67
|
-
|
|
68
|
-
it("should return original rules without wrapping", () => {
|
|
69
|
-
const rules = [passingRule, errorThrowingRule, objectThrowingRule];
|
|
70
|
-
const normalized = getNormalizedRules(rules, unsafeOptions);
|
|
71
|
-
|
|
72
|
-
expect(normalized).toEqual(rules);
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
it("should preserve custom error types", () => {
|
|
76
|
-
const rules = [passingRuleCustom, errorThrowingRuleCustom];
|
|
77
|
-
const normalized = getNormalizedRules(rules, unsafeOptions);
|
|
78
|
-
|
|
79
|
-
expect(normalized).toEqual(rules);
|
|
80
|
-
});
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
describe("with custom errorTransform", () => {
|
|
84
|
-
const customTransform = vi.fn(
|
|
85
|
-
(error: unknown): CustomError => ({
|
|
86
|
-
code: 500,
|
|
87
|
-
message: String(error),
|
|
88
|
-
}),
|
|
89
|
-
);
|
|
90
|
-
|
|
91
|
-
const transformOptions: RuleSafetyOptions<CustomError> = {
|
|
92
|
-
errorTransform: customTransform,
|
|
93
|
-
};
|
|
94
|
-
|
|
95
|
-
it("should apply transform to throwing rules", async () => {
|
|
96
|
-
const rules = [errorThrowingRuleCustom];
|
|
97
|
-
const normalized = getNormalizedRules(rules, transformOptions);
|
|
98
|
-
|
|
99
|
-
// Test behavior instead of function reference
|
|
100
|
-
const result = await normalized[0]("test");
|
|
101
|
-
expect(result.status).toBe("failed");
|
|
102
|
-
expect((result as any).error).toEqual({
|
|
103
|
-
code: 500,
|
|
104
|
-
message: "Error: Boom!",
|
|
105
|
-
});
|
|
106
|
-
expect(customTransform).toHaveBeenCalled();
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
it("should not transform non-throwing rules", async () => {
|
|
110
|
-
const rules = [passingRuleCustom];
|
|
111
|
-
const normalized = getNormalizedRules(rules, transformOptions);
|
|
112
|
-
|
|
113
|
-
// Test behavior instead of function reference
|
|
114
|
-
const result = await normalized[0]("test");
|
|
115
|
-
expect(result).toEqual(pass());
|
|
116
|
-
expect(customTransform).not.toHaveBeenCalled();
|
|
117
|
-
});
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
describe("edge cases", () => {
|
|
121
|
-
it("should handle null/undefined rules array", () => {
|
|
122
|
-
expect(getNormalizedRules(null as any, {})).toEqual([]);
|
|
123
|
-
expect(getNormalizedRules(undefined as any, {})).toEqual([]);
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
it("should pass context through to normalized rules", async () => {
|
|
127
|
-
const context = { userId: 123 };
|
|
128
|
-
const contextAwareRule: Rule<string> = vi.fn((_, ctx) =>
|
|
129
|
-
ctx?.userId === 123 ? pass() : fail("Wrong context"),
|
|
130
|
-
);
|
|
131
|
-
|
|
132
|
-
const normalized = getNormalizedRules([contextAwareRule], {});
|
|
133
|
-
await normalized[0]("test", context);
|
|
134
|
-
|
|
135
|
-
expect(contextAwareRule).toHaveBeenCalledWith("test", context);
|
|
136
|
-
});
|
|
137
|
-
});
|
|
138
|
-
});
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { withSafeError } from "../../combinators";
|
|
2
|
-
import type { Rule, RuleSafetyOptions } from "../../types";
|
|
3
|
-
|
|
4
|
-
export const getNormalizedRules = <TInput, TError, TContext>(
|
|
5
|
-
rules: Rule<TInput, TError, TContext>[],
|
|
6
|
-
opts?: RuleSafetyOptions<TError>,
|
|
7
|
-
): Rule<TInput, TError, TContext>[] => {
|
|
8
|
-
const normalizedRules =
|
|
9
|
-
opts?.errorHandlingMode === "unsafe"
|
|
10
|
-
? rules
|
|
11
|
-
: (rules || [])?.map((rule) => withSafeError(rule, opts?.errorTransform));
|
|
12
|
-
|
|
13
|
-
return normalizedRules;
|
|
14
|
-
};
|
package/src/lib/index.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import type { Prettify } from "./prettify";
|
|
2
|
-
import type { RuleSafetyOptions } from "./rule-safety-options";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Options for rule composition functions.
|
|
6
|
-
* @property cloneContext - Whether to clone the context for each rule
|
|
7
|
-
* @property cloneStrategy - Which strategy to use when cloning the context
|
|
8
|
-
* @property errorHandling - Determines how the combinator handles thrown errors
|
|
9
|
-
* - "safe": (default) Catches errors and converts them to failed RuleResults
|
|
10
|
-
* - "unsafe": Lets errors propagate normally (for performance-critical cases)
|
|
11
|
-
*
|
|
12
|
-
* @property errorTransform - Optional custom error transformation function
|
|
13
|
-
* Only used when errorHandling="safe". Allows customizing how thrown errors
|
|
14
|
-
* are converted to the rule's error type.
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* @warn
|
|
18
|
-
* - Cloning behavior follows this priority:
|
|
19
|
-
* 1. Uses shallowClone if options.cloneStrategy = "shallow"
|
|
20
|
-
* 2. Uses structuredClone if available and options.cloneStrategy = "structured"
|
|
21
|
-
* 3. Falls back to JSON clone otherwise
|
|
22
|
-
* - structuredClone requires Node 17+ or modern browsers
|
|
23
|
-
* - JSON clone will lose special types (Date, Map, etc.)
|
|
24
|
-
* - All clones convert undefined/null to empty object {}
|
|
25
|
-
* - Circular references fail silently in JSON clone mode
|
|
26
|
-
*/
|
|
27
|
-
export type CompositionOptions<TError = string> = Prettify<
|
|
28
|
-
{
|
|
29
|
-
cloneContext?: boolean;
|
|
30
|
-
cloneStrategy?: "shallow" | "json" | "structured";
|
|
31
|
-
} & RuleSafetyOptions<TError>
|
|
32
|
-
>;
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import type { RuleResult } from "./rule-result";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Configuration options for debug functionality.
|
|
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
|
-
* @property name - Unique identifier for the rule
|
|
9
|
-
* @property onStart - Called before rule execution
|
|
10
|
-
* @property onEnd - Called after rule completes
|
|
11
|
-
* @property onError - Called when rule throws
|
|
12
|
-
*/
|
|
13
|
-
export type DebugOptions<TInput, TError, TContext> = {
|
|
14
|
-
/** Unique identifier for the rule */
|
|
15
|
-
name?: string;
|
|
16
|
-
/** Called before rule execution */
|
|
17
|
-
onStart?: (input: TInput, context?: TContext) => void;
|
|
18
|
-
/** Called after rule completes */
|
|
19
|
-
onEnd?: (
|
|
20
|
-
input: TInput,
|
|
21
|
-
result: RuleResult<TError>,
|
|
22
|
-
context?: TContext,
|
|
23
|
-
meta?: {
|
|
24
|
-
ruleName: string;
|
|
25
|
-
duration: number;
|
|
26
|
-
startTime: number;
|
|
27
|
-
},
|
|
28
|
-
) => void;
|
|
29
|
-
/** Called when rule throws */
|
|
30
|
-
onError?: (
|
|
31
|
-
error: unknown,
|
|
32
|
-
input: TInput,
|
|
33
|
-
context?: TContext,
|
|
34
|
-
duration?: number,
|
|
35
|
-
) => void;
|
|
36
|
-
};
|
package/src/lib/types/index.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
export type * from "./composition-options";
|
|
2
|
-
export type * from "./debug-options";
|
|
3
|
-
export type * from "./rule-result";
|
|
4
|
-
export type * from "./rule";
|
|
5
|
-
export type * from "./rule-safety-options";
|
|
6
|
-
export type * from "./predicate";
|
|
7
|
-
export type * from "./predicate-result";
|
|
8
|
-
export type * from "./predicate-safe";
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Represents the result of a predicate evaluation.
|
|
3
|
-
* @template TError - The type of the error (defaults to string)
|
|
4
|
-
* @example
|
|
5
|
-
* // Passed result, true value
|
|
6
|
-
* const passed: PredicateResult = { status: "passed", value: true };
|
|
7
|
-
*
|
|
8
|
-
* // Passed result, false value
|
|
9
|
-
* const passed: PredicateResult = { status: "passed", value: false };
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* // Failed result
|
|
13
|
-
* const failed: PredicateResult = {
|
|
14
|
-
* status: "failed",
|
|
15
|
-
* error: "Validation failed"
|
|
16
|
-
* };
|
|
17
|
-
*/
|
|
18
|
-
export type PredicateResult<TError = string> =
|
|
19
|
-
| { readonly status: "passed"; value: boolean }
|
|
20
|
-
| { readonly status: "failed"; readonly error: TError };
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { PredicateResult } from "./predicate-result";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* A predicate function that evaluates an input and returns a PredicateResult.
|
|
5
|
-
* Can be synchronous or asynchronous.
|
|
6
|
-
*/
|
|
7
|
-
export type PredicateSafe<TInput, TError, TContext> = (
|
|
8
|
-
input: TInput,
|
|
9
|
-
context?: TContext,
|
|
10
|
-
) => PredicateResult<TError> | Promise<PredicateResult<TError>>;
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Configuration options for error handling behavior in rule combinators
|
|
3
|
-
* @template TError - The type of the error that will be caught and transformed (when safe)
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* @property predicateErrorTransform - Optional custom error transformation function
|
|
7
|
-
* Only used when errorHandling="safe". Allows customizing how thrown errors
|
|
8
|
-
* are converted to the rule's error type.
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* @example
|
|
12
|
-
* // Custom error transformation
|
|
13
|
-
* const rule = ifElse(
|
|
14
|
-
* (user) => user.age >= 18,
|
|
15
|
-
* validateAdultAccount,
|
|
16
|
-
* validateMinorAccount,
|
|
17
|
-
* {
|
|
18
|
-
* predicateErrorTransform: (err) => ({
|
|
19
|
-
* code: 500,
|
|
20
|
-
* message: String(err)
|
|
21
|
-
* })
|
|
22
|
-
* }
|
|
23
|
-
* );
|
|
24
|
-
*/
|
|
25
|
-
export type PredicateSafetyOptions<TError = unknown> = {
|
|
26
|
-
predicateErrorTransform?: (error: unknown) => TError;
|
|
27
|
-
};
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Represents the result of a rule evaluation.
|
|
3
|
-
* @template TError - The type of the error (defaults to string)
|
|
4
|
-
* @example
|
|
5
|
-
* // Passed result
|
|
6
|
-
* const passed: RuleResult = { status: "passed" };
|
|
7
|
-
*
|
|
8
|
-
* // Failed result
|
|
9
|
-
* const failed: RuleResult = {
|
|
10
|
-
* status: "failed",
|
|
11
|
-
* error: "Validation failed"
|
|
12
|
-
* };
|
|
13
|
-
*/
|
|
14
|
-
export type RuleResult<TError = string> =
|
|
15
|
-
| { readonly status: "passed" }
|
|
16
|
-
| { readonly status: "failed"; readonly error: TError };
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Configuration options for error handling behavior in rule combinators
|
|
3
|
-
* @template TError - The type of the error that will be caught and transformed (when safe)
|
|
4
|
-
*
|
|
5
|
-
* @property errorHandling - Determines how the combinator handles thrown errors
|
|
6
|
-
* - "safe": (default) Catches errors and converts them to failed RuleResults
|
|
7
|
-
* - "unsafe": Lets errors propagate normally (for performance-critical cases)
|
|
8
|
-
*
|
|
9
|
-
* @property errorTransform - Optional custom error transformation function
|
|
10
|
-
* Only used when errorHandling="safe". Allows customizing how thrown errors
|
|
11
|
-
* are converted to the rule's error type.
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* // Basic usage with default safe handling
|
|
15
|
-
* const rule = every([rule1, rule2], { errorHandling: "safe" });
|
|
16
|
-
*
|
|
17
|
-
* @example
|
|
18
|
-
* // Unsafe mode for performance
|
|
19
|
-
* const rule = every([rule1, rule2], { errorHandling: "unsafe" });
|
|
20
|
-
*
|
|
21
|
-
* @example
|
|
22
|
-
* // Custom error transformation
|
|
23
|
-
* const rule = every([rule1, rule2], {
|
|
24
|
-
* errorHandling: "safe",
|
|
25
|
-
* errorTransform: (err) => ({
|
|
26
|
-
* code: 500,
|
|
27
|
-
* message: String(err)
|
|
28
|
-
* })
|
|
29
|
-
* });
|
|
30
|
-
*/
|
|
31
|
-
export type RuleSafetyOptions<TError = unknown> = {
|
|
32
|
-
errorHandlingMode?: "safe" | "unsafe";
|
|
33
|
-
errorTransform?: (error: unknown) => TError;
|
|
34
|
-
};
|
package/src/lib/types/rule.ts
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import type { RuleResult } from "./rule-result";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* A function that validates an input and returns a RuleResult.
|
|
5
|
-
* @template TInput - The type of the input to validate
|
|
6
|
-
* @template TError - The type of the error (defaults to string)
|
|
7
|
-
* @template TContext - The type of the context object (optional)
|
|
8
|
-
* @param input - The input value to validate
|
|
9
|
-
* @param context - Optional context object that can be used during validation
|
|
10
|
-
* @returns Either a Promise of RuleResult or RuleResult directly
|
|
11
|
-
* @example
|
|
12
|
-
* const isEven: Rule<number> = (input) => {
|
|
13
|
-
* return input % 2 === 0
|
|
14
|
-
* ? { status: "passed" }
|
|
15
|
-
* : { status: "failed", error: "Number must be even" };
|
|
16
|
-
* };
|
|
17
|
-
*/
|
|
18
|
-
export type Rule<TInput, TError = string, TContext = unknown> = (
|
|
19
|
-
input: TInput,
|
|
20
|
-
context?: TContext,
|
|
21
|
-
) => Promise<RuleResult<TError>> | RuleResult<TError>;
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import type { PredicateSafetyOptions } from "./predicate-safety-options";
|
|
2
|
-
import type { Prettify } from "./prettify";
|
|
3
|
-
import type { RuleSafetyOptions } from "./rule-safety-options";
|
|
4
|
-
|
|
5
|
-
export type SafetyOptions<TError = unknown> = Prettify<
|
|
6
|
-
RuleSafetyOptions<TError> & PredicateSafetyOptions<TError>
|
|
7
|
-
>;
|
|
@@ -1,251 +0,0 @@
|
|
|
1
|
-
import { vi, describe, beforeEach, it, expect } from "vitest";
|
|
2
|
-
import type { Rule } from "../lib";
|
|
3
|
-
import {
|
|
4
|
-
pipeRules,
|
|
5
|
-
match,
|
|
6
|
-
withRetry,
|
|
7
|
-
withMemoize,
|
|
8
|
-
withTimeout,
|
|
9
|
-
when,
|
|
10
|
-
pass,
|
|
11
|
-
fail,
|
|
12
|
-
} from "../lib";
|
|
13
|
-
|
|
14
|
-
// Mock services
|
|
15
|
-
const fraudService = {
|
|
16
|
-
assess: vi.fn(),
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
const bankService = {
|
|
20
|
-
authCheck: vi.fn(),
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
// Types
|
|
24
|
-
interface Transaction {
|
|
25
|
-
amount: number;
|
|
26
|
-
currency: string;
|
|
27
|
-
userId: string;
|
|
28
|
-
recipient: string;
|
|
29
|
-
paymentType: string;
|
|
30
|
-
accountType: string;
|
|
31
|
-
cardNumber?: string;
|
|
32
|
-
expiry?: string;
|
|
33
|
-
walletAddress?: string;
|
|
34
|
-
iban?: string;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const SUPPORTED_CURRENCIES = ["USD", "EUR", "GBP"];
|
|
38
|
-
|
|
39
|
-
// 1. Basic validators
|
|
40
|
-
const validateAmount: Rule<Transaction> = (tx: Transaction) =>
|
|
41
|
-
tx.amount > 0 ? pass() : fail("Amount must be positive");
|
|
42
|
-
|
|
43
|
-
const validateCurrency: Rule<Transaction> = (tx: Transaction) =>
|
|
44
|
-
SUPPORTED_CURRENCIES.includes(tx.currency)
|
|
45
|
-
? pass()
|
|
46
|
-
: fail(`Unsupported currency: ${tx.currency}`);
|
|
47
|
-
|
|
48
|
-
// 2. Payment method specific validators
|
|
49
|
-
const validateCardNumber: Rule<Transaction> = (tx: Transaction) => {
|
|
50
|
-
if (!tx.cardNumber) return fail("Card number required");
|
|
51
|
-
// Simple Luhn check for example purposes
|
|
52
|
-
const digits = tx.cardNumber.replace(/\D/g, "").split("").map(Number);
|
|
53
|
-
if (digits.length < 13) return fail("Invalid card number");
|
|
54
|
-
|
|
55
|
-
let sum = 0;
|
|
56
|
-
for (let i = 0; i < digits.length; i++) {
|
|
57
|
-
let digit = digits[digits.length - 1 - i];
|
|
58
|
-
if (i % 2 === 1) digit *= 2;
|
|
59
|
-
if (digit > 9) digit -= 9;
|
|
60
|
-
sum += digit;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
return sum % 10 === 0 ? pass() : fail("Invalid card number");
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
const validateExpiry: Rule<Transaction> = (tx: Transaction) => {
|
|
67
|
-
if (!tx.expiry) return fail("Expiry required");
|
|
68
|
-
const [month, year] = tx.expiry.split("/").map(Number);
|
|
69
|
-
const now = new Date();
|
|
70
|
-
const currentYear = now.getFullYear() % 100;
|
|
71
|
-
const currentMonth = now.getMonth() + 1;
|
|
72
|
-
|
|
73
|
-
if (year < currentYear || (year === currentYear && month < currentMonth)) {
|
|
74
|
-
return fail("Card expired");
|
|
75
|
-
}
|
|
76
|
-
return pass();
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
const bankAuthCheck: Rule<Transaction> = async (tx: Transaction) => {
|
|
80
|
-
try {
|
|
81
|
-
const isValid = await bankService.authCheck(tx.cardNumber!);
|
|
82
|
-
return isValid ? pass() : fail("Bank authorization failed");
|
|
83
|
-
} catch (error) {
|
|
84
|
-
return fail("Bank service error");
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
const validateWalletAddress: Rule<Transaction> = (tx: Transaction) => {
|
|
89
|
-
if (!tx.walletAddress) return fail("Wallet address required");
|
|
90
|
-
return /^0x[a-fA-F0-9]{40}$/.test(tx.walletAddress)
|
|
91
|
-
? pass()
|
|
92
|
-
: fail("Invalid wallet address");
|
|
93
|
-
};
|
|
94
|
-
|
|
95
|
-
const validateIBAN: Rule<Transaction> = (tx: Transaction) => {
|
|
96
|
-
if (!tx.iban) return fail("IBAN required");
|
|
97
|
-
// Simple IBAN format check
|
|
98
|
-
return /^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(tx.iban)
|
|
99
|
-
? pass()
|
|
100
|
-
: fail("Invalid IBAN");
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
// 3. Account type specific validators
|
|
104
|
-
const validateBusinessTransfer: Rule<Transaction> = (tx: Transaction) => {
|
|
105
|
-
return tx.amount <= 100000
|
|
106
|
-
? pass()
|
|
107
|
-
: fail("Business transfers limited to $100,000");
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
const validatePersonalTransfer: Rule<Transaction> = (tx: Transaction) => {
|
|
111
|
-
return tx.amount <= 10000
|
|
112
|
-
? pass()
|
|
113
|
-
: fail("Personal transfers limited to $10,000");
|
|
114
|
-
};
|
|
115
|
-
|
|
116
|
-
// 4. Memoized fraud check (cached for 5 minutes)
|
|
117
|
-
const checkFraudRisk: Rule<Transaction> = withMemoize(
|
|
118
|
-
async (tx: Transaction) => {
|
|
119
|
-
const risk = await fraudService.assess(tx);
|
|
120
|
-
return risk.score < 5 ? pass() : fail("High fraud risk");
|
|
121
|
-
},
|
|
122
|
-
(tx) => `${tx.userId}-${tx.amount}-${tx.recipient}`,
|
|
123
|
-
{ ttl: 300000 },
|
|
124
|
-
);
|
|
125
|
-
|
|
126
|
-
// 5. Payment method handling
|
|
127
|
-
const validatePaymentMethod: Rule<Transaction> = match(
|
|
128
|
-
(tx: Transaction) => tx.paymentType,
|
|
129
|
-
{
|
|
130
|
-
credit_card: pipeRules([
|
|
131
|
-
validateCardNumber,
|
|
132
|
-
validateExpiry,
|
|
133
|
-
withTimeout(bankAuthCheck, 500, "Bank auth timeout"),
|
|
134
|
-
]),
|
|
135
|
-
crypto: validateWalletAddress,
|
|
136
|
-
bank_transfer: validateIBAN,
|
|
137
|
-
},
|
|
138
|
-
);
|
|
139
|
-
|
|
140
|
-
// 6. Complete pipeline
|
|
141
|
-
const validateTransaction: Rule<Transaction> = pipeRules([
|
|
142
|
-
validateAmount,
|
|
143
|
-
validateCurrency,
|
|
144
|
-
|
|
145
|
-
// Only run fraud check for transactions > $1000
|
|
146
|
-
when(
|
|
147
|
-
(tx: Transaction) => tx.amount > 1000,
|
|
148
|
-
withRetry(checkFraudRisk, { attempts: 2 }),
|
|
149
|
-
),
|
|
150
|
-
|
|
151
|
-
validatePaymentMethod,
|
|
152
|
-
|
|
153
|
-
// Compliance check (different for business/personal)
|
|
154
|
-
match((tx: Transaction) => tx.accountType, {
|
|
155
|
-
business: validateBusinessTransfer,
|
|
156
|
-
personal: validatePersonalTransfer,
|
|
157
|
-
}),
|
|
158
|
-
]);
|
|
159
|
-
|
|
160
|
-
// Test cases
|
|
161
|
-
describe("Transaction Validation", () => {
|
|
162
|
-
beforeEach(() => {
|
|
163
|
-
vi.clearAllMocks();
|
|
164
|
-
fraudService.assess.mockResolvedValue({ score: 2 }); // Low risk by default
|
|
165
|
-
bankService.authCheck.mockResolvedValue(true); // Success by default
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
it("should validate a successful credit card transaction", async () => {
|
|
169
|
-
const transaction = {
|
|
170
|
-
amount: 500,
|
|
171
|
-
currency: "USD",
|
|
172
|
-
userId: "user123",
|
|
173
|
-
recipient: "recipient456",
|
|
174
|
-
paymentType: "credit_card",
|
|
175
|
-
accountType: "personal",
|
|
176
|
-
cardNumber: "4111111111111111", // Valid test Visa number
|
|
177
|
-
expiry: "12/25",
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
const result = await validateTransaction(transaction);
|
|
181
|
-
expect(result).toEqual(pass());
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
it("should validate a successful crypto transaction", async () => {
|
|
185
|
-
const transaction = {
|
|
186
|
-
amount: 2000,
|
|
187
|
-
currency: "USD",
|
|
188
|
-
userId: "user123",
|
|
189
|
-
recipient: "recipient456",
|
|
190
|
-
paymentType: "crypto",
|
|
191
|
-
accountType: "business",
|
|
192
|
-
walletAddress: "0x71C7656EC7ab88b098defB751B7401B5f6d8976F",
|
|
193
|
-
};
|
|
194
|
-
|
|
195
|
-
const result = await validateTransaction(transaction);
|
|
196
|
-
expect(result).toEqual(pass());
|
|
197
|
-
expect(fraudService.assess).toHaveBeenCalled(); // Should check fraud for >$1000
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
it("should fail for invalid currency", async () => {
|
|
201
|
-
const transaction = {
|
|
202
|
-
amount: 500,
|
|
203
|
-
currency: "XYZ", // Invalid
|
|
204
|
-
userId: "user123",
|
|
205
|
-
recipient: "recipient456",
|
|
206
|
-
paymentType: "credit_card",
|
|
207
|
-
accountType: "personal",
|
|
208
|
-
cardNumber: "4111111111111111",
|
|
209
|
-
expiry: "12/25",
|
|
210
|
-
};
|
|
211
|
-
|
|
212
|
-
const result = await validateTransaction(transaction);
|
|
213
|
-
expect(result).toEqual(fail("Unsupported currency: XYZ"));
|
|
214
|
-
});
|
|
215
|
-
|
|
216
|
-
it("should timeout slow bank auth", async () => {
|
|
217
|
-
const transaction = {
|
|
218
|
-
amount: 500,
|
|
219
|
-
currency: "USD",
|
|
220
|
-
userId: "user123",
|
|
221
|
-
recipient: "recipient456",
|
|
222
|
-
paymentType: "credit_card",
|
|
223
|
-
accountType: "personal",
|
|
224
|
-
cardNumber: "4111111111111111",
|
|
225
|
-
expiry: "12/25",
|
|
226
|
-
};
|
|
227
|
-
|
|
228
|
-
// Mock a slow response
|
|
229
|
-
bankService.authCheck.mockImplementation(
|
|
230
|
-
() => new Promise((resolve) => setTimeout(() => resolve(true), 600)),
|
|
231
|
-
);
|
|
232
|
-
|
|
233
|
-
const result = await validateTransaction(transaction);
|
|
234
|
-
expect(result).toEqual(fail("Bank auth timeout"));
|
|
235
|
-
});
|
|
236
|
-
|
|
237
|
-
it("should enforce business transfer limits", async () => {
|
|
238
|
-
const transaction = {
|
|
239
|
-
amount: 200000, // Over limit
|
|
240
|
-
currency: "USD",
|
|
241
|
-
userId: "user123",
|
|
242
|
-
recipient: "recipient456",
|
|
243
|
-
paymentType: "crypto",
|
|
244
|
-
accountType: "business",
|
|
245
|
-
walletAddress: "0x71C7656EC7ab88b098defB751B7401B5f6d8976F",
|
|
246
|
-
};
|
|
247
|
-
|
|
248
|
-
const result = await validateTransaction(transaction);
|
|
249
|
-
expect(result).toEqual(fail("Business transfers limited to $100,000"));
|
|
250
|
-
});
|
|
251
|
-
});
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import type { RuleResult } from "../../lib/types";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Extracts the error from a failed RuleResult.
|
|
5
|
-
* @template TError - The type of the error
|
|
6
|
-
* @param result - The RuleResult to inspect
|
|
7
|
-
* @returns The error from a failed result
|
|
8
|
-
* @throws {Error} When called on a passed result
|
|
9
|
-
* @example
|
|
10
|
-
* const result = await validate(input);
|
|
11
|
-
* if (result.status === "failed") {
|
|
12
|
-
* const error = getError(result);
|
|
13
|
-
* // Handle error
|
|
14
|
-
* }
|
|
15
|
-
* @caveats
|
|
16
|
-
* - Throws an error if called on a passed result
|
|
17
|
-
*/
|
|
18
|
-
export const getRuleError = <TError>(result: RuleResult<TError>): TError => {
|
|
19
|
-
if (result.status !== "failed") {
|
|
20
|
-
throw new Error("Cannot get error from passed result");
|
|
21
|
-
}
|
|
22
|
-
return result.error;
|
|
23
|
-
};
|