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,34 @@
|
|
|
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
CHANGED
|
@@ -0,0 +1,7 @@
|
|
|
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
|
+
>;
|
|
@@ -0,0 +1,251 @@
|
|
|
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
|
+
});
|
|
@@ -107,7 +107,7 @@ describe("Full Integration Test", () => {
|
|
|
107
107
|
);
|
|
108
108
|
return valid ? pass() : fail("Paypal error");
|
|
109
109
|
},
|
|
110
|
-
|
|
110
|
+
100,
|
|
111
111
|
"Paypal timeout",
|
|
112
112
|
);
|
|
113
113
|
|
|
@@ -164,10 +164,10 @@ describe("Full Integration Test", () => {
|
|
|
164
164
|
when(
|
|
165
165
|
(user) => user.profile !== undefined,
|
|
166
166
|
mapError(
|
|
167
|
-
oneOf(
|
|
167
|
+
oneOf([
|
|
168
168
|
validateUserProfile,
|
|
169
169
|
not(() => fail("Profile blocked"), "Profile must be valid"),
|
|
170
|
-
),
|
|
170
|
+
]),
|
|
171
171
|
(errors) => errors.join(", "),
|
|
172
172
|
),
|
|
173
173
|
),
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
+
import { inject, pass, fail } from "../lib";
|
|
3
|
+
import {
|
|
4
|
+
type Rule,
|
|
5
|
+
withMemoize,
|
|
6
|
+
pipeRules,
|
|
7
|
+
tap,
|
|
8
|
+
withLazyContext,
|
|
9
|
+
} from "../lib";
|
|
10
|
+
|
|
11
|
+
const mockLogger = {
|
|
12
|
+
log: vi.fn(),
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const baseMeta = {
|
|
16
|
+
modelId: "model-x",
|
|
17
|
+
latestVersion: "1.2.0",
|
|
18
|
+
isDeprecated: false,
|
|
19
|
+
riskScore: 3,
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const mockRegistry = {
|
|
23
|
+
getMetadata: vi.fn(async () => ({ ...baseMeta })),
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const mockRiskService = {
|
|
27
|
+
assess: vi.fn(async () => 5),
|
|
28
|
+
};
|
|
29
|
+
// 1. Define types
|
|
30
|
+
type Deployment = {
|
|
31
|
+
modelId: string;
|
|
32
|
+
version: string;
|
|
33
|
+
userId: string;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
type ModelMetadata = {
|
|
37
|
+
modelId: string;
|
|
38
|
+
latestVersion: string;
|
|
39
|
+
isDeprecated: boolean;
|
|
40
|
+
riskScore: number;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
type Context = {
|
|
44
|
+
modelMeta: ModelMetadata;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
type Injected = {
|
|
48
|
+
logger: {
|
|
49
|
+
log: (msg: string, payload: unknown) => void;
|
|
50
|
+
};
|
|
51
|
+
riskService: {
|
|
52
|
+
assess: (modelId: string) => Promise<number>;
|
|
53
|
+
};
|
|
54
|
+
modelRegistry: {
|
|
55
|
+
getMetadata: (modelId: string) => Promise<ModelMetadata>;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// 2. Basic rules
|
|
60
|
+
const validateVersionUpToDate: Rule<Deployment, string, Context> = (d, ctx) => {
|
|
61
|
+
return d.version === ctx?.modelMeta.latestVersion
|
|
62
|
+
? pass()
|
|
63
|
+
: fail("Version is not up to date");
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const checkDeprecation: Rule<Deployment, string, Context> = (_, ctx) => {
|
|
67
|
+
return ctx?.modelMeta.isDeprecated ? fail("Model is deprecated") : pass();
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const checkRisk = (services: Injected["riskService"]): Rule<Deployment> =>
|
|
71
|
+
withMemoize(
|
|
72
|
+
async (d) => {
|
|
73
|
+
const score = await services.assess(d.modelId);
|
|
74
|
+
return score < 7 ? pass() : fail("Model risk too high");
|
|
75
|
+
},
|
|
76
|
+
(d) => d.modelId,
|
|
77
|
+
{ ttl: 60_000 },
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
// 3. Factory function with injection
|
|
81
|
+
const createDeploymentValidator = (deps: Injected) =>
|
|
82
|
+
pipeRules([
|
|
83
|
+
tap((input) => deps.logger.log("Deployment started", { input })),
|
|
84
|
+
|
|
85
|
+
withLazyContext<Deployment, string, Context>(
|
|
86
|
+
async (deployment) => {
|
|
87
|
+
const meta = await deps.modelRegistry.getMetadata(deployment.modelId);
|
|
88
|
+
return { modelMeta: meta };
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
pipeRules<Deployment, string, Context>([
|
|
92
|
+
validateVersionUpToDate,
|
|
93
|
+
checkDeprecation,
|
|
94
|
+
]),
|
|
95
|
+
),
|
|
96
|
+
|
|
97
|
+
checkRisk(deps.riskService),
|
|
98
|
+
|
|
99
|
+
tap((_, __) => deps.logger.log("Deployment passed", {})),
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
describe("model-deployment-validator", () => {
|
|
103
|
+
let validateDeployment: Rule<Deployment, string>;
|
|
104
|
+
const validDeployment: Deployment = {
|
|
105
|
+
modelId: "model-x",
|
|
106
|
+
version: "1.2.0",
|
|
107
|
+
userId: "u1",
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
beforeEach(() => {
|
|
111
|
+
vi.clearAllMocks();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("should pass for a valid deployment", async () => {
|
|
115
|
+
validateDeployment = inject(
|
|
116
|
+
{
|
|
117
|
+
logger: mockLogger,
|
|
118
|
+
modelRegistry: mockRegistry,
|
|
119
|
+
riskService: mockRiskService,
|
|
120
|
+
},
|
|
121
|
+
createDeploymentValidator,
|
|
122
|
+
);
|
|
123
|
+
const result = await validateDeployment(validDeployment);
|
|
124
|
+
expect(result).toEqual(pass());
|
|
125
|
+
expect(mockLogger.log).toHaveBeenCalledWith(
|
|
126
|
+
"Deployment started",
|
|
127
|
+
expect.objectContaining({ input: validDeployment }),
|
|
128
|
+
);
|
|
129
|
+
expect(mockLogger.log).toHaveBeenCalledWith("Deployment passed", {});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("should fail if version is outdated", async () => {
|
|
133
|
+
validateDeployment = inject(
|
|
134
|
+
{
|
|
135
|
+
logger: mockLogger,
|
|
136
|
+
modelRegistry: mockRegistry,
|
|
137
|
+
riskService: mockRiskService,
|
|
138
|
+
},
|
|
139
|
+
createDeploymentValidator,
|
|
140
|
+
);
|
|
141
|
+
const result = await validateDeployment({
|
|
142
|
+
...validDeployment,
|
|
143
|
+
version: "1.0.0",
|
|
144
|
+
});
|
|
145
|
+
expect(result).toEqual(fail("Version is not up to date"));
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("should fail if model is deprecated", async () => {
|
|
149
|
+
mockRegistry.getMetadata.mockResolvedValueOnce({
|
|
150
|
+
...baseMeta,
|
|
151
|
+
isDeprecated: true,
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
validateDeployment = inject(
|
|
155
|
+
{
|
|
156
|
+
logger: mockLogger,
|
|
157
|
+
modelRegistry: mockRegistry,
|
|
158
|
+
riskService: mockRiskService,
|
|
159
|
+
},
|
|
160
|
+
createDeploymentValidator,
|
|
161
|
+
);
|
|
162
|
+
const result = await validateDeployment(validDeployment);
|
|
163
|
+
expect(result).toEqual(fail("Model is deprecated"));
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("should fail if risk score is too high", async () => {
|
|
167
|
+
mockRiskService.assess.mockResolvedValueOnce(9);
|
|
168
|
+
validateDeployment = inject(
|
|
169
|
+
{
|
|
170
|
+
logger: mockLogger,
|
|
171
|
+
modelRegistry: mockRegistry,
|
|
172
|
+
riskService: mockRiskService,
|
|
173
|
+
},
|
|
174
|
+
createDeploymentValidator,
|
|
175
|
+
);
|
|
176
|
+
const result = await validateDeployment(validDeployment);
|
|
177
|
+
expect(result).toEqual(fail("Model risk too high"));
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it("should memoize risk check", async () => {
|
|
181
|
+
validateDeployment = inject(
|
|
182
|
+
{
|
|
183
|
+
logger: mockLogger,
|
|
184
|
+
modelRegistry: mockRegistry,
|
|
185
|
+
riskService: mockRiskService,
|
|
186
|
+
},
|
|
187
|
+
createDeploymentValidator,
|
|
188
|
+
);
|
|
189
|
+
const result1 = await validateDeployment(validDeployment);
|
|
190
|
+
const result2 = await validateDeployment(validDeployment);
|
|
191
|
+
|
|
192
|
+
expect(result1).toEqual(pass());
|
|
193
|
+
expect(result2).toEqual(pass());
|
|
194
|
+
expect(mockRiskService.assess).toHaveBeenCalledTimes(1); // memoized
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("should reuse lazy context for multiple rules", async () => {
|
|
198
|
+
validateDeployment = inject(
|
|
199
|
+
{
|
|
200
|
+
logger: mockLogger,
|
|
201
|
+
modelRegistry: mockRegistry,
|
|
202
|
+
riskService: mockRiskService,
|
|
203
|
+
},
|
|
204
|
+
createDeploymentValidator,
|
|
205
|
+
);
|
|
206
|
+
await validateDeployment(validDeployment);
|
|
207
|
+
expect(mockRegistry.getMetadata).toHaveBeenCalledTimes(1);
|
|
208
|
+
});
|
|
209
|
+
});
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
pass,
|
|
4
|
+
fail,
|
|
5
|
+
every,
|
|
6
|
+
mapError,
|
|
7
|
+
match,
|
|
8
|
+
pipeRules,
|
|
9
|
+
withMemoize,
|
|
10
|
+
type Rule,
|
|
11
|
+
} from "../lib";
|
|
12
|
+
|
|
13
|
+
// Types
|
|
14
|
+
type User = {
|
|
15
|
+
username: string;
|
|
16
|
+
password: string;
|
|
17
|
+
email: string;
|
|
18
|
+
role: "admin" | "user" | "unknown";
|
|
19
|
+
};
|
|
20
|
+
|
|
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
|
+
describe("user-registration-validator", () => {
|
|
81
|
+
const baseUser: User = {
|
|
82
|
+
username: "valid_user",
|
|
83
|
+
password: "strongpass",
|
|
84
|
+
email: "valid@example.com",
|
|
85
|
+
role: "user",
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
beforeEach(() => {
|
|
89
|
+
vi.clearAllMocks();
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("should pass for a valid user", async () => {
|
|
93
|
+
const result = await validateUser(baseUser);
|
|
94
|
+
expect(result).toEqual(pass());
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("should fail on invalid username format", async () => {
|
|
98
|
+
const result = await validateUser({
|
|
99
|
+
...baseUser,
|
|
100
|
+
username: "??",
|
|
101
|
+
});
|
|
102
|
+
expect(result).toEqual(
|
|
103
|
+
fail("Username must be 3-16 characters and alphanumeric"),
|
|
104
|
+
);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("should fail if username is taken", async () => {
|
|
108
|
+
const result = await validateUser({
|
|
109
|
+
...baseUser,
|
|
110
|
+
username: "admin", // mocked taken name
|
|
111
|
+
});
|
|
112
|
+
expect(result).toEqual(fail("Username is already taken"));
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("should fail if password is too weak", async () => {
|
|
116
|
+
const result = await validateUser({
|
|
117
|
+
...baseUser,
|
|
118
|
+
password: "123",
|
|
119
|
+
});
|
|
120
|
+
expect(result).toEqual(fail("Password must be at least 8 characters long"));
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it("should fail on invalid email format", async () => {
|
|
124
|
+
const result = await validateUser({
|
|
125
|
+
...baseUser,
|
|
126
|
+
email: "invalid@",
|
|
127
|
+
});
|
|
128
|
+
expect(result).toEqual(fail("Invalid email format"));
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("should fail if email is already taken", async () => {
|
|
132
|
+
const result = await validateUser({
|
|
133
|
+
...baseUser,
|
|
134
|
+
email: "taken@example.com",
|
|
135
|
+
});
|
|
136
|
+
expect(result).toEqual(fail("Email is already in use"));
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("should fail if admin does not use reserved username", async () => {
|
|
140
|
+
const result = await validateUser({
|
|
141
|
+
...baseUser,
|
|
142
|
+
role: "admin",
|
|
143
|
+
username: "not_admin",
|
|
144
|
+
});
|
|
145
|
+
expect(result).toEqual(fail("Admin users must use the 'admin' username"));
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("should fail for unknown roles", async () => {
|
|
149
|
+
const result = await validateUser({
|
|
150
|
+
...baseUser,
|
|
151
|
+
role: "unknown",
|
|
152
|
+
});
|
|
153
|
+
expect(result).toEqual(fail("Unknown role"));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("should memoize username availability check", async () => {
|
|
157
|
+
const input = { ...baseUser, username: "new_user" };
|
|
158
|
+
const result1 = await validateUser(input);
|
|
159
|
+
const result2 = await validateUser(input);
|
|
160
|
+
expect(result1).toEqual(pass());
|
|
161
|
+
expect(result2).toEqual(pass());
|
|
162
|
+
// WithMemoize doesn't expose call count, but we expect caching to work
|
|
163
|
+
});
|
|
164
|
+
});
|