@thi.ng/validate 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ <!-- This file is generated - DO NOT EDIT! -->
2
+ <!-- Please see: https://codeberg.org/thi.ng/umbrella/src/branch/develop/CONTRIBUTING.md#changes-to-readme-files -->
3
+ # ![@thi.ng/validate](https://codeberg.org/thi.ng/umbrella/media/branch/develop/assets/banners/thing-validate.svg?9ff0fc13)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@thi.ng/validate.svg)](https://www.npmjs.com/package/@thi.ng/validate)
6
+ ![npm downloads](https://img.shields.io/npm/dm/@thi.ng/validate.svg)
7
+ [![Mastodon Follow](https://img.shields.io/mastodon/follow/109331703950160316?domain=https%3A%2F%2Fmastodon.thi.ng&style=social)](https://mastodon.thi.ng/@toxi)
8
+
9
+ > [!NOTE]
10
+ > This is one of 215 standalone projects, maintained as part
11
+ > of the [@thi.ng/umbrella](https://codeberg.org/thi.ng/umbrella/) ecosystem
12
+ > and anti-framework.
13
+ >
14
+ > 🚀 Please help me to work full-time on these projects by [sponsoring
15
+ > me](https://codeberg.org/thi.ng/umbrella/src/branch/develop/CONTRIBUTING.md#donations).
16
+ > Thank you! ❤️
17
+
18
+ - [About](#about)
19
+ - [Built-in validators](#built-in-validators)
20
+ - [Combinators](#combinators)
21
+ - [Status](#status)
22
+ - [Installation](#installation)
23
+ - [Dependencies](#dependencies)
24
+ - [API](#api)
25
+ - [Authors](#authors)
26
+ - [License](#license)
27
+
28
+ ## About
29
+
30
+ Functional, composable, fully extensible, predicate-based value validation with customizable error messages.
31
+
32
+ Based on ideas from older `thi.ng/validate-x` Clojure/ClojureScript library...
33
+
34
+ Basic usage:
35
+
36
+ ```ts
37
+ import * as v from "@thi.ng/validate";
38
+
39
+ // build validation function to check if a value is...
40
+ const check = v.validator(
41
+ // a plain object
42
+ v.isObject(),
43
+ // and its keys are matching given validation criteria:
44
+ v.hasKeysOf({
45
+ // number in [0,1000] range
46
+ id: [v.isNumber(), v.isInRange(1, 1000)],
47
+ // optional title string (i.e. nullish values allowed)
48
+ title: v.optional(v.isString()),
49
+ // enum type
50
+ type: v.isEnum(["file", "url", "record"])
51
+ })
52
+ );
53
+
54
+ try {
55
+
56
+ check({ id: 123, title: "abc", type: "file" });
57
+ // true
58
+
59
+ // validation will fail:
60
+ check({ id: 999, type: "foo" });
61
+
62
+ } catch(e) {
63
+ console.warn(e);
64
+ }
65
+
66
+ // validation error: required value to be one of: file, url, record (key: type)
67
+ ```
68
+
69
+ ### Built-in validators
70
+
71
+ - [`hasKeysOf()`](https://docs.thi.ng/umbrella/validate/functions/hasKeysOf.html)
72
+ - [`hasRequiredKeys()`](https://docs.thi.ng/umbrella/validate/functions/hasRequiredKeys.html)
73
+ - [`isArray()`](https://docs.thi.ng/umbrella/validate/functions/isArray.html)
74
+ - [`isArrayOf()`](https://docs.thi.ng/umbrella/validate/functions/isArrayOf.html)
75
+ - [`isBoolean()`](https://docs.thi.ng/umbrella/validate/functions/isBoolean.html)
76
+ - [`isDate()`](https://docs.thi.ng/umbrella/validate/functions/isDate.html)
77
+ - [`isEnum()`](https://docs.thi.ng/umbrella/validate/functions/isEnum.html)
78
+ - [`isInRange()`](https://docs.thi.ng/umbrella/validate/functions/isInRange.html)
79
+ - [`isLength()`](https://docs.thi.ng/umbrella/validate/functions/isLength.html)
80
+ - [`isMaxLength()`](https://docs.thi.ng/umbrella/validate/functions/isMaxLength.html)
81
+ - [`isMinLength()`](https://docs.thi.ng/umbrella/validate/functions/isMinLength.html)
82
+ - [`isMinMaxLength()`](https://docs.thi.ng/umbrella/validate/functions/isMinMaxLength.html)
83
+ - [`isNegative()`](https://docs.thi.ng/umbrella/validate/functions/isNegative.html)
84
+ - [`isNonNegative()`](https://docs.thi.ng/umbrella/validate/functions/isNonNegative.html)
85
+ - [`isNonPositive()`](https://docs.thi.ng/umbrella/validate/functions/isNonPositive.html)
86
+ - [`isNullish()`](https://docs.thi.ng/umbrella/validate/functions/isNullish.html)
87
+ - [`isNumber()`](https://docs.thi.ng/umbrella/validate/functions/isNumber.html)
88
+ - [`isObject()`](https://docs.thi.ng/umbrella/validate/functions/isObject.html)
89
+ - [`isObjectOf()`](https://docs.thi.ng/umbrella/validate/functions/isObjectOf.html)
90
+ - [`isPositive()`](https://docs.thi.ng/umbrella/validate/functions/isPositive.html)
91
+ - [`isRegExp()`](https://docs.thi.ng/umbrella/validate/functions/isRegExp.html)
92
+ - [`isString()`](https://docs.thi.ng/umbrella/validate/functions/isString.html)
93
+ - [`isUndefined()`](https://docs.thi.ng/umbrella/validate/functions/isUndefined.html)
94
+ - [`matchesRegexp()`](https://docs.thi.ng/umbrella/validate/functions/matchesRegexp.html)
95
+
96
+ ### Combinators
97
+
98
+ - [`oneOf()`](https://docs.thi.ng/umbrella/validate/functions/oneOf.html)
99
+ - [`optional()`](https://docs.thi.ng/umbrella/validate/functions/optional.html)
100
+
101
+ ## Status
102
+
103
+ **ALPHA** - bleeding edge / work-in-progress
104
+
105
+ [Search or submit any issues for this package](https://codeberg.org/thi.ng/umbrella/issues?q=%5Bvalidate%5D)
106
+
107
+ ## Installation
108
+
109
+ ```bash
110
+ yarn add @thi.ng/validate
111
+ ```
112
+
113
+ ESM import:
114
+
115
+ ```ts
116
+ import * as val from "@thi.ng/validate";
117
+ ```
118
+
119
+ Browser ESM import:
120
+
121
+ ```html
122
+ <script type="module" src="https://esm.run/@thi.ng/validate"></script>
123
+ ```
124
+
125
+ [JSDelivr documentation](https://www.jsdelivr.com/)
126
+
127
+ For Node.js REPL:
128
+
129
+ ```js
130
+ const val = await import("@thi.ng/validate");
131
+ ```
132
+
133
+ Package sizes (brotli'd, pre-treeshake): ESM: 1021 bytes
134
+
135
+ ## Dependencies
136
+
137
+ - [@thi.ng/api](https://codeberg.org/thi.ng/umbrella/src/branch/develop/packages/api)
138
+ - [@thi.ng/checks](https://codeberg.org/thi.ng/umbrella/src/branch/develop/packages/checks)
139
+ - [@thi.ng/errors](https://codeberg.org/thi.ng/umbrella/src/branch/develop/packages/errors)
140
+
141
+ Note: @thi.ng/api is in _most_ cases a type-only import (not used at runtime)
142
+
143
+ ## API
144
+
145
+ [Generated API docs](https://docs.thi.ng/umbrella/validate/)
146
+
147
+ ## Authors
148
+
149
+ - [Karsten Schmidt](https://thi.ng)
150
+
151
+ If this project contributes to an academic publication, please cite it as:
152
+
153
+ ```bibtex
154
+ @misc{thing-validate,
155
+ title = "@thi.ng/validate",
156
+ author = "Karsten Schmidt",
157
+ note = "https://thi.ng/validate",
158
+ year = 2026
159
+ }
160
+ ```
161
+
162
+ ## License
163
+
164
+ &copy; 2026 Karsten Schmidt // Apache License 2.0
package/api.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { Fn, Predicate } from "@thi.ng/api";
2
+ export interface Validator {
3
+ /**
4
+ * Optional coercion function, applied as pre-processor for {@link Validator.valid}.
5
+ */
6
+ coerce?: Fn<any, any>;
7
+ /**
8
+ * Validation predicate. If the function returns false, the
9
+ * {@link volidator} wrapper will throw an error.
10
+ */
11
+ valid: Predicate<any>;
12
+ /**
13
+ * Optional error message (or function to produce such).
14
+ */
15
+ msg?: string | Fn<any, string>;
16
+ }
17
+ //# sourceMappingURL=api.d.ts.map
package/api.js ADDED
File without changes
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./api.js";
2
+ export * from "./validators.js";
3
+ //# sourceMappingURL=index.d.ts.map
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./api.js";
2
+ export * from "./validators.js";
package/package.json ADDED
@@ -0,0 +1,89 @@
1
+ {
2
+ "name": "@thi.ng/validate",
3
+ "version": "0.1.0",
4
+ "description": "Functional, composable, fully extensible, predicate-based value validation with customizable error messages",
5
+ "type": "module",
6
+ "module": "./index.js",
7
+ "typings": "./index.d.ts",
8
+ "sideEffects": false,
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://codeberg.org/thi.ng/umbrella.git",
12
+ "directory": "packages/validate"
13
+ },
14
+ "homepage": "https://thi.ng/validate",
15
+ "funding": [
16
+ {
17
+ "type": "github",
18
+ "url": "https://github.com/sponsors/postspectacular"
19
+ },
20
+ {
21
+ "type": "patreon",
22
+ "url": "https://patreon.com/thing_umbrella"
23
+ },
24
+ {
25
+ "type": "liberapay",
26
+ "url": "https://liberapay.com/thi.ng"
27
+ }
28
+ ],
29
+ "author": "Karsten Schmidt (https://thi.ng)",
30
+ "license": "Apache-2.0",
31
+ "scripts": {
32
+ "build": "yarn build:esbuild && yarn build:decl",
33
+ "build:decl": "tsc --declaration --emitDeclarationOnly",
34
+ "build:esbuild": "esbuild --format=esm --platform=neutral --target=es2022 --tsconfig=tsconfig.json --outdir=. src/**/*.ts",
35
+ "clean": "bun ../../tools/src/clean-package.ts",
36
+ "doc": "typedoc --options ../../typedoc.json --out doc src/index.ts",
37
+ "doc:readme": "bun ../../tools/src/module-stats.ts && bun ../../tools/src/readme.ts",
38
+ "pub": "npm publish --access public",
39
+ "test": "bun test",
40
+ "tool:tangle": "../../node_modules/.bin/tangle src/**/*.ts"
41
+ },
42
+ "dependencies": {
43
+ "@thi.ng/api": "^8.12.20",
44
+ "@thi.ng/checks": "^3.9.0",
45
+ "@thi.ng/errors": "^2.6.9"
46
+ },
47
+ "devDependencies": {
48
+ "esbuild": "^0.28.0",
49
+ "typedoc": "^0.28.18",
50
+ "typescript": "^5.9.3"
51
+ },
52
+ "keywords": [
53
+ "composition",
54
+ "functional",
55
+ "predicate",
56
+ "typescript",
57
+ "validate"
58
+ ],
59
+ "publishConfig": {
60
+ "access": "public"
61
+ },
62
+ "browser": {
63
+ "process": false,
64
+ "setTimeout": false
65
+ },
66
+ "engines": {
67
+ "node": ">=18"
68
+ },
69
+ "files": [
70
+ "./*.js",
71
+ "./*.d.ts"
72
+ ],
73
+ "exports": {
74
+ ".": {
75
+ "default": "./index.js"
76
+ },
77
+ "./api": {
78
+ "default": "./api.js"
79
+ },
80
+ "./validators": {
81
+ "default": "./validators.js"
82
+ }
83
+ },
84
+ "thi.ng": {
85
+ "status": "alpha",
86
+ "year": 2026
87
+ },
88
+ "gitHead": "92be63f24030506f09d6d156804da2798c381dc4"
89
+ }
@@ -0,0 +1,133 @@
1
+ import type { Validator } from "./api.js";
2
+ /**
3
+ * Error type thrown by validation functions.
4
+ */
5
+ export declare const ValidationError: {
6
+ new (msg?: string | undefined): {
7
+ origMessage: string;
8
+ name: string;
9
+ message: string;
10
+ stack?: string;
11
+ cause?: unknown;
12
+ };
13
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
14
+ prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
15
+ stackTraceLimit: number;
16
+ };
17
+ /**
18
+ * Higher order function. Takes a number of {@link Validator}s and returns a
19
+ * function which when called, applies validators in sequence to provided value.
20
+ * Returns true if all validators passed, otherwise throws an error if any of
21
+ * the validators fails.
22
+ *
23
+ * @example
24
+ * ```ts tangle:../export/validator.ts
25
+ * import * as v from "@thi.ng/validate";
26
+ *
27
+ * // build validation function to check if a value is...
28
+ * const check = v.validator(
29
+ * // a plain object
30
+ * v.isObject(),
31
+ * // its keys are matching given validation criteria:
32
+ * v.hasKeysOf({
33
+ * // number in [0,1000] range
34
+ * id: [v.isNumber(), v.isInRange(1,1000)],
35
+ * // optional title string (i.e. nullish values allowed)
36
+ * title: v.optional(v.isString()),
37
+ * // enum type
38
+ * type: v.isEnum(["file", "url", "record"])
39
+ * })
40
+ * );
41
+ *
42
+ * try {
43
+ * check({ id: 123, title: "abc", type: "file" });
44
+ * // true
45
+ *
46
+ * // validation will fail:
47
+ * check({ id: 999, type: "foo" })
48
+ * } catch(e) {
49
+ * console.warn(e);
50
+ * }
51
+ *
52
+ * // validation error: required value to be one of: file, url, record (key: type)
53
+ * ```
54
+ *
55
+ * @param validators
56
+ */
57
+ export declare const validator: (...validators: Validator[]) => (x: any) => boolean;
58
+ /**
59
+ * Higher order validator. Takes an existing validator and returns an augmented
60
+ * version which also allows value to be nullish.
61
+ *
62
+ * @param validator
63
+ */
64
+ export declare const optional: ({ coerce, valid, msg }: Validator) => Validator;
65
+ /**
66
+ * Higher order validator. Takes a numer of validators and returns a new one
67
+ * which will apply the validators in given order, but return when the first one
68
+ * succeeds and only fails if all of the validators failed.
69
+ *
70
+ * @param validators
71
+ */
72
+ export declare const oneOf: (validators: (Validator | Validator[])[]) => Validator;
73
+ /**
74
+ * Returns validator to check if value is undefined.
75
+ *
76
+ * @param msg
77
+ */
78
+ export declare const isUndefined: (msg?: Validator["msg"]) => Validator;
79
+ /**
80
+ * Returns validator to check if value is nullish.
81
+ *
82
+ * @param msg
83
+ */
84
+ export declare const isNullish: (msg?: Validator["msg"]) => Validator;
85
+ export declare const isBoolean: (msg?: Validator["msg"]) => Validator;
86
+ export declare const isNumber: (msg?: Validator["msg"]) => Validator;
87
+ export declare const isString: (msg?: Validator["msg"]) => Validator;
88
+ export declare const isDate: (msg?: Validator["msg"]) => Validator;
89
+ export declare const isRegExp: (msg?: Validator["msg"]) => Validator;
90
+ export declare const isObject: (msg?: Validator["msg"]) => Validator;
91
+ /**
92
+ * Returns validator to check if value is a plain object and the values of all
93
+ * its keys are matching given validators.
94
+ *
95
+ * @param validators
96
+ * @param msg
97
+ */
98
+ export declare const isObjectOf: (validators: Validator | Validator[], msg?: Validator["msg"]) => Validator;
99
+ export declare const isArray: (msg?: Validator["msg"]) => Validator;
100
+ export declare const isArrayOf: (validators: Validator | Validator[], msg?: Validator["msg"]) => Validator;
101
+ export declare const hasRequiredKeys: (keys: string[], msg?: Validator["msg"]) => Validator;
102
+ export declare const hasKeysOf: (validators: Record<PropertyKey, Validator | Validator[]>) => Validator;
103
+ /**
104
+ * Returns validator to check if value is one of the given options.
105
+ *
106
+ * @param opts
107
+ * @param msg
108
+ */
109
+ export declare const isEnum: <T>(opts: T[], msg?: Validator["msg"]) => Validator;
110
+ /**
111
+ * Returns validator to check if value is in given closed [min,max] interval.
112
+ *
113
+ * @param min
114
+ * @param max
115
+ * @param msg
116
+ */
117
+ export declare const isInRange: <T extends number | string>(min: T, max: T, msg?: Validator["msg"]) => Validator;
118
+ export declare const isPositive: (msg?: Validator["msg"]) => Validator;
119
+ export declare const isNegative: (msg?: Validator["msg"]) => Validator;
120
+ export declare const isNonPositive: (msg?: Validator["msg"]) => Validator;
121
+ export declare const isNonNegative: (msg?: Validator["msg"]) => Validator;
122
+ export declare const isLength: (n: number, msg?: Validator["msg"]) => Validator;
123
+ export declare const isMinLength: (n: number, msg?: Validator["msg"]) => Validator;
124
+ export declare const isMaxLength: (n: number, msg?: Validator["msg"]) => Validator;
125
+ export declare const isMinMaxLength: (min: number, max: number, msg?: Validator["msg"]) => Validator;
126
+ /**
127
+ * Returns validator to check if value is a string and matches given regexp.
128
+ *
129
+ * @param re
130
+ * @param msg
131
+ */
132
+ export declare const matchesRegexp: (re: RegExp, msg?: Validator["msg"]) => Validator;
133
+ //# sourceMappingURL=validators.d.ts.map
package/validators.js ADDED
@@ -0,0 +1,185 @@
1
+ import { isArray as $isArray } from "@thi.ng/checks/is-array";
2
+ import { isArrayOf as $isArrayOf } from "@thi.ng/checks/is-array-of";
3
+ import { isBoolean as $isBoolean } from "@thi.ng/checks/is-boolean";
4
+ import { isDate as $isDate } from "@thi.ng/checks/is-date";
5
+ import { isFunction } from "@thi.ng/checks/is-function";
6
+ import { isNumber as $isNumber } from "@thi.ng/checks/is-number";
7
+ import { isObjectOf as $isObjectOf } from "@thi.ng/checks/is-object-of";
8
+ import { isPlainObject } from "@thi.ng/checks/is-plain-object";
9
+ import { isRegExp as $isRegExp } from "@thi.ng/checks/is-regexp";
10
+ import { isString as $isString } from "@thi.ng/checks/is-string";
11
+ import { defError } from "@thi.ng/errors/deferror";
12
+ const ValidationError = defError(() => `validation error`);
13
+ const validator = (...validators) => (x) => {
14
+ for (let { coerce, valid, msg } of validators) {
15
+ if (coerce) x = coerce(x);
16
+ if (!valid(x)) {
17
+ if (isFunction(msg)) msg = msg(x);
18
+ throw new ValidationError(msg ?? "failed validation");
19
+ }
20
+ }
21
+ return true;
22
+ };
23
+ const optional = ({ coerce, valid, msg }) => ({
24
+ coerce,
25
+ valid: (x) => x == null || valid(x),
26
+ msg
27
+ });
28
+ const __asArray = (v) => $isArray(v) ? v : [v];
29
+ const oneOf = (validators) => {
30
+ let lastMsg;
31
+ return {
32
+ valid: (x) => {
33
+ lastMsg = void 0;
34
+ for (let v of validators) {
35
+ try {
36
+ return validator(...__asArray(v))(x);
37
+ } catch (e) {
38
+ lastMsg = e.origMessage ?? e.message;
39
+ }
40
+ }
41
+ return false;
42
+ },
43
+ msg: () => lastMsg ?? "invalid value"
44
+ };
45
+ };
46
+ const isUndefined = (msg) => ({
47
+ valid: (x) => x === void 0,
48
+ msg: msg ?? `expected undefined value`
49
+ });
50
+ const isNullish = (msg) => ({
51
+ valid: (x) => x === null,
52
+ msg: msg ?? `expected nullish value`
53
+ });
54
+ const isBoolean = (msg) => ({
55
+ valid: $isBoolean,
56
+ msg: msg ?? `required boolean value`
57
+ });
58
+ const isNumber = (msg) => ({
59
+ valid: $isNumber,
60
+ msg: msg ?? `required number value`
61
+ });
62
+ const isString = (msg) => ({
63
+ valid: $isString,
64
+ msg: msg ?? `required string value`
65
+ });
66
+ const isDate = (msg) => ({
67
+ valid: $isDate,
68
+ msg: msg ?? `required date value`
69
+ });
70
+ const isRegExp = (msg) => ({
71
+ valid: $isRegExp,
72
+ msg: msg ?? `required regexp value`
73
+ });
74
+ const isObject = (msg) => ({
75
+ valid: isPlainObject,
76
+ msg: msg ?? `required object value`
77
+ });
78
+ const isObjectOf = (validators, msg) => ({
79
+ valid: $isObjectOf(validator(...__asArray(validators))),
80
+ msg: msg ?? `required object value`
81
+ });
82
+ const isArray = (msg) => ({
83
+ valid: $isArray,
84
+ msg: msg ?? `required array value`
85
+ });
86
+ const isArrayOf = (validators, msg) => ({
87
+ valid: $isArrayOf(validator(...__asArray(validators))),
88
+ msg: msg ?? `required array value`
89
+ });
90
+ const hasRequiredKeys = (keys, msg) => ({
91
+ valid: (x) => {
92
+ const $keys = new Set(Object.keys(x));
93
+ return keys.every((k) => $keys.has(k));
94
+ },
95
+ msg: msg ?? `required keys: ${keys.join(", ")}`
96
+ });
97
+ const hasKeysOf = (validators) => ({
98
+ valid: (x) => {
99
+ if (x == null) return false;
100
+ for (let [key, v] of Object.entries(validators)) {
101
+ try {
102
+ validator(...__asArray(v))(x[key]);
103
+ } catch (e) {
104
+ throw new ValidationError(
105
+ (e.origMessage ?? e.message) + ` (key: ${key})`
106
+ );
107
+ }
108
+ }
109
+ return true;
110
+ }
111
+ });
112
+ const isEnum = (opts, msg) => ({
113
+ valid: (x) => opts.includes(x),
114
+ msg: msg ?? `required value to be one of: ${opts.join(", ")}`
115
+ });
116
+ const isInRange = (min, max, msg) => ({
117
+ valid: (x) => x >= min && x <= max,
118
+ msg: msg ?? ((x) => `value ${x} not in range [${min},${max}]`)
119
+ });
120
+ const isPositive = (msg) => ({
121
+ valid: (x) => x > 0,
122
+ msg: msg ?? `required positive value`
123
+ });
124
+ const isNegative = (msg) => ({
125
+ valid: (x) => x < 0,
126
+ msg: msg ?? `required negative number`
127
+ });
128
+ const isNonPositive = (msg) => ({
129
+ valid: (x) => x <= 0,
130
+ msg: msg ?? `required non-positive value`
131
+ });
132
+ const isNonNegative = (msg) => ({
133
+ valid: (x) => x >= 0,
134
+ msg: msg ?? `required non-negative value`
135
+ });
136
+ const isLength = (n, msg) => ({
137
+ valid: (x) => x?.length === n,
138
+ msg: msg ?? `required length (${n})`
139
+ });
140
+ const isMinLength = (n, msg) => ({
141
+ valid: (x) => x?.length >= n,
142
+ msg: msg ?? `required min. length (${n})`
143
+ });
144
+ const isMaxLength = (n, msg) => ({
145
+ valid: (x) => x?.length <= n,
146
+ msg: msg ?? `required max. length (${n})`
147
+ });
148
+ const isMinMaxLength = (min, max, msg) => ({
149
+ valid: (x) => x?.length >= min && x?.length <= max,
150
+ msg: msg ?? `length not in [${min},${max}] range`
151
+ });
152
+ const matchesRegexp = (re, msg) => ({
153
+ valid: (x) => $isString(x) && re.test(x),
154
+ msg: msg ?? `doesn't match pattern`
155
+ });
156
+ export {
157
+ ValidationError,
158
+ hasKeysOf,
159
+ hasRequiredKeys,
160
+ isArray,
161
+ isArrayOf,
162
+ isBoolean,
163
+ isDate,
164
+ isEnum,
165
+ isInRange,
166
+ isLength,
167
+ isMaxLength,
168
+ isMinLength,
169
+ isMinMaxLength,
170
+ isNegative,
171
+ isNonNegative,
172
+ isNonPositive,
173
+ isNullish,
174
+ isNumber,
175
+ isObject,
176
+ isObjectOf,
177
+ isPositive,
178
+ isRegExp,
179
+ isString,
180
+ isUndefined,
181
+ matchesRegexp,
182
+ oneOf,
183
+ optional,
184
+ validator
185
+ };