@modulify/validator 0.1.0 → 0.2.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +324 -107
  3. package/dist/assert.cjs +66 -0
  4. package/dist/assert.d.ts +16 -0
  5. package/dist/assert.mjs +66 -0
  6. package/dist/assertions.cjs +190 -92
  7. package/dist/assertions.d.ts +58 -2
  8. package/dist/assertions.mjs +191 -93
  9. package/dist/checkers.d.ts +8 -0
  10. package/dist/combinators.cjs +341 -0
  11. package/dist/combinators.d.ts +17 -0
  12. package/dist/combinators.mjs +341 -0
  13. package/dist/constraints.d.ts +4 -0
  14. package/dist/extractors.d.ts +2 -0
  15. package/dist/index.cjs +172 -61
  16. package/dist/index.d.ts +10 -4
  17. package/dist/index.mjs +176 -64
  18. package/dist/json-schema.cjs +514 -0
  19. package/dist/json-schema.d.ts +14 -0
  20. package/dist/json-schema.mjs +514 -0
  21. package/dist/metadata.cjs +8 -0
  22. package/dist/metadata.cjs.js +130 -0
  23. package/dist/metadata.d.ts +8 -0
  24. package/dist/metadata.es.js +131 -0
  25. package/dist/metadata.mjs +8 -0
  26. package/dist/predicates.cjs +40 -5
  27. package/dist/predicates.d.ts +25 -3
  28. package/dist/predicates.mjs +40 -5
  29. package/dist/violations.d.ts +29 -0
  30. package/docs/en/00-index.md +14 -0
  31. package/docs/en/01-shape-api.md +348 -0
  32. package/docs/en/02-metadata-and-introspection.md +276 -0
  33. package/docs/en/03-violations.md +267 -0
  34. package/docs/en/04-json-schema-export.md +264 -0
  35. package/docs/en/05-public-api.md +123 -0
  36. package/docs/en/06-common-recipes.md +273 -0
  37. package/docs/en/07-ai-reference.md +215 -0
  38. package/docs/en/08-violation-code-types.md +241 -0
  39. package/docs/ru/00-index.md +15 -0
  40. package/docs/ru/01-shape-api.md +348 -0
  41. package/docs/ru/02-metadata-and-introspection.md +276 -0
  42. package/docs/ru/03-violations.md +267 -0
  43. package/docs/ru/04-json-schema-export.md +264 -0
  44. package/docs/ru/05-public-api.md +123 -0
  45. package/docs/ru/06-common-recipes.md +273 -0
  46. package/docs/ru/07-ai-reference.md +215 -0
  47. package/docs/ru/08-violation-code-types.md +241 -0
  48. package/docs/ru/README.md +371 -0
  49. package/package.json +51 -33
  50. package/types/index.d.ts +789 -30
  51. package/types/json-schema.d.ts +75 -0
  52. package/dist/assertions/Assert.d.ts +0 -2
  53. package/dist/assertions/HasLength.d.ts +0 -7
  54. package/dist/assertions/check.d.ts +0 -3
  55. package/dist/assertions/index.d.ts +0 -16
  56. package/dist/runners/Each.d.ts +0 -3
  57. package/dist/runners/HasProperties.d.ts +0 -6
  58. package/dist/runners/index.d.ts +0 -2
  59. package/dist/runners.cjs +0 -32
  60. package/dist/runners.d.ts +0 -2
  61. package/dist/runners.mjs +0 -32
