ts-rules-composer 0.0.1 → 1.0.0
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/.github/workflows/publish.yml +1 -1
- package/README.md +310 -42
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +335 -55
- package/dist/index.d.ts +335 -55
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/eslint.config.mjs +84 -0
- package/examples/financial-transaction.example.ts +188 -0
- package/examples/model-deployment.example.ts +136 -0
- package/examples/user-registration.example.ts +101 -0
- package/package.json +21 -6
- package/src/lib/combinators/logic/every.spec.ts +1 -1
- package/src/lib/combinators/logic/every.ts +17 -7
- package/src/lib/combinators/logic/if-else.spec.ts +11 -1
- package/src/lib/combinators/logic/if-else.ts +33 -8
- package/src/lib/combinators/logic/match.ts +20 -6
- package/src/lib/combinators/logic/not.spec.ts +3 -1
- package/src/lib/combinators/logic/not.ts +12 -3
- package/src/lib/combinators/logic/one-of.spec.ts +7 -7
- package/src/lib/combinators/logic/one-of.ts +11 -4
- package/src/lib/combinators/logic/unless.spec.ts +1 -1
- package/src/lib/combinators/logic/unless.ts +28 -5
- package/src/lib/combinators/logic/when.spec.ts +11 -15
- package/src/lib/combinators/logic/when.ts +29 -8
- package/src/lib/combinators/logic/with-fallback.ts +13 -4
- package/src/lib/combinators/utility/index.ts +5 -2
- package/src/lib/combinators/utility/inject.ts +1 -1
- package/src/lib/combinators/utility/map-error.ts +1 -1
- package/src/lib/combinators/utility/tap.spec.ts +63 -63
- package/src/lib/combinators/utility/tap.ts +18 -28
- package/src/lib/combinators/utility/validate-field.spec.ts +1 -1
- package/src/lib/combinators/utility/validate-field.ts +10 -3
- package/src/lib/combinators/utility/with-debug.spec.ts +1 -1
- package/src/lib/combinators/utility/with-debug.ts +1 -1
- package/src/lib/combinators/utility/with-memoize.spec.ts +1 -1
- package/src/lib/combinators/utility/with-memoize.ts +12 -4
- package/src/lib/combinators/utility/with-retry.spec.ts +1 -1
- package/src/lib/combinators/utility/with-retry.ts +4 -2
- package/src/lib/combinators/utility/with-safe-error.spec.ts +137 -0
- package/src/lib/combinators/utility/with-safe-error.ts +56 -0
- package/src/lib/combinators/utility/with-safe-predicate.spec.ts +176 -0
- package/src/lib/combinators/utility/with-safe-predicate.ts +64 -0
- package/src/lib/combinators/utility/with-tap.spec.ts +104 -0
- package/src/lib/combinators/utility/with-tap.ts +46 -0
- package/src/lib/combinators/utility/with-timeout.spec.ts +1 -1
- package/src/lib/combinators/utility/with-timeout.ts +10 -3
- package/src/lib/composition/compose-rules.spec.ts +1 -1
- package/src/lib/composition/compose-rules.ts +16 -8
- package/src/lib/composition/pipe-rules.spec.ts +1 -1
- package/src/lib/composition/pipe-rules.ts +15 -7
- package/src/lib/composition/pipe.ts +1 -0
- package/src/lib/helpers/clone/clone.ts +12 -0
- package/src/lib/helpers/clone/getCloneFn.ts +17 -0
- package/src/lib/helpers/clone/shallowClone.ts +12 -0
- package/src/lib/helpers/context/require-context.ts +1 -1
- package/src/lib/helpers/context/with-lazy-context.spec.ts +1 -1
- package/src/lib/helpers/context/with-lazy-context.ts +1 -1
- package/src/lib/helpers/index.ts +2 -0
- package/src/lib/helpers/result/fail.ts +1 -1
- package/src/lib/helpers/result/pass.ts +1 -1
- package/src/lib/helpers/retry/calculate-delay.ts +1 -1
- package/src/lib/helpers/safety/get-normalized-rule.spec.ts +209 -0
- package/src/lib/helpers/safety/get-normalized-rule.ts +14 -0
- package/src/lib/helpers/safety/get-normalized-rules.spec.ts +138 -0
- package/src/lib/helpers/safety/get-normalized-rules.ts +14 -0
- package/src/lib/index.ts +1 -1
- package/src/lib/types/composition-options.ts +28 -3
- package/src/lib/types/debug-options.ts +1 -1
- package/src/lib/types/index.ts +8 -4
- package/src/lib/types/predicate-result.ts +20 -0
- package/src/lib/types/predicate-safe.ts +10 -0
- package/src/lib/types/predicate-safety-options.ts +27 -0
- package/src/lib/types/predicate.ts +8 -0
- package/src/lib/types/prettify.ts +3 -0
- package/src/lib/types/rule-safety-options.ts +34 -0
- package/src/lib/types/rule.ts +1 -1
- package/src/lib/types/safety-options.ts +7 -0
- package/src/test/financial-transaction.spec.ts +251 -0
- package/src/test/helpers/get-rule-error.ts +1 -1
- package/src/test/integration.spec.ts +3 -3
- package/src/test/model-deployment.spec.ts +209 -0
- package/src/test/user-registration.spec.ts +164 -0
- package/tsconfig.json +5 -4
- package/tsup.config.ts +15 -15
- package/typedoc/tsconfig.typedoc.json +15 -0
- package/typedoc/typedoc.json +14 -0
- package/.eslintrc.json +0 -66
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { Rule } from "../src/lib";
|
|
2
|
+
import {
|
|
3
|
+
inject,
|
|
4
|
+
withLazyContext,
|
|
5
|
+
withMemoize,
|
|
6
|
+
pass,
|
|
7
|
+
fail,
|
|
8
|
+
pipeRules,
|
|
9
|
+
tap,
|
|
10
|
+
} from "../src/lib";
|
|
11
|
+
|
|
12
|
+
// 1. Define types
|
|
13
|
+
type Deployment = {
|
|
14
|
+
modelId: string;
|
|
15
|
+
version: string;
|
|
16
|
+
userId: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type ModelMetadata = {
|
|
20
|
+
modelId: string;
|
|
21
|
+
latestVersion: string;
|
|
22
|
+
isDeprecated: boolean;
|
|
23
|
+
riskScore: number;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
type Context = {
|
|
27
|
+
modelMeta: ModelMetadata;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
type Injected = {
|
|
31
|
+
logger: {
|
|
32
|
+
log: (msg: string, payload: unknown) => void;
|
|
33
|
+
};
|
|
34
|
+
riskService: {
|
|
35
|
+
assess: (modelId: string) => Promise<number>;
|
|
36
|
+
};
|
|
37
|
+
modelRegistry: {
|
|
38
|
+
getMetadata: (modelId: string) => Promise<ModelMetadata>;
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// 2. Basic rules
|
|
43
|
+
const validateVersionUpToDate: Rule<Deployment, string, Context> = (d, ctx) => {
|
|
44
|
+
return d.version === ctx?.modelMeta.latestVersion
|
|
45
|
+
? pass()
|
|
46
|
+
: fail("Version is not up to date");
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const checkDeprecation: Rule<Deployment, string, Context> = (_, ctx) => {
|
|
50
|
+
return ctx?.modelMeta.isDeprecated ? fail("Model is deprecated") : pass();
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const checkRisk = (services: Injected["riskService"]): Rule<Deployment> =>
|
|
54
|
+
withMemoize(
|
|
55
|
+
async (d) => {
|
|
56
|
+
const score = await services.assess(d.modelId);
|
|
57
|
+
return score < 7 ? pass() : fail("Model risk too high");
|
|
58
|
+
},
|
|
59
|
+
(d) => d.modelId,
|
|
60
|
+
{ ttl: 60_000 },
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
// 3. Factory function with injection
|
|
64
|
+
const createDeploymentValidator = (deps: Injected) =>
|
|
65
|
+
pipeRules([
|
|
66
|
+
tap((input) => deps.logger.log("Deployment started", { input })),
|
|
67
|
+
|
|
68
|
+
withLazyContext<Deployment, string, Context>(
|
|
69
|
+
async (deployment) => {
|
|
70
|
+
const meta = await deps.modelRegistry.getMetadata(deployment.modelId);
|
|
71
|
+
return { modelMeta: meta };
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
pipeRules<Deployment, string, Context>([
|
|
75
|
+
validateVersionUpToDate,
|
|
76
|
+
checkDeprecation,
|
|
77
|
+
]),
|
|
78
|
+
),
|
|
79
|
+
|
|
80
|
+
checkRisk(deps.riskService),
|
|
81
|
+
|
|
82
|
+
tap((_, __) => deps.logger.log("Deployment passed", {})),
|
|
83
|
+
]);
|
|
84
|
+
|
|
85
|
+
// 4. Setup
|
|
86
|
+
const mockLogger = {
|
|
87
|
+
log: (msg: string, payload: unknown) =>
|
|
88
|
+
console.log(`[LOG] ${msg}:`, JSON.stringify(payload, null, 2)),
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const mockRegistry = {
|
|
92
|
+
getMetadata: async (id: string): Promise<ModelMetadata> => ({
|
|
93
|
+
modelId: id,
|
|
94
|
+
latestVersion: "1.2.0",
|
|
95
|
+
isDeprecated: false,
|
|
96
|
+
riskScore: 4,
|
|
97
|
+
}),
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const mockRiskService = {
|
|
101
|
+
assess: async (modelId: string) => {
|
|
102
|
+
console.log(`Assessing risk for ${modelId}...`);
|
|
103
|
+
return 5;
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// 5. Compose final rule
|
|
108
|
+
const validateDeployment = inject(
|
|
109
|
+
{
|
|
110
|
+
logger: mockLogger,
|
|
111
|
+
modelRegistry: mockRegistry,
|
|
112
|
+
riskService: mockRiskService,
|
|
113
|
+
},
|
|
114
|
+
createDeploymentValidator,
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
// 6. Run it
|
|
118
|
+
(async () => {
|
|
119
|
+
const deployment: Deployment = {
|
|
120
|
+
modelId: "gpt-9000",
|
|
121
|
+
version: "1.2.0",
|
|
122
|
+
userId: "u456",
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const result = await validateDeployment(deployment);
|
|
126
|
+
console.log("Result:", result);
|
|
127
|
+
|
|
128
|
+
const outdatedDeploymenty: Deployment = {
|
|
129
|
+
modelId: "gpt-9000",
|
|
130
|
+
version: "1.1.0",
|
|
131
|
+
userId: "u456",
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const outdatedResult = await validateDeployment(outdatedDeploymenty);
|
|
135
|
+
console.log("Result 2 (outdated):", outdatedResult);
|
|
136
|
+
})();
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { Rule } from "../src/lib";
|
|
2
|
+
import {
|
|
3
|
+
pipeRules,
|
|
4
|
+
every,
|
|
5
|
+
match,
|
|
6
|
+
withMemoize,
|
|
7
|
+
pass,
|
|
8
|
+
fail,
|
|
9
|
+
mapError,
|
|
10
|
+
} from "../src/lib";
|
|
11
|
+
|
|
12
|
+
// Types
|
|
13
|
+
type User = {
|
|
14
|
+
username: string;
|
|
15
|
+
password: string;
|
|
16
|
+
email: string;
|
|
17
|
+
role: "admin" | "user" | "unknown";
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// Mocked rules
|
|
21
|
+
const validateUsernameFormat: Rule<User> = (user) => {
|
|
22
|
+
return /^[a-zA-Z0-9_]{3,16}$/.test(user.username)
|
|
23
|
+
? pass()
|
|
24
|
+
: fail("Username must be 3-16 characters and alphanumeric");
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const checkUsernameAvailability: Rule<User> = async (user) => {
|
|
28
|
+
const taken = ["admin", "testuser"];
|
|
29
|
+
return taken.includes(user.username)
|
|
30
|
+
? fail("Username is already taken")
|
|
31
|
+
: pass();
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const validatePasswordStrength: Rule<User> = (user) => {
|
|
35
|
+
return user.password.length >= 8
|
|
36
|
+
? pass()
|
|
37
|
+
: fail("Password must be at least 8 characters long");
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const validateEmailFormat: Rule<User> = (user) => {
|
|
41
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(user.email)
|
|
42
|
+
? pass()
|
|
43
|
+
: fail("Invalid email format");
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const checkEmailUnique: Rule<User> = async (user) => {
|
|
47
|
+
const usedEmails = ["taken@example.com"];
|
|
48
|
+
return usedEmails.includes(user.email)
|
|
49
|
+
? fail("Email is already in use")
|
|
50
|
+
: pass();
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const validateAdminPrivileges: Rule<User> = (user) =>
|
|
54
|
+
user.username === "admin"
|
|
55
|
+
? pass()
|
|
56
|
+
: fail("Admin users must use the 'admin' username");
|
|
57
|
+
|
|
58
|
+
const validateStandardUser: Rule<User> = () => pass();
|
|
59
|
+
|
|
60
|
+
// Compose validator
|
|
61
|
+
const validateUser = pipeRules([
|
|
62
|
+
validateUsernameFormat,
|
|
63
|
+
withMemoize(checkUsernameAvailability, (user) => user.username, {
|
|
64
|
+
ttl: 60000,
|
|
65
|
+
}),
|
|
66
|
+
mapError(
|
|
67
|
+
every([validatePasswordStrength, validateEmailFormat, checkEmailUnique]),
|
|
68
|
+
(errors) => errors.join(", "),
|
|
69
|
+
),
|
|
70
|
+
match<User, string>(
|
|
71
|
+
(user) => user.role,
|
|
72
|
+
{
|
|
73
|
+
admin: validateAdminPrivileges,
|
|
74
|
+
user: validateStandardUser,
|
|
75
|
+
},
|
|
76
|
+
"Unknown role",
|
|
77
|
+
),
|
|
78
|
+
]);
|
|
79
|
+
|
|
80
|
+
// Example usage
|
|
81
|
+
(async () => {
|
|
82
|
+
const validUser: User = {
|
|
83
|
+
username: "new_user",
|
|
84
|
+
password: "password123",
|
|
85
|
+
email: "user@example.com",
|
|
86
|
+
role: "user",
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const failingUser: User = {
|
|
90
|
+
username: "new_user",
|
|
91
|
+
password: "psw",
|
|
92
|
+
email: "taken@example.com",
|
|
93
|
+
role: "user",
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const validResult = await validateUser(validUser);
|
|
97
|
+
console.log("Validation Result:", validResult);
|
|
98
|
+
|
|
99
|
+
const failingResult = await validateUser(failingUser);
|
|
100
|
+
console.log("Validation Result 2:", failingResult);
|
|
101
|
+
})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ts-rules-composer",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Typescript rules engine by composition",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -32,15 +32,16 @@
|
|
|
32
32
|
"test:coverage": "vitest run --coverage",
|
|
33
33
|
"watch:build": "tsc -p tsconfig.json -w",
|
|
34
34
|
"watch:test": "vitest",
|
|
35
|
-
"generate-docs": "typedoc
|
|
35
|
+
"generate-docs": "typedoc --options typedoc/typedoc.json",
|
|
36
36
|
"release": "semantic-release"
|
|
37
37
|
},
|
|
38
38
|
"engines": {
|
|
39
39
|
"node": ">=18"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@
|
|
43
|
-
"@
|
|
42
|
+
"@eslint/compat": "^1.2.9",
|
|
43
|
+
"@eslint/eslintrc": "^3.3.1",
|
|
44
|
+
"@eslint/js": "^9.26.0",
|
|
44
45
|
"@vitest/coverage-v8": "^3.1.2",
|
|
45
46
|
"conventional-changelog-conventionalcommits": "^8.0.0",
|
|
46
47
|
"cspell": "^8.19.2",
|
|
@@ -58,7 +59,21 @@
|
|
|
58
59
|
"ts-node": "^10.9.2",
|
|
59
60
|
"tsup": "^8.4.0",
|
|
60
61
|
"typedoc": "^0.28.3",
|
|
62
|
+
"typedoc-github-theme": "^0.3.0",
|
|
63
|
+
"typedoc-plugin-mermaid": "^1.12.0",
|
|
61
64
|
"typescript": "^5.8.3",
|
|
65
|
+
"typescript-eslint": "^8.32.1",
|
|
62
66
|
"vitest": "^3.1.2"
|
|
63
|
-
}
|
|
64
|
-
|
|
67
|
+
},
|
|
68
|
+
"keywords": [
|
|
69
|
+
"validation",
|
|
70
|
+
"rules engine",
|
|
71
|
+
"typescript",
|
|
72
|
+
"pipeline",
|
|
73
|
+
"combinator",
|
|
74
|
+
"functional",
|
|
75
|
+
"context-aware",
|
|
76
|
+
"business logic",
|
|
77
|
+
"async"
|
|
78
|
+
]
|
|
79
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { fail, pass } from "../../helpers";
|
|
2
|
-
import {
|
|
1
|
+
import { fail, getNormalizedRules, pass } from "../../helpers";
|
|
2
|
+
import { getCloneFn } from "../../helpers/clone/getCloneFn";
|
|
3
|
+
import type { CompositionOptions, Rule } from "../../types";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Composes multiple rules into a single rule that runs them all and collects all errors.
|
|
@@ -9,6 +10,11 @@ import { CompositionOptions, Rule } from "../../types";
|
|
|
9
10
|
* @param rules - Array of rules to compose
|
|
10
11
|
* @param options - Configuration options
|
|
11
12
|
* @param options.cloneContext - Whether to clone the context for each rule (default: false)
|
|
13
|
+
* @param options.cloneStrategy -Which strategy to use when cloning the context
|
|
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
|
|
12
18
|
* @returns A new rule that returns all errors from all failing rules
|
|
13
19
|
* @example
|
|
14
20
|
* const rule = every([
|
|
@@ -24,18 +30,22 @@ import { CompositionOptions, Rule } from "../../types";
|
|
|
24
30
|
* @caveats
|
|
25
31
|
* - Rules are executed in parallel (using Promise.all)
|
|
26
32
|
* - All rules are executed even if some fail
|
|
33
|
+
* - Cloning behavior follows this priority:
|
|
34
|
+
* 1. Uses shallowClone if options.shallowClone = true
|
|
35
|
+
* 2. Uses structuredClone if available and options.structuredClone = true
|
|
36
|
+
* 3. Falls back to JSON clone otherwise
|
|
27
37
|
*/
|
|
28
38
|
export const every = <TInput, TError = string, TContext = unknown>(
|
|
29
39
|
rules: Rule<TInput, TError, TContext>[],
|
|
30
|
-
options: CompositionOptions = {},
|
|
40
|
+
options: CompositionOptions<TError> = {},
|
|
31
41
|
): Rule<TInput, TError[], TContext> => {
|
|
32
42
|
return async (input: TInput, context?: TContext) => {
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
43
|
+
const cloneFn = getCloneFn(options);
|
|
44
|
+
const currentContext = options?.cloneContext ? cloneFn(context) : context;
|
|
45
|
+
const normalizedRules = getNormalizedRules(rules, options);
|
|
36
46
|
|
|
37
47
|
const results = await Promise.all(
|
|
38
|
-
|
|
48
|
+
normalizedRules.map((rule) => rule(input, currentContext)),
|
|
39
49
|
);
|
|
40
50
|
|
|
41
51
|
const errors = results.flatMap((r) =>
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { describe, vi, beforeEach, it, expect } from "vitest";
|
|
2
2
|
import { pass, fail } from "../../helpers";
|
|
3
|
-
import { Rule } from "../../types";
|
|
3
|
+
import type { Rule } from "../../types";
|
|
4
4
|
import { ifElse } from "./if-else";
|
|
5
5
|
|
|
6
6
|
describe("branch", () => {
|
|
7
7
|
const mockTruePredicate = vi.fn(() => true);
|
|
8
8
|
const mockFalsePredicate = vi.fn(() => false);
|
|
9
9
|
const asyncTruePredicate = vi.fn(async () => true);
|
|
10
|
+
const mockThrowingPredicate = vi.fn(() => {
|
|
11
|
+
throw new Error("Boom!");
|
|
12
|
+
});
|
|
10
13
|
|
|
11
14
|
const passingRule: Rule<string> = vi.fn(() => pass());
|
|
12
15
|
const failingRule: Rule<string> = vi.fn(() => fail("Failed rule"));
|
|
@@ -69,4 +72,11 @@ describe("branch", () => {
|
|
|
69
72
|
expect(result.status).toBe("failed");
|
|
70
73
|
expect(result).toEqual(fail("Failed rule"));
|
|
71
74
|
});
|
|
75
|
+
|
|
76
|
+
it("should handle throwing predicate", async () => {
|
|
77
|
+
const rule = ifElse(mockThrowingPredicate, passingRule, failingRule);
|
|
78
|
+
const result = await rule("input");
|
|
79
|
+
expect(result.status).toBe("failed");
|
|
80
|
+
expect(result).toEqual(fail(new Error("Boom!")));
|
|
81
|
+
});
|
|
72
82
|
});
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { pass } from "../../helpers";
|
|
2
|
-
import { Rule } from "../../types";
|
|
1
|
+
import { fail, getNormalizedRules, pass } from "../../helpers";
|
|
2
|
+
import type { Predicate, Rule } from "../../types";
|
|
3
|
+
import type { SafetyOptions } from "../../types/safety-options";
|
|
4
|
+
import { withSafePredicate } from "../utility";
|
|
3
5
|
|
|
4
6
|
/**
|
|
5
7
|
* Conditionally executes one of two rules based on a predicate
|
|
@@ -9,31 +11,54 @@ import { Rule } from "../../types";
|
|
|
9
11
|
* @param predicate - Function that determines which rule to execute
|
|
10
12
|
* @param ifRule - Rule to execute when predicate returns true
|
|
11
13
|
* @param elseRule - Rule to execute when predicate returns false (optional)
|
|
14
|
+
* @param options - Configuration for error handling and predicate safety
|
|
15
|
+
* @param options.errorHandlingMode - Determines how errors are handled:
|
|
16
|
+
* - 'safe': (default) Converts thrown errors to validation failures
|
|
17
|
+
* - 'unsafe': Lets errors propagate (use only in performance-critical paths)
|
|
18
|
+
* @param options.errorTransform - Custom transformation for caught errors
|
|
19
|
+
* @param options.predicateErrorTransform - Special error handler for predicate failures
|
|
12
20
|
* @returns A new rule that conditionally executes one of two rules
|
|
13
21
|
* @example
|
|
14
|
-
* const rule =
|
|
22
|
+
* const rule = ifElse(
|
|
15
23
|
* (user) => user.age >= 18,
|
|
16
24
|
* validateAdultAccount,
|
|
17
25
|
* validateMinorAccount
|
|
18
26
|
* );
|
|
19
27
|
*
|
|
20
28
|
* // Without elseRule (passes when predicate is false)
|
|
21
|
-
* const adultOnlyRule =
|
|
29
|
+
* const adultOnlyRule = ifElse(
|
|
22
30
|
* (user) => user.age >= 18,
|
|
23
31
|
* validateAdultAccount
|
|
24
32
|
* );
|
|
25
33
|
*/
|
|
26
34
|
export const ifElse = <TInput, TError = string, TContext = unknown>(
|
|
27
|
-
predicate:
|
|
35
|
+
predicate: Predicate<TInput, TContext>,
|
|
28
36
|
ifRule: Rule<TInput, TError, TContext>,
|
|
29
37
|
elseRule?: Rule<TInput, TError, TContext>,
|
|
38
|
+
options?: SafetyOptions<TError>,
|
|
30
39
|
): Rule<TInput, TError, TContext> => {
|
|
31
40
|
return async (input: TInput, context?: TContext) => {
|
|
32
|
-
const
|
|
41
|
+
const safePredicate = withSafePredicate<TInput, TError, TContext>(
|
|
42
|
+
predicate,
|
|
43
|
+
options?.predicateErrorTransform,
|
|
44
|
+
);
|
|
45
|
+
const safePredicateResult = await safePredicate(input, context);
|
|
46
|
+
|
|
47
|
+
// Predicate fail to run or returned invalid result
|
|
48
|
+
if (safePredicateResult.status === "failed") {
|
|
49
|
+
return fail(safePredicateResult.error);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const [normalizedIfRule, normalizedElseRule] = getNormalizedRules(
|
|
53
|
+
[ifRule, elseRule!],
|
|
54
|
+
options,
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
const shouldBranch = safePredicateResult.value;
|
|
33
58
|
return shouldBranch
|
|
34
|
-
?
|
|
59
|
+
? normalizedIfRule(input, context)
|
|
35
60
|
: elseRule
|
|
36
|
-
?
|
|
61
|
+
? normalizedElseRule(input, context)
|
|
37
62
|
: pass();
|
|
38
63
|
};
|
|
39
64
|
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { fail } from "../../helpers";
|
|
2
|
-
import { Rule, RuleResult } from "../../types";
|
|
1
|
+
import { fail, getNormalizedRule } from "../../helpers";
|
|
2
|
+
import type { Rule, RuleResult, RuleSafetyOptions } from "../../types";
|
|
3
3
|
|
|
4
4
|
const isRule = <TInput, TError, TContext>(
|
|
5
5
|
value: unknown,
|
|
@@ -16,6 +16,11 @@ const isRule = <TInput, TError, TContext>(
|
|
|
16
16
|
* @param accessor - Function that extracts the match key from input
|
|
17
17
|
* @param cases - Object mapping keys to their corresponding rules
|
|
18
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
|
|
19
24
|
* @returns A new rule that executes the matching case's rule
|
|
20
25
|
* @example
|
|
21
26
|
* // Basic usage with string error type
|
|
@@ -69,6 +74,7 @@ export const match = <
|
|
|
69
74
|
accessor: (input: TInput, context?: TContext) => TKey | Promise<TKey>,
|
|
70
75
|
cases: Record<TKey, Rule<TInput, TError, TContext>>,
|
|
71
76
|
defaultCase?: Rule<TInput, TError, TContext> | TError,
|
|
77
|
+
options?: RuleSafetyOptions<TError>,
|
|
72
78
|
): Rule<TInput, TError, TContext> => {
|
|
73
79
|
return async (
|
|
74
80
|
input: TInput,
|
|
@@ -78,13 +84,21 @@ export const match = <
|
|
|
78
84
|
const matchedRule = cases[key];
|
|
79
85
|
|
|
80
86
|
if (matchedRule) {
|
|
81
|
-
|
|
87
|
+
const safeMatchedRule = getNormalizedRule(matchedRule, options);
|
|
88
|
+
return safeMatchedRule(input, context);
|
|
82
89
|
}
|
|
83
90
|
|
|
84
91
|
if (defaultCase !== undefined) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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);
|
|
88
102
|
}
|
|
89
103
|
|
|
90
104
|
return fail(`No matching rule for key: ${String(key)}` as TError);
|
|
@@ -56,7 +56,9 @@ describe("not combinator", () => {
|
|
|
56
56
|
throw new Error("Boom!");
|
|
57
57
|
});
|
|
58
58
|
|
|
59
|
-
const invertedRule = not(errorRule, errorMsg
|
|
59
|
+
const invertedRule = not(errorRule, errorMsg, {
|
|
60
|
+
errorHandlingMode: "unsafe",
|
|
61
|
+
});
|
|
60
62
|
await expect(invertedRule({})).rejects.toThrow("Boom!");
|
|
61
63
|
});
|
|
62
64
|
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { pass, fail } from "../../helpers";
|
|
2
|
-
import {
|
|
1
|
+
import { pass, fail, getNormalizedRule } from "../../helpers";
|
|
2
|
+
import type { RuleSafetyOptions } from "../../types";
|
|
3
|
+
import type { Rule } from "../../types/rule";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Inverts the logic of a rule - passes when original fails and vice versa.
|
|
@@ -7,6 +8,11 @@ import { Rule } from "../../types/rule";
|
|
|
7
8
|
* @template TError - The type of the error (defaults to string)
|
|
8
9
|
* @param rule - The rule to invert
|
|
9
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
|
|
10
16
|
* @returns A new rule with inverted logic
|
|
11
17
|
* @example
|
|
12
18
|
* const isNotAdmin = not(isAdmin, "User must not be admin");
|
|
@@ -17,9 +23,12 @@ import { Rule } from "../../types/rule";
|
|
|
17
23
|
export const not = <TInput, TError = string>(
|
|
18
24
|
rule: Rule<TInput, TError>,
|
|
19
25
|
error: TError,
|
|
26
|
+
options?: RuleSafetyOptions<TError>,
|
|
20
27
|
): Rule<TInput, TError> => {
|
|
21
28
|
return async (input: TInput, context?: unknown) => {
|
|
22
|
-
const
|
|
29
|
+
const normalizedRule = getNormalizedRule(rule, options);
|
|
30
|
+
|
|
31
|
+
const result = await normalizedRule(input, context);
|
|
23
32
|
return result.status === "passed" ? fail(error) : pass();
|
|
24
33
|
};
|
|
25
34
|
};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, beforeEach, it, expect, vi } from "vitest";
|
|
2
2
|
import { fail, pass } from "../../helpers";
|
|
3
|
-
import { Rule } from "../../types";
|
|
3
|
+
import type { Rule } from "../../types";
|
|
4
4
|
import { oneOf } from "./one-of";
|
|
5
5
|
|
|
6
6
|
describe("oneOf combinator", () => {
|
|
@@ -13,7 +13,7 @@ describe("oneOf combinator", () => {
|
|
|
13
13
|
});
|
|
14
14
|
|
|
15
15
|
it("should pass if any rule passes", async () => {
|
|
16
|
-
const validator = oneOf(failingRule1, passingRule, failingRule2);
|
|
16
|
+
const validator = oneOf([failingRule1, passingRule, failingRule2]);
|
|
17
17
|
const result = await validator({});
|
|
18
18
|
|
|
19
19
|
expect(result).toEqual(pass());
|
|
@@ -23,14 +23,14 @@ describe("oneOf combinator", () => {
|
|
|
23
23
|
});
|
|
24
24
|
|
|
25
25
|
it("should fail with all errors if no rules pass", async () => {
|
|
26
|
-
const validator = oneOf(failingRule1, failingRule2);
|
|
26
|
+
const validator = oneOf([failingRule1, failingRule2]);
|
|
27
27
|
const result = await validator({});
|
|
28
28
|
|
|
29
29
|
expect(result).toEqual(fail(["Error 1", "Error 2"]));
|
|
30
30
|
});
|
|
31
31
|
|
|
32
32
|
it("should handle empty rules array", async () => {
|
|
33
|
-
const validator = oneOf();
|
|
33
|
+
const validator = oneOf([]);
|
|
34
34
|
const result = await validator({});
|
|
35
35
|
|
|
36
36
|
expect(result).toEqual(pass()); // Vacuous truth
|
|
@@ -40,7 +40,7 @@ describe("oneOf combinator", () => {
|
|
|
40
40
|
const context = { userId: 123 };
|
|
41
41
|
const rule = vi.fn(() => pass());
|
|
42
42
|
|
|
43
|
-
await oneOf(rule)({}, context);
|
|
43
|
+
await oneOf([rule])({}, context);
|
|
44
44
|
expect(rule).toHaveBeenCalledWith({}, context);
|
|
45
45
|
});
|
|
46
46
|
|
|
@@ -50,7 +50,7 @@ describe("oneOf combinator", () => {
|
|
|
50
50
|
return pass();
|
|
51
51
|
});
|
|
52
52
|
|
|
53
|
-
const result = await oneOf(asyncRule)({});
|
|
53
|
+
const result = await oneOf([asyncRule])({});
|
|
54
54
|
expect(result).toEqual(pass());
|
|
55
55
|
});
|
|
56
56
|
|
|
@@ -60,7 +60,7 @@ describe("oneOf combinator", () => {
|
|
|
60
60
|
const typedRule: Rule<StrictInput, string> = () => pass();
|
|
61
61
|
|
|
62
62
|
// Valid usage
|
|
63
|
-
oneOf(typedRule, () => fail("Error"));
|
|
63
|
+
oneOf([typedRule, () => fail("Error")]);
|
|
64
64
|
|
|
65
65
|
// @ts-expect-error - Should fail if input types mismatch
|
|
66
66
|
oneOf(typedRule, (input: { other: number }) => pass());
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { fail, pass } from "../../helpers";
|
|
2
|
-
import { Rule } from "../../types";
|
|
1
|
+
import { fail, getNormalizedRules, pass } from "../../helpers";
|
|
2
|
+
import type { Rule, RuleSafetyOptions } from "../../types";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Creates a rule that passes if any of the provided rules pass (short-circuiting).
|
|
@@ -7,6 +7,11 @@ import { Rule } from "../../types";
|
|
|
7
7
|
* @template TError - The type of the error (defaults to string)
|
|
8
8
|
* @template TContext - The type of the context object (optional)
|
|
9
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
|
|
10
15
|
* @returns A rule that passes if any rule passes, or fails with all errors
|
|
11
16
|
* @example
|
|
12
17
|
* const rule = oneOf(
|
|
@@ -19,16 +24,18 @@ import { Rule } from "../../types";
|
|
|
19
24
|
* - Returns all errors if all rules fail
|
|
20
25
|
*/
|
|
21
26
|
export const oneOf = <TInput, TError = string, TContext = unknown>(
|
|
22
|
-
|
|
27
|
+
rules: Rule<TInput, TError, TContext>[],
|
|
28
|
+
options?: RuleSafetyOptions<TError>,
|
|
23
29
|
): Rule<TInput, TError[], TContext> => {
|
|
24
30
|
return async (input: TInput, context?: TContext) => {
|
|
31
|
+
const normalizedRules = getNormalizedRules(rules, options);
|
|
25
32
|
const errors: TError[] = [];
|
|
26
33
|
|
|
27
34
|
if (!rules || rules.length === 0) {
|
|
28
35
|
return pass();
|
|
29
36
|
}
|
|
30
37
|
|
|
31
|
-
for (const rule of
|
|
38
|
+
for (const rule of normalizedRules) {
|
|
32
39
|
const result = await rule(input, context);
|
|
33
40
|
if (result.status === "passed") {
|
|
34
41
|
return pass();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, vi, beforeEach, it, expect } from "vitest";
|
|
2
2
|
import { fail, pass } from "../../helpers";
|
|
3
|
-
import { Rule } from "../../types";
|
|
3
|
+
import type { Rule } from "../../types";
|
|
4
4
|
import { unless } from "./unless";
|
|
5
5
|
|
|
6
6
|
describe("unless combinator", () => {
|