@muze-nl/assert 0.5.1 → 0.6.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/src/assert.mjs CHANGED
@@ -1,328 +1,5 @@
1
- /*
2
- TODO: add assertExplain global flag, so that if assert() fails, you can call explain() with
3
- the same pattern and it will return text explanation of why it failed, each assertion function must
4
- then check assertExplain, and return a text explanation of what fails or succeeds
5
- top level can then filter to show only the failures
6
- (so that not(x) can show the succeeds message of x)
7
- */
1
+ import * as assertApi from './assert-core.mjs'
8
2
 
9
- /**
10
- * assertEnabled (Boolean) used to toggle whether the assert()
11
- * method should test assertions or not.
12
- */
13
- globalThis.assertEnabled = false
3
+ export * from './assert-core.mjs'
14
4
 
15
- /**
16
- * Enables assertion testing with assert()
17
- */
18
- export function enable() {
19
- globalThis.assertEnabled = true
20
- }
21
-
22
- /**
23
- * Disables assertion testing with assert()
24
- */
25
- export function disable() {
26
- globalThis.assertEnabled = false
27
- }
28
-
29
- /**
30
- * This function will check the source for the assertions in test, if
31
- * assertion checking is enabled globally.
32
- * If it is, and any assertion fails, it will throw an assertError
33
- * with a list of problems and other details.
34
- */
35
- export function assert(source, test) {
36
- if (globalThis.assertEnabled) {
37
- let problems = fails(source,test)
38
- if (problems) {
39
- console.error('🅰️ Assertions failed because of:', problems, 'in this source:', source)
40
- throw new Error('Assertions failed', {
41
- cause: { problems, source }
42
- })
43
- }
44
- }
45
- }
46
-
47
- /**
48
- * Tests a given value against a pattern, only if the value is not null or undefined
49
- */
50
- export function Optional(pattern) {
51
- return function _Optional(data, root, path) {
52
- if (typeof data != 'undefined' && data!=null && typeof pattern != 'undefined' ) {
53
- return fails(data, pattern, root, path)
54
- }
55
- }
56
- }
57
-
58
- /**
59
- * Tests a given value against a pattern, always.
60
- */
61
- export function Required(pattern) {
62
- return function _Required(data, root, path) {
63
- if (data==null || typeof data == 'undefined') {
64
- return error('data is required', data, pattern || 'any value', path)
65
- } else if (typeof pattern != 'undefined') {
66
- return fails(data, pattern, root, path)
67
- } else {
68
- return false
69
- }
70
- }
71
- }
72
-
73
- /**
74
- * Tests a given value against a pattern, only if the value is not null or undefined
75
- * If null or undefined, it does print a warning to the console.
76
- */
77
- export function Recommended(pattern) {
78
- return function _Recommended(data, root, path) {
79
- if (data==null || typeof data == 'undefined') {
80
- warn('data does not contain recommended value', data, pattern, path)
81
- return false
82
- } else {
83
- return fails(data, pattern, root, path)
84
- }
85
- }
86
- }
87
-
88
- /**
89
- * Tests a given value against a set of patterns, untill one succeeds
90
- * Returns an error if none succeed
91
- */
92
- export function oneOf(...patterns) {
93
- return function _oneOf(data, root, path) {
94
- for(let pattern of patterns) {
95
- if (!fails(data, pattern, root, path)) {
96
- return false
97
- }
98
- }
99
- return error('data does not match oneOf patterns', data, patterns, path)
100
- }
101
- }
102
-
103
- /**
104
- * Tests a given array of values against a set of patterns
105
- * If any value does not match one of the patterns, it will return an error
106
- * If not given an array to test, it will return an error
107
- */
108
- export function anyOf(...patterns) {
109
- return function _anyOf(data, root, path) {
110
- if (!Array.isArray(data)) {
111
- return error('data is not an array',data,'anyOf',path)
112
- }
113
- for (let value of data) {
114
- if (oneOf(...patterns)(value)) {
115
- return error('data does not match anyOf patterns',value,patterns,path)
116
- }
117
- }
118
- return false
119
- }
120
- }
121
-
122
- export function allOf(...patterns) {
123
- return function _allOf(data, root, path) {
124
- let problems = []
125
- for (let pattern of patterns) {
126
- problems = problems.concat(fails(data, pattern, root, path))
127
- }
128
- problems = problems.filter(Boolean)
129
- if (problems.length) {
130
- return error('data does not match all given patterns', data, patterns, path, problems)
131
- }
132
- }
133
- }
134
-
135
- /**
136
- * Tests a given value to see if it is a valid (and absolute) URL, by
137
- * parsing it with the URL() constructor, and then testing the href
138
- * value to be equal to the initial value.
139
- */
140
- export function validURL(data, root, path) {
141
- try {
142
- if (data instanceof URL) {
143
- data = data.href
144
- }
145
- let url = new URL(data)
146
- if (url.href!=data) {
147
- if (!(url.href+'/'==data || url.href==data+'/')) {
148
- // new URL() always adds a / as path
149
- return error('data is not a valid url',data,'validURL',path)
150
- }
151
- }
152
- } catch(e) {
153
- return error('data is not a valid url',data,'validURL',path)
154
- }
155
- }
156
-
157
- /**
158
- * Tests a given value to see if it looks like a valid email address, by
159
- * testing it against a regular expression. So there are no guarantees that
160
- * it is an actual working email address, just that it looks like one.
161
- */
162
- export function validEmail(data, root, path) {
163
- if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data)) {
164
- return error('data is not a valid email',data,'validEmail',path)
165
- }
166
- }
167
-
168
- /**
169
- * Tests a given value to see if it is an object which is an instance of the given
170
- * constructor
171
- */
172
- export function instanceOf(constructor) {
173
- return function _instanceOf(data, root, path) {
174
- if (!(data instanceof constructor)) {
175
- return error('data is not an instanceof pattern',data,constructor,path)
176
- }
177
- }
178
- }
179
-
180
- /**
181
- * Runs the given test pattern on a value, if the test succeeds, it fails
182
- * the not() test.
183
- */
184
- export function not(pattern) {
185
- return function _not(data, root, path) {
186
- if (!fails(data, pattern, root, path)) {
187
- return error('data matches pattern, when required not to', data, pattern, path)
188
- }
189
- }
190
- }
191
-
192
- /**
193
- * returns an array of problems if the data fails to satisfy
194
- * the assertions in the given pattern, false otherwise
195
- * @param {any} data The data to match
196
- * @param {any} pattern The pattern to match
197
- * @param {any} root Root object for assertions, set to data by default
198
- * @return {Array|false} Array with problems if the pattern fails, false otherwise
199
- */
200
- export function fails(data, pattern, root, path='') {
201
- if (!root) {
202
- root = data
203
- }
204
- let problems = []
205
- if (pattern === Boolean) {
206
- if (typeof data != 'boolean' && !(data instanceof Boolean)) {
207
- problems.push(error('data is not a boolean', data, pattern, path))
208
- }
209
- } else if (pattern === Number) {
210
- if (typeof data != 'number' && !(data instanceof Number)) {
211
- problems.push(error('data is not a number', data, pattern, path))
212
- }
213
- } else if (pattern === String) {
214
- if (typeof data != 'string' && !(data instanceof String)) {
215
- problems.push(error('data is not a string', data, pattern, path))
216
- }
217
- if (data == "") {
218
- problems.push(error('data is an empty string, which is not allowed', data, pattern, path))
219
- }
220
- } else if (pattern instanceof RegExp) {
221
- if (Array.isArray(data)) {
222
- let index = data.findIndex((element,index) => fails(element,pattern,root,path+'['+index+']'))
223
- if (index>-1) {
224
- problems.push(error('data['+index+'] does not match pattern', data[index], pattern, path+'['+index+']'))
225
- }
226
- } else if (typeof data == 'undefined') {
227
- problems.push(error('data is undefined, should match pattern', data, pattern, path))
228
- } else if (!pattern.test(data)) {
229
- problems.push(error('data does not match pattern', data, pattern, path))
230
- }
231
- } else if (pattern instanceof Function) {
232
- let problem = pattern(data, root, path)
233
- if (problem) {
234
- if (Array.isArray(problem)) {
235
- problems = problems.concat(problem)
236
- } else {
237
- problems.push(problem)
238
- }
239
- }
240
- } else if (Array.isArray(pattern)) {
241
- if (!Array.isArray(data)) {
242
- problems.push(error('data is not an array',data,[],path))
243
- }
244
- for (let p of pattern) {
245
- for (let index of data.keys()) {
246
- let problem = fails(data[index], p, root, path+'['+index+']')
247
- if (Array.isArray(problem)) {
248
- problems = problems.concat(problem)
249
- } else if (problem) {
250
- problems.push(problem)
251
- }
252
- }
253
- }
254
- } else if (pattern && typeof pattern == 'object') {
255
- if (Array.isArray(data)) {
256
- let index = data.findIndex((element,index) => fails(element,pattern,root,path+'['+index+']'))
257
- if (index>-1) {
258
- problems.push(error('data['+index+'] does not match pattern', data[index], pattern, path+'['+index+']'))
259
- }
260
- } else if (!data || typeof data != 'object') {
261
- problems.push(error('data is not an object, pattern is', data, pattern, path))
262
- } else {
263
- if (data instanceof URLSearchParams) {
264
- data = Object.fromEntries(data)
265
- }
266
- if (pattern instanceof Function) {
267
- let result = fails(data, pattern, root, path)
268
- if (result) {
269
- problems = problems.concat(result)
270
- }
271
- } else {
272
- for (const [patternKey, subpattern] of Object.entries(pattern)) {
273
- let result = fails(data[patternKey], subpattern, root, path+'.'+patternKey)
274
- if (result) {
275
- problems = problems.concat(result)
276
- }
277
- }
278
- }
279
- }
280
- } else {
281
- if (pattern!=data) {
282
- problems.push(error('data and pattern are not equal', data, pattern, path))
283
- }
284
- }
285
- if (problems.length) {
286
- return problems
287
- }
288
- return false
289
- }
290
-
291
- /**
292
- * Returns an object with message, found and expected properties
293
- */
294
- export function error(message, found, expected, path, problems) {
295
- let result = {
296
- path,
297
- message,
298
- found,
299
- expected
300
- }
301
- if (problems) {
302
- result.problems = problems
303
- }
304
- return result
305
- }
306
-
307
- export function warn(message, data, pattern, path) {
308
- console.warn('🅰️ Assert: '+path, message, pattern, data)
309
- }
310
-
311
- globalThis.assert = {
312
- warn,
313
- error,
314
- assert,
315
- enable,
316
- disable,
317
- Required,
318
- Recommended,
319
- Optional,
320
- oneOf,
321
- anyOf,
322
- allOf,
323
- validURL,
324
- validEmail,
325
- instanceOf,
326
- not,
327
- fails
328
- }
5
+ globalThis.assert = { ...assertApi }