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,285 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
-
import {
|
|
3
|
-
withFallback,
|
|
4
|
-
withRetry,
|
|
5
|
-
withTimeout,
|
|
6
|
-
every,
|
|
7
|
-
unless,
|
|
8
|
-
withMemoize,
|
|
9
|
-
mapError,
|
|
10
|
-
when,
|
|
11
|
-
oneOf,
|
|
12
|
-
not,
|
|
13
|
-
withDebug,
|
|
14
|
-
match,
|
|
15
|
-
} from "../lib/combinators";
|
|
16
|
-
import { pipeRules } from "../lib/composition";
|
|
17
|
-
import { pass, fail } from "../lib/helpers";
|
|
18
|
-
import { getRuleError } from "./helpers/get-rule-error";
|
|
19
|
-
import { validateField } from "../lib/combinators/utility/validate-field";
|
|
20
|
-
|
|
21
|
-
describe("Full Integration Test", () => {
|
|
22
|
-
type User = {
|
|
23
|
-
email?: string;
|
|
24
|
-
username?: string;
|
|
25
|
-
age?: number;
|
|
26
|
-
payment: {
|
|
27
|
-
method?: string;
|
|
28
|
-
paymentId?: string;
|
|
29
|
-
};
|
|
30
|
-
profile?: {
|
|
31
|
-
bio?: string;
|
|
32
|
-
avatar?: string;
|
|
33
|
-
};
|
|
34
|
-
id: string;
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
// Mock services
|
|
38
|
-
const mockDb = {
|
|
39
|
-
checkEmail: vi.fn(),
|
|
40
|
-
checkUsername: vi.fn(),
|
|
41
|
-
getProfile: vi.fn(),
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
const mockPaymentService = {
|
|
45
|
-
validateCard: vi.fn(),
|
|
46
|
-
validatePaypal: vi.fn(),
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
beforeEach(() => {
|
|
50
|
-
vi.resetAllMocks();
|
|
51
|
-
mockDb.checkEmail.mockResolvedValue(false);
|
|
52
|
-
mockDb.checkUsername.mockResolvedValue(true);
|
|
53
|
-
mockDb.getProfile.mockResolvedValue({ verified: true });
|
|
54
|
-
mockPaymentService.validateCard.mockResolvedValue(true);
|
|
55
|
-
mockPaymentService.validatePaypal.mockResolvedValue(true);
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
// 1. Define individual rules
|
|
59
|
-
const validateEmailFormat = (email: string) =>
|
|
60
|
-
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
|
|
61
|
-
? pass()
|
|
62
|
-
: fail("Invalid email format");
|
|
63
|
-
|
|
64
|
-
const checkEmailUnique = async (email: string) =>
|
|
65
|
-
(await mockDb.checkEmail(email)) ? fail("Email already in use") : pass();
|
|
66
|
-
|
|
67
|
-
const validateUserEmail = validateField<User, string>(
|
|
68
|
-
(user) => user.email,
|
|
69
|
-
pipeRules([validateEmailFormat, checkEmailUnique]),
|
|
70
|
-
);
|
|
71
|
-
|
|
72
|
-
const validateUsername = pipeRules([
|
|
73
|
-
(username: string) => (username.length >= 3 ? pass() : fail("Too short")),
|
|
74
|
-
async (username: string) =>
|
|
75
|
-
(await mockDb.checkUsername(username)) ? pass() : fail("Username taken"),
|
|
76
|
-
]);
|
|
77
|
-
|
|
78
|
-
const validateUserUsername = validateField<User, string>(
|
|
79
|
-
(user) => user.username,
|
|
80
|
-
validateUsername,
|
|
81
|
-
);
|
|
82
|
-
|
|
83
|
-
const validateAge = (age: number) =>
|
|
84
|
-
age >= 18 ? pass() : fail("Must be 18+");
|
|
85
|
-
|
|
86
|
-
const validateUserAge = validateField<User, number>(
|
|
87
|
-
(user) => user.age,
|
|
88
|
-
validateAge,
|
|
89
|
-
);
|
|
90
|
-
|
|
91
|
-
// 2. Payment validation with fallback
|
|
92
|
-
const validateCreditCard = withFallback(
|
|
93
|
-
withRetry(
|
|
94
|
-
async (card: User["payment"]) => {
|
|
95
|
-
const valid = await mockPaymentService.validateCard(card.paymentId);
|
|
96
|
-
return valid ? pass() : fail("Card declined");
|
|
97
|
-
},
|
|
98
|
-
{ attempts: 2 },
|
|
99
|
-
),
|
|
100
|
-
() => fail("Payment system unavailable"),
|
|
101
|
-
);
|
|
102
|
-
|
|
103
|
-
const validatePaypal = withTimeout(
|
|
104
|
-
async (paypalAccount: User["payment"]) => {
|
|
105
|
-
const valid = await mockPaymentService.validatePaypal(
|
|
106
|
-
paypalAccount.paymentId,
|
|
107
|
-
);
|
|
108
|
-
return valid ? pass() : fail("Paypal error");
|
|
109
|
-
},
|
|
110
|
-
100,
|
|
111
|
-
"Paypal timeout",
|
|
112
|
-
);
|
|
113
|
-
|
|
114
|
-
// 3. Profile validation (parallel)
|
|
115
|
-
const validateProfile = mapError(
|
|
116
|
-
every([
|
|
117
|
-
(profile: User["profile"]) =>
|
|
118
|
-
!profile?.bio || profile.bio.length <= 500
|
|
119
|
-
? pass()
|
|
120
|
-
: fail("Bio too long"),
|
|
121
|
-
unless(
|
|
122
|
-
(profile) => !profile?.avatar,
|
|
123
|
-
() => fail("Avatar required"),
|
|
124
|
-
),
|
|
125
|
-
]),
|
|
126
|
-
(errors) => errors.join(", "),
|
|
127
|
-
);
|
|
128
|
-
|
|
129
|
-
const validateUserProfile = validateField<User, User["profile"]>(
|
|
130
|
-
(user) => user.profile,
|
|
131
|
-
validateProfile,
|
|
132
|
-
);
|
|
133
|
-
|
|
134
|
-
pipeRules<User>([
|
|
135
|
-
withMemoize(
|
|
136
|
-
validateField((user) => user.email, validateEmailFormat),
|
|
137
|
-
(user) => user.id,
|
|
138
|
-
),
|
|
139
|
-
validateField((user) => user.email, checkEmailUnique),
|
|
140
|
-
validateField((user) => user.username, validateUsername),
|
|
141
|
-
mapError(
|
|
142
|
-
validateField((user) => user.age, validateAge),
|
|
143
|
-
(err) => `Age: ${err}`,
|
|
144
|
-
),
|
|
145
|
-
]);
|
|
146
|
-
|
|
147
|
-
// 4. Main pipeline
|
|
148
|
-
const validateUserRegistration = pipeRules<User>([
|
|
149
|
-
// Account basics
|
|
150
|
-
withMemoize(validateUserEmail, (user) => user.id + user.email),
|
|
151
|
-
validateUserUsername,
|
|
152
|
-
mapError(validateUserAge, (err) => `Age: ${err}`),
|
|
153
|
-
// Payment method branch
|
|
154
|
-
match(
|
|
155
|
-
(user: User) => user.payment.method || "",
|
|
156
|
-
{
|
|
157
|
-
credit: validateField((user) => user.payment, validateCreditCard),
|
|
158
|
-
paypal: validateField((user) => user.payment, validatePaypal),
|
|
159
|
-
},
|
|
160
|
-
"Invalid payment method",
|
|
161
|
-
),
|
|
162
|
-
|
|
163
|
-
// Conditional profile check
|
|
164
|
-
when(
|
|
165
|
-
(user) => user.profile !== undefined,
|
|
166
|
-
mapError(
|
|
167
|
-
oneOf([
|
|
168
|
-
validateUserProfile,
|
|
169
|
-
not(() => fail("Profile blocked"), "Profile must be valid"),
|
|
170
|
-
]),
|
|
171
|
-
(errors) => errors.join(", "),
|
|
172
|
-
),
|
|
173
|
-
),
|
|
174
|
-
|
|
175
|
-
// Final verification
|
|
176
|
-
withDebug(
|
|
177
|
-
async (user, _ctx) => {
|
|
178
|
-
const profile = await mockDb.getProfile(user.id);
|
|
179
|
-
return profile?.verified ? pass() : fail("Unverified");
|
|
180
|
-
},
|
|
181
|
-
{ name: "FinalVerification" },
|
|
182
|
-
),
|
|
183
|
-
]);
|
|
184
|
-
|
|
185
|
-
it("should successfully validate complete registration", async () => {
|
|
186
|
-
const user = {
|
|
187
|
-
email: "test@example.com",
|
|
188
|
-
username: "testuser",
|
|
189
|
-
age: 25,
|
|
190
|
-
payment: { method: "credit", paymentId: "4111111111111111" },
|
|
191
|
-
profile: { bio: "Hello", avatar: "image.jpg" },
|
|
192
|
-
id: "123",
|
|
193
|
-
};
|
|
194
|
-
|
|
195
|
-
const result = await validateUserRegistration(user);
|
|
196
|
-
|
|
197
|
-
expect(result).toEqual(pass());
|
|
198
|
-
expect(mockDb.checkEmail).toHaveBeenCalledWith("test@example.com");
|
|
199
|
-
expect(mockPaymentService.validateCard).toHaveBeenCalledWith(
|
|
200
|
-
"4111111111111111",
|
|
201
|
-
);
|
|
202
|
-
});
|
|
203
|
-
|
|
204
|
-
it("should collect multiple errors from parallel rules", async () => {
|
|
205
|
-
const user = {
|
|
206
|
-
email: "test@example.com",
|
|
207
|
-
username: "testuser",
|
|
208
|
-
age: 25,
|
|
209
|
-
payment: { method: "credit", number: "4111111111111111" },
|
|
210
|
-
profile: { bio: "a".repeat(600) }, // Invalid bio
|
|
211
|
-
id: "123",
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
mockDb.getProfile.mockResolvedValue({ verified: false });
|
|
215
|
-
|
|
216
|
-
const result = await validateUserRegistration(user);
|
|
217
|
-
|
|
218
|
-
if (result.status === "failed") {
|
|
219
|
-
const error = getRuleError(result);
|
|
220
|
-
console.log(error);
|
|
221
|
-
expect(error).toMatch("Unverified");
|
|
222
|
-
} else {
|
|
223
|
-
expect.fail("Expected validation to fail");
|
|
224
|
-
}
|
|
225
|
-
});
|
|
226
|
-
|
|
227
|
-
it("should handle payment fallback", async () => {
|
|
228
|
-
const user = {
|
|
229
|
-
email: "test@example.com",
|
|
230
|
-
username: "testuser",
|
|
231
|
-
age: 25,
|
|
232
|
-
payment: { method: "credit", number: "4111111111111111" },
|
|
233
|
-
id: "123",
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
mockPaymentService.validateCard.mockRejectedValue(new Error("API down"));
|
|
237
|
-
|
|
238
|
-
const result = await validateUserRegistration(user);
|
|
239
|
-
|
|
240
|
-
if (result.status === "failed") {
|
|
241
|
-
expect(getRuleError(result)).toBe("Payment system unavailable");
|
|
242
|
-
} else {
|
|
243
|
-
expect.fail("Expected fallback to trigger");
|
|
244
|
-
}
|
|
245
|
-
});
|
|
246
|
-
|
|
247
|
-
it("should timeout slow payments", async () => {
|
|
248
|
-
const user = {
|
|
249
|
-
email: "test@example.com",
|
|
250
|
-
username: "testuser",
|
|
251
|
-
age: 25,
|
|
252
|
-
payment: { method: "paypal", email: "test@paypal.com" },
|
|
253
|
-
id: "123",
|
|
254
|
-
};
|
|
255
|
-
|
|
256
|
-
mockPaymentService.validatePaypal.mockImplementation(
|
|
257
|
-
() => new Promise((resolve) => setTimeout(() => resolve(true), 4000)),
|
|
258
|
-
);
|
|
259
|
-
|
|
260
|
-
const result = await validateUserRegistration(user);
|
|
261
|
-
|
|
262
|
-
if (result.status === "failed") {
|
|
263
|
-
expect(getRuleError(result)).toBe("Paypal timeout");
|
|
264
|
-
} else {
|
|
265
|
-
expect.fail("Expected timeout to trigger");
|
|
266
|
-
}
|
|
267
|
-
});
|
|
268
|
-
|
|
269
|
-
it("should memoize expensive validations", async () => {
|
|
270
|
-
const user = {
|
|
271
|
-
email: "memo@test.com",
|
|
272
|
-
username: "memo_user",
|
|
273
|
-
age: 30,
|
|
274
|
-
payment: { method: "credit", number: "5555555555554444" },
|
|
275
|
-
id: "456",
|
|
276
|
-
};
|
|
277
|
-
|
|
278
|
-
// First call
|
|
279
|
-
await validateUserRegistration(user);
|
|
280
|
-
// Second call with same email
|
|
281
|
-
await validateUserRegistration(user);
|
|
282
|
-
|
|
283
|
-
expect(mockDb.checkEmail).toHaveBeenCalledTimes(1);
|
|
284
|
-
});
|
|
285
|
-
});
|
|
@@ -1,209 +0,0 @@
|
|
|
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
|
-
});
|
|
@@ -1,164 +0,0 @@
|
|
|
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
|
-
});
|
package/tsconfig.json
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"incremental": false,
|
|
4
|
-
"target": "ES2018",
|
|
5
|
-
"outDir": "dist",
|
|
6
|
-
"sourceRoot": "src",
|
|
7
|
-
"moduleResolution": "node",
|
|
8
|
-
"module": "ES6",
|
|
9
|
-
"declaration": true,
|
|
10
|
-
"sourceMap": true,
|
|
11
|
-
"mapRoot": "./",
|
|
12
|
-
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
|
|
13
|
-
"resolveJsonModule": true /* Include modules imported with .json extension. */,
|
|
14
|
-
"strict": true /* Enable all strict type-checking options. */,
|
|
15
|
-
/* Strict Type-Checking Options */
|
|
16
|
-
// "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
|
|
17
|
-
// "strictNullChecks": true /* Enable strict null checks. */,
|
|
18
|
-
// "strictFunctionTypes": true /* Enable strict checking of function types. */,
|
|
19
|
-
// "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */,
|
|
20
|
-
// "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
|
|
21
|
-
// "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,
|
|
22
|
-
/* Additional Checks */
|
|
23
|
-
"noUnusedLocals": true /* Report errors on unused locals. */,
|
|
24
|
-
"noUnusedParameters": true /* Report errors on unused parameters. */,
|
|
25
|
-
"noImplicitReturns": false /* Report error when not all code paths in function return a value. */,
|
|
26
|
-
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
|
|
27
|
-
/* Debugging Options */
|
|
28
|
-
"traceResolution": false /* Report module resolution log messages. */,
|
|
29
|
-
"listEmittedFiles": false /* Print names of generated files part of the compilation. */,
|
|
30
|
-
"listFiles": false /* Print names of files part of the compilation. */,
|
|
31
|
-
"pretty": true /* Stylize errors and messages using color and context. */,
|
|
32
|
-
/* Experimental Options */
|
|
33
|
-
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
|
|
34
|
-
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
|
|
35
|
-
"lib": [
|
|
36
|
-
"ES2022",
|
|
37
|
-
"DOM"
|
|
38
|
-
],
|
|
39
|
-
"types": [],
|
|
40
|
-
"typeRoots": [
|
|
41
|
-
"node_modules/@types",
|
|
42
|
-
"src/types"
|
|
43
|
-
]
|
|
44
|
-
},
|
|
45
|
-
"include": [
|
|
46
|
-
"src/**/*.ts",
|
|
47
|
-
"examples/**/*.ts"
|
|
48
|
-
],
|
|
49
|
-
"exclude": [
|
|
50
|
-
"dist/**",
|
|
51
|
-
"build/**",
|
|
52
|
-
"node_modules/**",
|
|
53
|
-
"vitest.config.ts",
|
|
54
|
-
],
|
|
55
|
-
"compileOnSave": false,
|
|
56
|
-
}
|