package/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [0.2.1](https://github.com/modulify/validator/compare/v0.2.0...v0.2.1) (2026-03-09)
6
+
7
+ ## [0.2.0](https://github.com/modulify/validator/compare/v0.1.0...v0.2.0) (2026-03-09)
8
+
9
+
10
+ ### ⚠ BREAKING CHANGES
11
+
12
+ * Validation API was redesigned around typed tuples
13
+ * legacy assertion entrypoints were removed, assertion exports now use camelCase names, and violations now expose structured metadata via violates.{predicate,rule,args}.
14
+ * isObject now returns false on null values, added isShape predicate constructor for checking objects structures
15
+ * Injecting check utility into Assertion
16
+
17
+ ### Features
18
+
19
+ * Added JSON Schema export entrypoint ([0b3ec5b](https://github.com/modulify/validator/commit/0b3ec5b008418d7e7ceaa4a603341f24dc454b48))
20
+ * Added metadata and introspection API ([16ea412](https://github.com/modulify/validator/commit/16ea41268424dc878271227ad4e58cd2cd089c2d))
21
+ * Added simple runtime predicates for built-in values ([11c9f19](https://github.com/modulify/validator/commit/11c9f1996988e7c3ac45c8632caa1c7198ab2792))
22
+ * Added violation collection utilities ([64e9e36](https://github.com/modulify/validator/commit/64e9e36da63a672263f5ac48ef7b22e992dc6148))
23
+ * **assertions:** Added reusable assertion mixins for strings and numbers ([658dc9f](https://github.com/modulify/validator/commit/658dc9f32d1936fcd080969d55415aa5b450ec05))
24
+ * **combinators:** Added object-level shape refinement runtime ([2e2607f](https://github.com/modulify/validator/commit/2e2607f29211db48e5d46652ccef6b4cc185647d))
25
+ * **combinators:** Added tuple and record validators ([71742f9](https://github.com/modulify/validator/commit/71742f9216c7e20d6c3535af965dc2c134c5b4e8))
26
+ * **combinators:** Added union variant validators ([8b9e131](https://github.com/modulify/validator/commit/8b9e131a06a87e9bf462c492cbf8a6facacb7230))
27
+ * **combinators:** Extended fieldsMatch with nested selectors ([af5801e](https://github.com/modulify/validator/commit/af5801ed21dfa62e3f2ae88ad9e6db130ecbe293))
28
+ * Expanded metadata introspection contracts ([a188152](https://github.com/modulify/validator/commit/a1881526b2bd25d18584b478a1650a23d2a28f16))
29
+ * Injecting check utility into Assertion ([be8b22e](https://github.com/modulify/validator/commit/be8b22e23e968d39ade0198f85944b8f82e3183b))
30
+ * isObject now returns false on null values, added isShape predicate constructor for checking objects structures ([ee70741](https://github.com/modulify/validator/commit/ee70741e6f8ad4f2da0913187b1663b2dc1da6ed))
31
+ * redesign assertion API around structured violations ([acf16f3](https://github.com/modulify/validator/commit/acf16f39e26a38da944805dff8eb20ca416ad174))
32
+ * Shape object API was unified ([c43f6b6](https://github.com/modulify/validator/commit/c43f6b61b3cacf33fca224c9f4ef93c794145028))
33
+ * **types:** Added code-aware violation inference ([f9851db](https://github.com/modulify/validator/commit/f9851db28ac663a59a07fb6ca8396910a20929eb))
34
+ * Validation API was redesigned around typed tuples ([d645441](https://github.com/modulify/validator/commit/d6454412b6ac514ff3c31cce6641fabe11c844c3))
35
+
5
36
  ## [0.1.0](https://github.com/modulify/validator/compare/v0.0.2...v0.1.0) (2024-12-22)
6
37
 
7
38
 
package/README.md CHANGED
@@ -1,151 +1,368 @@
1
1
  # <img src="./logo.png" alt="Logo" width="36" /> `@modulify/validator`
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@modulify/validator.svg)](https://www.npmjs.com/package/@modulify/validator)
3
4
  [![codecov](https://codecov.io/gh/modulify/validator/branch/main/graph/badge.svg)](https://codecov.io/gh/modulify/validator)
4
5
  [![Tests Status](https://github.com/modulify/validator/actions/workflows/tests.yml/badge.svg)](https://github.com/modulify/validator/actions)
5
- [![npm version](https://badge.fury.io/js/%40modulify%2Fvalidator.svg)](https://www.npmjs.com/package/@modulify/validator)
6
6
 
7
- This library provides a declarative validation utility.
7
+ `@modulify/validator` is a small TypeScript validation library built around three separate layers:
8
8
 
9
- The utility does not include text messages in the generated violations but instead provides metadata that can
10
- be used to create a custom view for them.
9
+ - predicates for runtime checks and type narrowing;
10
+ - assertions for machine-readable validation failures;
11
+ - combinators for schema composition, including structural recursion over arrays and objects.
12
+
13
+ The project is intentionally centered on structured metadata instead of built-in human-readable error messages.
14
+
15
+ ## What This Project Is
16
+
17
+ This library is designed for cases where you want to:
18
+
19
+ - keep simple type guards useful on their own;
20
+ - validate nested data recursively;
21
+ - receive structured violation objects instead of text messages;
22
+ - decide later how those violations should be rendered or transformed.
23
+
24
+ Typical outputs of the validation layer can be mapped into:
25
+
26
+ - localized error messages;
27
+ - form field error state;
28
+ - API error payloads;
29
+ - analytics/debug data;
30
+ - custom UI or virtual DOM nodes.
31
+
32
+ ## Idea
33
+
34
+ The project separates two concerns that are often mixed in one abstraction.
35
+
36
+ ### Predicates
37
+
38
+ Predicates are small runtime checks that also act as TypeScript type guards.
39
+
40
+ They answer questions like:
41
+
42
+ - is this value a string?
43
+ - is this value an object with a specific shape?
44
+ - does this value satisfy a basic logical condition?
45
+
46
+ This layer is meant to stay simple and independently useful even outside the validation pipeline.
47
+
48
+ ### Validators And Assertions
49
+
50
+ Assertions are checks that can return a violation with structured metadata.
51
+
52
+ Instead of generating a text message, an assertion returns data that describes:
53
+
54
+ - what failed;
55
+ - where it failed;
56
+ - which semantic code failed;
57
+ - which arguments or bounds were involved.
58
+
59
+ That keeps presentation outside the library.
60
+
61
+ ### Why This Exists Alongside `zod`-Like Libraries
62
+
63
+ Libraries such as `zod`, `yup`, and similar schema-oriented tools are well known and solve a large class of validation problems well.
64
+
65
+ The goal of this project is different.
66
+
67
+ It is not primarily trying to be:
68
+
69
+ - a schema-definition DSL;
70
+ - a form library with built-in message semantics;
71
+ - an all-in-one parsing and presentation layer.
72
+
73
+ Instead, this project focuses on:
74
+
75
+ - small predicates for narrowing;
76
+ - a separate assertion layer for diagnostics;
77
+ - composable schema combinators;
78
+ - machine-readable violations that consumers can map however they want.
79
+
80
+ A short summary of the intended direction is:
81
+
82
+ > Type-safe predicates for narrowing, and validators for machine-readable diagnostics.
83
+
84
+ Or even shorter:
85
+
86
+ > No messages, only meaning.
11
87
 
12
88
  ## Installation
13
89
 
14
90
  Using `yarn`:
15
91
 
16
- ```
92
+ ```bash
17
93
  yarn add @modulify/validator
18
94
  ```
19
95
 
20
- or, using `npm`:
96
+ Using `npm`:
21
97
 
22
- ```
98
+ ```bash
23
99
  npm install @modulify/validator --save
24
100
  ```
25
101
 
26
- ## Usage
102
+ ## Quick Example
27
103
 
28
104
  ```typescript
29
105
  import {
30
- HasLength,
31
- HasProperties,
32
- IsDefined,
33
- IsString,
106
+ each,
107
+ shape,
108
+ exact,
109
+ hasLength,
110
+ isDefined,
111
+ isString,
112
+ nullable,
113
+ optional,
34
114
  validate,
35
115
  } from '@modulify/validator'
36
116
 
37
- const violations = await validate({
117
+ const [ok, validated, violations] = await validate({
38
118
  form: {
39
- nickname: '',
119
+ nickname: undefined,
120
+ title: null,
40
121
  password: '',
122
+ role: 'admin',
41
123
  },
42
- }, HasProperties({
124
+ }, shape({
43
125
  form: [
44
- IsDefined(),
45
- HasProperties({
46
- nickname: IsString.That(HasLength({ min: 4 })),
47
- password: IsString.That(HasLength({ min: 6 })),
126
+ isDefined,
127
+ shape({
128
+ nickname: optional([isString, hasLength({ min: 4 })]),
129
+ title: nullable(isString),
130
+ password: [isString, hasLength({ min: 6 })],
131
+ role: exact('admin'),
48
132
  }),
49
133
  ],
50
- })) /* [{
51
- by: '@modulify/validator/IsString',
52
- value: '',
53
- path: ['form', 'nickname'],
54
- reason: 'min',
55
- meta: 4,
56
- }, {
57
- by: '@modulify/validator/IsString',
58
- value: '',
59
- path: ['form', 'password'],
60
- reason: 'min',
61
- meta: 6,
62
- }] */
134
+ }))
135
+
136
+ if (ok) {
137
+ validated.form.nickname.toUpperCase()
138
+ } else {
139
+ console.log(violations)
140
+ }
63
141
  ```
64
142
 
65
- or (for synchronous validation):
143
+ Synchronous validation:
66
144
 
67
145
  ```typescript
68
- const violations = validate.sync({
146
+ const [ok, validated, violations] = validate.sync({
69
147
  form: {
70
148
  nickname: '',
71
149
  password: '',
72
150
  },
73
- }, HasProperties({
151
+ }, shape({
74
152
  form: [
75
- IsDefined(),
76
- HasProperties({
77
- nickname: IsString.That(HasLength({ min: 4 })),
78
- password: IsString.That(HasLength({ min: 6 })),
153
+ isDefined,
154
+ shape({
155
+ nickname: [isString, hasLength({ min: 4 })],
156
+ password: [isString, hasLength({ min: 6 })],
79
157
  }),
80
158
  ],
81
159
  }))
160
+
161
+ if (ok) {
162
+ validated.form.password.toUpperCase()
163
+ }
82
164
  ```
83
165
 
84
- ## Exported types
85
-
86
- * `Violation` – an object that contains information about a value – why it violates one or more constraints;
87
- includes following fields:
88
- * `value` – value that violates something;
89
- * `path` – path to the value, an empty array for scalar values and represents full path to the value in a complex
90
- object;
91
- * `violates` – indicator of the violated constraint;
92
- * `reason` – indicator of the reason why the constraint is violated;
93
- * `meta` – some data to describe the reason – what exactly the boundaries were not met;
94
- ```typescript
95
- import type { Violation } from '@modulify/validator/types'
96
- ```
97
- * `Predicate` – function that accepts a value and returns `true` or `false`; logical unit that is used for checking
98
- multiple things: type or if the value satisfies certain criteria; accepts generic argument `T` to specify
99
- the type of the value, if predicate returns `true`;
100
- ```typescript
101
- import type { Predicate } from '@modulify/validator/types'
102
- ```
103
- * `Assertion` – extension of the `Predicate` type that includes:
104
- * `fqn` – field – some predefined name that will be used as a value for the `violates` field of `Violation`;
105
- * `bail` – field – flag that interrupts further validation if the assertion fails;
106
- * `reason` – field, optional – string or symbol that is used to indicate, why assertion has failed;
107
- always added to a violation object, if present;
108
- * `meta` – field, optional – some metadata to use in further analysis; always added to a violation object, if present;
109
- * `That` – method – used to extend assertion with other assertions;
110
- * `also` – field – readonly array of other assertions that was attached by `That` method;
111
- ```typescript
112
- import type { Assertion } from '@modulify/validator/types'
113
- ```
114
-
115
- ## Exported members
116
-
117
- * `validate` – function that accepts a value for validation as the first argument, constraints as the second,
118
- and path to a value as the third (that is optional and used mostly for internal purposes, as validation is recursive);
119
- includes method `sync` that has the same arguments set but performs validation synchronously and throws error when
120
- finds an asynchronous constraint;
121
-
122
- * `Assert` – creates assertion from logical predicate:
123
- ```typescript
124
- const IsSomething = Assert(isSomething, {
125
- fqn: 'Some fqn',
126
- bail: true,
127
- })
128
- ```
129
- Arguments:
130
- * Logical predicate
131
- * Options, that includes `fqn`, `bail`, `reason` (optional), and `meta` (optional);
132
- * `HasLength` – checks length property of the specified string or array; can be configured with options:
133
- * `exact` – if the length should be exactly equal the specified value;
134
- * `max` – if the length should be equal or less than the specified value;
135
- * `min` – if the length should be equal or greater than the specified value;
136
- * `bail` – set this to true if you need to interrupt further validation if the assertion fails;
137
- * `IsBoolean` – checks if the value is **boolean**; interrupts further validation if fails;
138
- * `IsDate` – checks if the value is Date **object**; interrupts further validation if fails;
139
- * `IsDefined` – checks if the value is **not undefined**; interrupts further validation if fails;
140
- * `IsEmail` – checks if the value is a **valid email**; interrupts further validation if fails;
141
- * `IsNull` – checks if the value is **null**; interrupts further validation if fails;
142
- * `IsNumber` – checks if the value is **number**; interrupts further validation if fails;
143
- * `IsString` – checks if the value is **string**; interrupts further validation if fails;
144
- * `IsSymbol` – checks if the value is a **symbol**; interrupts further validation if fails;
145
- * `OneOf` – checks if the value equal to one of the specified values; can be configured with:
146
- * `equalTo` – predicate f(a, b) that checks if two values are equal or not;
147
- by default the strict `===` comparison is used
148
- * `bail` – set this to true if you need to interrupt further validation if the assertion fails;
149
-
150
- * `Each` – a runner that runs validation for each element in array;
151
- * `HasProperties` – a runner that runs object's structure check.
166
+ Sync narrowing of the original variable:
167
+
168
+ ```typescript
169
+ import {
170
+ isDefined,
171
+ isString,
172
+ matches,
173
+ } from '@modulify/validator'
174
+
175
+ const value: unknown = 'nickname'
176
+
177
+ if (matches.sync(value, [isDefined, isString])) {
178
+ value.toUpperCase()
179
+ }
180
+ ```
181
+
182
+ Typed success branch directly from `validate`:
183
+
184
+ ```typescript
185
+ import {
186
+ shape,
187
+ isDefined,
188
+ isString,
189
+ validate,
190
+ } from '@modulify/validator'
191
+
192
+ const schema = shape({
193
+ name: [isDefined, isString],
194
+ })
195
+
196
+ const [ok, validated, violations] = await validate({ name: 'Kirill' }, schema)
197
+
198
+ if (ok) {
199
+ validated.name.toUpperCase()
200
+ } else {
201
+ console.log(violations)
202
+ }
203
+ ```
204
+
205
+ ## Shape API
206
+
207
+ `shape(...)` is the reusable object-shape API. It validates nested record-like objects and exposes small immutable helpers such as `strict()`, `pick()`, `omit()`, `partial()`, `extend()`, `merge()`, `refine()`, and `fieldsMatch(...)`.
208
+
209
+ ```typescript
210
+ import {
211
+ isString,
212
+ optional,
213
+ shape,
214
+ validate,
215
+ } from '@modulify/validator'
216
+
217
+ const profile = shape({
218
+ id: isString,
219
+ nickname: optional(isString),
220
+ })
221
+
222
+ const [ok] = validate.sync({
223
+ id: 'u1',
224
+ nickname: 'neo',
225
+ }, profile)
226
+ ```
227
+
228
+ Detailed guides:
229
+
230
+ - [Shape API Guide](./docs/en/01-shape-api.md)
231
+
232
+ ## Metadata And Introspection
233
+
234
+ `meta(...)` attaches machine-readable metadata to any constraint, and `describe(...)` returns a stable recursive descriptor tree for built-in constraints and compatible custom validators.
235
+
236
+ ```typescript
237
+ import {
238
+ describe,
239
+ isString,
240
+ meta,
241
+ optional,
242
+ shape,
243
+ } from '@modulify/validator'
244
+
245
+ const registration = meta(shape({
246
+ email: meta(isString, {
247
+ title: 'Email',
248
+ placeholder: 'name@example.com',
249
+ }),
250
+ nickname: optional(isString),
251
+ }).strict(), {
252
+ title: 'Registration form',
253
+ })
254
+
255
+ const node = describe(registration)
256
+ ```
257
+
258
+ Detailed guides:
259
+
260
+ - [Metadata And Introspection Guide](./docs/en/02-metadata-and-introspection.md)
261
+ - [Violation Code Types Guide](./docs/en/08-violation-code-types.md)
262
+
263
+ ## Mental Model
264
+
265
+ A practical way to think about the library is:
266
+
267
+ - predicates answer: does this value satisfy condition `X`?
268
+ - assertions answer: if not, what exactly failed?
269
+ - combinators answer: how should constraints be combined into a bigger schema, including recursive object and array traversal?
270
+
271
+ In the current API this usually looks like:
272
+
273
+ - leaf checks with assertions such as `isString`, `isDefined`, `hasLength`, `oneOf`;
274
+ - schema composition with combinators such as `exact`, `optional`, `nullable`, `nullish`, `shape(...)`, `each(...)`;
275
+ - typed validation through `validate(...)` or `validate.sync(...)`;
276
+ - narrowing of the original sync variable through `matches.sync(...)`.
277
+
278
+ ## Violations
279
+
280
+ `validate(...)` returns machine-readable `Violation[]`, and `collection(...)` can wrap that list into a small helper API for exact path lookups and tree traversal.
281
+
282
+ ```typescript
283
+ import {
284
+ collection,
285
+ isString,
286
+ shape,
287
+ validate,
288
+ } from '@modulify/validator'
289
+
290
+ const [ok, validated, violations] = validate.sync({
291
+ profile: {
292
+ email: '',
293
+ },
294
+ }, shape({
295
+ profile: shape({
296
+ email: isString,
297
+ }),
298
+ }))
299
+
300
+ const errors = collection(violations)
301
+
302
+ const rootErrors = errors.at([])
303
+ const emailErrors = errors.at(['profile', 'email'])
304
+ ```
305
+
306
+ Detailed guides:
307
+
308
+ - [Violations Guide](./docs/en/03-violations.md)
309
+ - [Violation Code Types Guide](./docs/en/08-violation-code-types.md)
310
+
311
+ ## JSON Schema Export
312
+
313
+ `toJsonSchema(...)` derives a JSON Schema view from the same public descriptor tree returned by `describe(...)`.
314
+
315
+ ```typescript
316
+ import {
317
+ isNumber,
318
+ isString,
319
+ meta,
320
+ optional,
321
+ shape,
322
+ } from '@modulify/validator'
323
+ import { toJsonSchema } from '@modulify/validator/json-schema'
324
+
325
+ const profile = meta(shape({
326
+ email: meta(isString, {
327
+ title: 'Email',
328
+ format: 'email',
329
+ }),
330
+ age: optional(isNumber),
331
+ }).strict(), {
332
+ title: 'Profile',
333
+ })
334
+
335
+ const jsonSchema = toJsonSchema(profile)
336
+ ```
337
+
338
+ Detailed guides:
339
+
340
+ - [JSON Schema Export Guide](./docs/en/04-json-schema-export.md)
341
+
342
+ ## Public API
343
+
344
+ The detailed public API guide covers root exports, specialized subpath exports, the validation result tuple, and how the package surface is split between validation, predicates, violations, metadata, and JSON Schema export.
345
+
346
+ Detailed guides:
347
+
348
+ - [Public API Guide](./docs/en/05-public-api.md)
349
+
350
+ ## Recipes And AI Reference
351
+
352
+ Two additional guides are useful when you want faster practical navigation instead of reading the whole conceptual set front to back.
353
+
354
+ - [Common Recipes](./docs/en/06-common-recipes.md) - task-oriented examples for payload validation, wrapper choice, reusable shapes, form error mapping, and JSON Schema export.
355
+ - [AI Reference](./docs/en/07-ai-reference.md) - compact contract summary for agents, tooling, and quick semantic lookup.
356
+
357
+ ## Notes
358
+
359
+ - Assertions return structured metadata instead of messages.
360
+ - Combinators are thin schema-building helpers layered on top of assertions and validators; `each` and `shape` are structural combinators in this model.
361
+ - Predicates are intended to stay useful independently from the validation layer.
362
+ - The library is easier to use when one stable violation format is kept across the whole project.
363
+ - `validate(...)` narrows the `validated` tuple item, not the original input variable.
364
+ - To narrow the original variable in sync code, use `matches.sync(...)`.
365
+
366
+ ## Translations
367
+
368
+ - [Russian](./docs/ru/README.md)
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const metadata = require("./metadata.cjs.js");
4
+ const assert = (predicate, meta, constraints = []) => {
5
+ const assertionCode = meta.code ?? meta.name;
6
+ const assertionArgs = meta.args ?? [];
7
+ const violationSubject = {
8
+ kind: "assertion",
9
+ name: meta.name,
10
+ code: assertionCode,
11
+ args: assertionArgs
12
+ };
13
+ const assertion = ((value) => {
14
+ if (!predicate(value)) {
15
+ return {
16
+ value,
17
+ violates: violationSubject
18
+ };
19
+ }
20
+ for (const [extract, check, code, ...args] of constraints) {
21
+ if (!check(extract(value), ...args)) {
22
+ const constraintSubject = {
23
+ kind: "assertion",
24
+ name: meta.name,
25
+ code,
26
+ args
27
+ };
28
+ return {
29
+ value,
30
+ violates: constraintSubject
31
+ };
32
+ }
33
+ }
34
+ return null;
35
+ });
36
+ Object.defineProperties(assertion, {
37
+ name: {
38
+ configurable: true,
39
+ value: meta.name
40
+ },
41
+ bail: {
42
+ enumerable: true,
43
+ value: meta.bail
44
+ },
45
+ constraints: {
46
+ enumerable: true,
47
+ value: constraints
48
+ },
49
+ check: {
50
+ enumerable: true,
51
+ value: (value) => predicate(value) && (!constraints.length || constraints.every(([extract, check, , ...args]) => check(extract(value), ...args)))
52
+ }
53
+ });
54
+ return metadata.attachConstraintDescriptor(assertion, () => ({
55
+ kind: "assertion",
56
+ name: meta.name,
57
+ bail: meta.bail,
58
+ code: assertionCode,
59
+ args: assertionArgs,
60
+ constraints: constraints.map(([, , code, ...args]) => ({
61
+ code,
62
+ args
63
+ }))
64
+ }));
65
+ };
66
+ exports.assert = assert;
@@ -0,0 +1,16 @@
1
+ import { Assertion, AssertionConstraint, Predicate } from '../types';
2
+ type AssertMeta = {
3
+ name: string;
4
+ bail: boolean;
5
+ code?: string;
6
+ args?: readonly unknown[];
7
+ };
8
+ type ResolveAssertionCode<Name extends string, Code extends string | undefined> = Code extends string ? Code : Name;
9
+ type ResolveAssertionArgs<Args extends readonly unknown[] | undefined> = Args extends readonly unknown[] ? Args : [];
10
+ export declare const assert: <T, const Name extends string, const Bail extends boolean, const Code extends string | undefined = undefined, const Args extends readonly unknown[] | undefined = undefined, const C extends readonly AssertionConstraint[] = []>(predicate: Predicate<T>, meta: AssertMeta & {
11
+ name: Name;
12
+ bail: Bail;
13
+ code?: Code;
14
+ args?: Args;
15
+ }, constraints?: C) => Assertion<T, C, ResolveAssertionCode<Name, Code>, ResolveAssertionArgs<Args>, Name>;
16
+ export {};
@@ -0,0 +1,66 @@
1
+ import { e as attachConstraintDescriptor } from "./metadata.es.js";
2
+ const assert = (predicate, meta, constraints = []) => {
3
+ const assertionCode = meta.code ?? meta.name;
4
+ const assertionArgs = meta.args ?? [];
5
+ const violationSubject = {
6
+ kind: "assertion",
7
+ name: meta.name,
8
+ code: assertionCode,
9
+ args: assertionArgs
10
+ };
11
+ const assertion = ((value) => {
12
+ if (!predicate(value)) {
13
+ return {
14
+ value,
15
+ violates: violationSubject
16
+ };
17
+ }
18
+ for (const [extract, check, code, ...args] of constraints) {
19
+ if (!check(extract(value), ...args)) {
20
+ const constraintSubject = {
21
+ kind: "assertion",
22
+ name: meta.name,
23
+ code,
24
+ args
25
+ };
26
+ return {
27
+ value,
28
+ violates: constraintSubject
29
+ };
30
+ }
31
+ }
32
+ return null;
33
+ });
34
+ Object.defineProperties(assertion, {
35
+ name: {
36
+ configurable: true,
37
+ value: meta.name
38
+ },
39
+ bail: {
40
+ enumerable: true,
41
+ value: meta.bail
42
+ },
43
+ constraints: {
44
+ enumerable: true,
45
+ value: constraints
46
+ },
47
+ check: {
48
+ enumerable: true,
49
+ value: (value) => predicate(value) && (!constraints.length || constraints.every(([extract, check, , ...args]) => check(extract(value), ...args)))
50
+ }
51
+ });
52
+ return attachConstraintDescriptor(assertion, () => ({
53
+ kind: "assertion",
54
+ name: meta.name,
55
+ bail: meta.bail,
56
+ code: assertionCode,
57
+ args: assertionArgs,
58
+ constraints: constraints.map(([, , code, ...args]) => ({
59
+ code,
60
+ args
61
+ }))
62
+ }));
63
+ };
64
+ export {
65
+ assert
66
+ };