n4s 3.0.0 → 4.0.0-dev-1aae50

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 (64) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/LICENSE +1 -2
  3. package/README.md +2 -5
  4. package/compose/package.json +7 -0
  5. package/compounds/package.json +7 -0
  6. package/dist/cjs/compose.development.js +139 -0
  7. package/dist/cjs/compose.js +7 -0
  8. package/dist/cjs/compose.production.js +1 -0
  9. package/dist/cjs/compounds.development.js +132 -0
  10. package/dist/cjs/compounds.js +7 -0
  11. package/dist/cjs/compounds.production.js +1 -0
  12. package/dist/cjs/n4s.development.js +602 -0
  13. package/dist/cjs/n4s.js +7 -0
  14. package/dist/cjs/n4s.production.js +1 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/schema.development.js +144 -0
  17. package/dist/cjs/schema.js +7 -0
  18. package/dist/cjs/schema.production.js +1 -0
  19. package/dist/es/compose.development.js +137 -0
  20. package/dist/es/compose.production.js +1 -0
  21. package/dist/es/compounds.development.js +130 -0
  22. package/dist/es/compounds.production.js +1 -0
  23. package/dist/es/n4s.development.js +597 -0
  24. package/dist/es/n4s.production.js +1 -0
  25. package/dist/es/package.json +1 -0
  26. package/dist/es/schema.development.js +140 -0
  27. package/dist/es/schema.production.js +1 -0
  28. package/dist/umd/compose.development.js +143 -0
  29. package/dist/umd/compose.production.js +1 -0
  30. package/dist/umd/compounds.development.js +136 -0
  31. package/dist/umd/compounds.production.js +1 -0
  32. package/dist/umd/n4s.development.js +606 -0
  33. package/dist/umd/n4s.production.js +1 -0
  34. package/dist/umd/schema.development.js +148 -0
  35. package/dist/umd/schema.production.js +1 -0
  36. package/docs/README.md +2 -5
  37. package/docs/_sidebar.md +1 -2
  38. package/docs/external.md +1 -28
  39. package/docs/rules.md +28 -0
  40. package/package.json +129 -42
  41. package/schema/package.json +7 -0
  42. package/tsconfig.json +8 -0
  43. package/types/compose.d.ts +134 -0
  44. package/types/compounds.d.ts +146 -0
  45. package/types/n4s.d.ts +167 -0
  46. package/types/schema.d.ts +151 -0
  47. package/config/jest/jest.setup.js +0 -14
  48. package/config/rollup/enforce.js +0 -8
  49. package/config/rollup/rollup.config.js +0 -3
  50. package/docs/compound.md +0 -187
  51. package/docs/custom.md +0 -52
  52. package/docs/template.md +0 -53
  53. package/esm/n4s.mjs.development.js +0 -1101
  54. package/esm/n4s.mjs.production.js +0 -1101
  55. package/esm/n4s.mjs.production.min.js +0 -1
  56. package/esm/package.json +0 -1
  57. package/jest.config.js +0 -3
  58. package/n4s.cjs.development.js +0 -1103
  59. package/n4s.cjs.production.js +0 -1103
  60. package/n4s.cjs.production.min.js +0 -1
  61. package/n4s.js +0 -7
  62. package/n4s.umd.development.js +0 -1109
  63. package/n4s.umd.production.js +0 -1192
  64. package/n4s.umd.production.min.js +0 -1
@@ -1,1101 +0,0 @@
1
- /**
2
- * Stores values and configuration passed down to compound rules.
3
- *
4
- * @param {Object} content
5
- */
6
- function EnforceContext(content) {
7
- Object.assign(this, content);
8
- }
9
- /**
10
- * Sets an EnforceContext config `failFast`
11
- *
12
- * @param {Boolean} failFast
13
- * @return {EnforceContext}
14
- */
15
-
16
- EnforceContext.prototype.setFailFast = function (failFast) {
17
- this.failFast = !!failFast;
18
- return this;
19
- };
20
- /**
21
- * Extracts the literal value from an EnforceContext object
22
- * @param {*} value
23
- * @return {*}
24
- */
25
-
26
-
27
- EnforceContext.unwrap = function unwrap(value) {
28
- return EnforceContext.is(value) ? value.value : value;
29
- };
30
- /**
31
- * Wraps a literal value within a context.
32
- * @param {*} value
33
- * @return {EnforceContext}
34
- */
35
-
36
-
37
- EnforceContext.wrap = function wrap(value) {
38
- return EnforceContext.is(value) ? value : new EnforceContext({
39
- value
40
- });
41
- };
42
- /**
43
- * Checks whether a given value is an EnforceContext instance
44
- *
45
- * @param {*} value
46
- * @returns {boolean}
47
- */
48
-
49
-
50
- EnforceContext.is = function is(value) {
51
- return value instanceof EnforceContext;
52
- };
53
-
54
- /**
55
- * A safe hasOwnProperty access
56
- */
57
- function hasOwnProperty(obj, key) {
58
- return Object.prototype.hasOwnProperty.call(obj, key);
59
- }
60
-
61
- function bindNot(fn) {
62
- return function () {
63
- return !fn.apply(this, arguments);
64
- };
65
- }
66
-
67
- function isBoolean(value) {
68
- return !!value === value;
69
- }
70
-
71
- const isNotBoolean = bindNot(isBoolean);
72
-
73
- function isNumeric(value) {
74
- const result = !isNaN(parseFloat(value)) && !isNaN(Number(value)) && isFinite(value);
75
- return Boolean(result);
76
- }
77
- const isNotNumeric = bindNot(isNumeric);
78
-
79
- function lengthEquals(value, arg1) {
80
- return value.length === Number(arg1);
81
- }
82
- const lengthNotEquals = bindNot(lengthEquals);
83
-
84
- function isEmpty(value) {
85
- if (!value) {
86
- return true;
87
- } else if (isNumeric(value)) {
88
- return value === 0;
89
- } else if (hasOwnProperty(value, 'length')) {
90
- return lengthEquals(value, 0);
91
- } else if (typeof value === 'object') {
92
- return lengthEquals(Object.keys(value), 0);
93
- }
94
-
95
- return true;
96
- }
97
- const isNotEmpty = bindNot(isEmpty);
98
-
99
- function isUndefined(value) {
100
- return value === undefined;
101
- }
102
- const isNotUndefined = bindNot(isUndefined);
103
-
104
- const HAS_WARNINGS = 'hasWarnings';
105
- const HAS_ERRORS = 'hasErrors';
106
-
107
- /**
108
- * Stores a rule result in an easy to inspect and manipulate structure.
109
- *
110
- * @param {boolean|RuleResult} ruleRunResult
111
- */
112
-
113
- function RuleResult(ruleRunResult) {
114
- if (isUndefined(ruleRunResult)) {
115
- return;
116
- }
117
-
118
- if (isBoolean(ruleRunResult)) {
119
- this.setFailed(!ruleRunResult);
120
- } else {
121
- this.extend(ruleRunResult);
122
- }
123
- }
124
- /**
125
- * Determines whether a given value is a RuleResult instance
126
- * @param {*} res
127
- * @return {boolean}
128
- */
129
-
130
- RuleResult.is = function (res) {
131
- return res instanceof RuleResult;
132
- };
133
- /**
134
- * Marks the current result object as an array
135
- */
136
-
137
-
138
- RuleResult.prototype.asArray = function () {
139
- this.isArray = true;
140
- return this;
141
- };
142
- /**
143
- * @param {string} key
144
- * @param {value} value
145
- * @return {RuleResult} current instance
146
- */
147
-
148
-
149
- RuleResult.prototype.setAttribute = function (key, value) {
150
- this[key] = value;
151
- return this;
152
- };
153
- /**
154
- * @param {boolean} failed
155
- * @return {RuleResult} current instance
156
- */
157
-
158
-
159
- RuleResult.prototype.setFailed = function (failed) {
160
- this.setAttribute(this.warn ? HAS_WARNINGS : HAS_ERRORS, failed);
161
- return this.setAttribute('failed', failed);
162
- };
163
- /**
164
- * Adds a nested result object
165
- *
166
- * @param {string} key
167
- * @param {RuleResult} child
168
- */
169
-
170
-
171
- RuleResult.prototype.setChild = function (key, child) {
172
- const isWarning = this[HAS_WARNINGS] || child[HAS_WARNINGS] || child.warn || this.warn;
173
- this.setAttribute(HAS_WARNINGS, isWarning && child.failed || false);
174
- this.setAttribute(HAS_ERRORS, this[HAS_ERRORS] || child[HAS_ERRORS] || !isWarning && child.failed || false);
175
- this.setFailed(this.failed || child.failed);
176
- this.children = this.children || {};
177
- this.children[key] = child;
178
- return child;
179
- };
180
- /**
181
- * Retrieves a child by its key
182
- *
183
- * @param {string} key
184
- * @return {RuleResult|undefined}
185
- */
186
-
187
-
188
- RuleResult.prototype.getChild = function (key) {
189
- return (this.children || {})[key];
190
- };
191
- /**
192
- * Extends current instance with a new provided result
193
- * @param {Boolean|RuleResult} newRes
194
- */
195
-
196
-
197
- RuleResult.prototype.extend = function (newRes) {
198
- const res = RuleResult.is(newRes) ? newRes : new RuleResult().setAttribute('warn', !!this.warn).setFailed(!newRes);
199
- const failed = this.failed || res.failed;
200
- const children = mergeChildren(res, this).children;
201
- Object.assign(this, res);
202
-
203
- if (!isEmpty(children)) {
204
- this.children = children;
205
- }
206
-
207
- this.setFailed(failed);
208
- this.setAttribute(HAS_WARNINGS, !!(this[HAS_WARNINGS] || res[HAS_WARNINGS]));
209
- this.setAttribute(HAS_ERRORS, !!(this[HAS_ERRORS] || res[HAS_ERRORS]));
210
- };
211
-
212
- Object.defineProperty(RuleResult.prototype, 'pass', {
213
- get() {
214
- return !this.failed;
215
- }
216
-
217
- });
218
- /**
219
- * Deeply merge the nested children of compound rules
220
- *
221
- * @param {?RuleResult} base
222
- * @param {?RuleResult} add
223
- * @return {RuleResult}
224
- */
225
-
226
- function mergeChildren(base, add) {
227
- const isRuleResultBase = RuleResult.is(base);
228
- const isRuleResultAdd = RuleResult.is(add); // If both base and add are result objects
229
-
230
- if (isRuleResultBase && isRuleResultAdd) {
231
- // Use failed if either is failing
232
- base.setFailed(base.failed || add.failed); // If neither has a children object, or the children object is
233
-
234
- if (isEmpty(base.children) && isEmpty(add.children)) {
235
- return base;
236
- } // If both have a children object
237
-
238
-
239
- if (base.children && add.children) {
240
- // Merge all the "right side" children back to base
241
- for (const key in base.children) {
242
- mergeChildren(base.children[key], add.children[key]);
243
- } // If a child exists in "add" but not in "base", just copy the child as is
244
-
245
-
246
- for (const key in add.children) {
247
- if (!hasOwnProperty(base.children, key)) {
248
- base.setChild(key, add.children[key]);
249
- }
250
- } // Return the modified base object
251
-
252
-
253
- return base; // If base has no children (but add does)
254
- } else if (!base.children) {
255
- // Use add's children
256
- base.children = add.children; // If add has no children
257
- } else if (!add.children) {
258
- // return base as is
259
- return base;
260
- } // If only base is `RuleResult`
261
-
262
- } else if (isRuleResultBase) {
263
- // Return base as is
264
- return base; // If only add is RuleResult
265
- } else if (isRuleResultAdd) {
266
- // Return add as is
267
- return add;
268
- } // That's a weird case. Let's fail. Very unlikely.
269
-
270
-
271
- return new RuleResult(false);
272
- }
273
-
274
- const RUN_RULE = 'run';
275
- const TEST_RULE = 'test';
276
- const MODE_ALL = 'all';
277
- const MODE_ONE = 'one';
278
- const MODE_ANY = 'any';
279
-
280
- function isFunction (v) {
281
- return typeof v === 'function';
282
- }
283
-
284
- function asArray(possibleArg) {
285
- return [].concat(possibleArg);
286
- }
287
-
288
- /**
289
- * Determines whether we should bail out of an enforcement.
290
- *
291
- * @param {EnforceContext} ctx
292
- * @param {RuleResult} result
293
- */
294
-
295
- function shouldFailFast(ctx, result) {
296
- if (result.pass || result.warn) {
297
- return false;
298
- }
299
-
300
- return !!EnforceContext.is(ctx) && ctx.failFast;
301
- }
302
-
303
- /**
304
- * Runs multiple enforce rules that are passed to compounds.
305
- * Example: enforce.allOf(enforce.ruleOne(), enforce.ruleTwo().ruleThree())
306
- *
307
- * @param {{run: Function}[]} ruleGroups
308
- * @param {*} value
309
- * @return {RuleResult}
310
- */
311
-
312
- function runLazyRules(ruleGroups, value) {
313
- const result = new RuleResult(true);
314
-
315
- for (const chain of asArray(ruleGroups)) {
316
- if (shouldFailFast(value, result)) {
317
- break;
318
- }
319
-
320
- result.extend(runLazyRule(chain, value));
321
- }
322
-
323
- return result;
324
- }
325
- /**
326
- * Runs a single lazy rule
327
- *
328
- * @param {{run: Function}} ruleGroup
329
- * @param {*} value
330
- * @return {boolean|RuleResult}
331
- */
332
-
333
- function runLazyRule(ruleGroup, value) {
334
- return ruleGroup[RUN_RULE](value);
335
- }
336
-
337
- /**
338
- * Runs chains of rules
339
- *
340
- * @param {EnforceContext} value
341
- * @param {[{test: Function, run: Function}]} rules
342
- * @param {RuleResult} options
343
- */
344
-
345
- function runCompoundChain(value, rules, options) {
346
- const result = new RuleResult(true);
347
-
348
- if (isEmpty(rules)) {
349
- result.setFailed(true);
350
- }
351
-
352
- const failedResults = [];
353
- let count = 0;
354
-
355
- for (const chain of rules) {
356
- // Inner result for each iteration
357
- const currentResult = runLazyRule(chain, value);
358
- const pass = currentResult.pass;
359
-
360
- if (pass) {
361
- count++;
362
- } else {
363
- failedResults.push(currentResult);
364
- }
365
-
366
- if (options) {
367
- // "anyOf" is a special case.
368
- // It shouldn't extend with failed results,
369
- // that's why we continue
370
- if (options.mode === MODE_ANY) {
371
- if (pass) {
372
- result.extend(currentResult);
373
- break;
374
- }
375
-
376
- continue;
377
- }
378
-
379
- result.extend(currentResult); // MODE_ALL: All must pass.
380
- // If one failed, exit.
381
-
382
- if (options.mode === MODE_ALL) {
383
- if (!pass) {
384
- break;
385
- }
386
- } // MODE_ONE: only one must pass.
387
- // If more than one passed, exit.
388
-
389
-
390
- if (options.mode === MODE_ONE) {
391
- result.setFailed(count !== 1);
392
-
393
- if (count > 1) {
394
- break;
395
- }
396
- }
397
- } else {
398
- result.extend(currentResult);
399
-
400
- if (pass) {
401
- break;
402
- }
403
- }
404
- }
405
-
406
- if (result.pass && count === 0) {
407
- result.setFailed(true); // In some cases we do not want to extend failures, for example - in ANY
408
- // when there is a valid response, so we do it before returning
409
-
410
- failedResults.forEach(failedResult => result.extend(failedResult));
411
- }
412
-
413
- return result;
414
- }
415
-
416
- function setFnName(fn, value) {
417
- return Object.defineProperty(fn, 'name', {
418
- value
419
- });
420
- }
421
-
422
- /**
423
- * ES5 Transpilation increases the size of spread arguments by a lot.
424
- * Wraps a function and passes its spread params as an array.
425
- *
426
- * @param {Function} cb
427
- * @param {String} [fnName]
428
- * @return {Function}
429
- */
430
-
431
- function withArgs(cb, fnName) {
432
- return setFnName((...args) => {
433
- const right = args.splice(cb.length - 1);
434
- return cb.apply(null, args.concat([right]));
435
- }, fnName || cb.name);
436
- }
437
-
438
- /**
439
- * Runs a chaen of rules, making sure that all assertions pass
440
- *
441
- * @param {EnforceContext} value
442
- * @param {[{test: Function, run: Function}]} ruleChains
443
- * @return {RuleResult}
444
- */
445
-
446
- function allOf(value, rules) {
447
- return runCompoundChain(value, rules, {
448
- mode: MODE_ALL
449
- });
450
- }
451
-
452
- var allOf$1 = withArgs(allOf);
453
-
454
- /**
455
- * Runs chains of rules, making sure
456
- * that at least one assertion passes
457
- *
458
- * @param {EnforceContext} value
459
- * @param {[{test: Function, run: Function}]} ruleChains
460
- * @return {RuleResult}
461
- */
462
-
463
- function anyOf(value, ruleChains) {
464
- return runCompoundChain(value, ruleChains, {
465
- mode: MODE_ANY
466
- });
467
- }
468
-
469
- var anyOf$1 = withArgs(anyOf);
470
-
471
- function isArray(value) {
472
- return Boolean(Array.isArray(value));
473
- }
474
- const isNotArray = bindNot(isArray);
475
-
476
- /**
477
- * Asserts that each element in an array passes
478
- * at least one of the provided rule chain
479
- *
480
- * @param {EnforceContext} value
481
- * @param {[{test: Function, run: Function}]} ruleChains
482
- * @return {RuleResult}
483
- */
484
-
485
- function isArrayOf(value, ruleChains) {
486
- const plainValue = EnforceContext.unwrap(value);
487
- const result = new RuleResult(true).asArray(); // Fails if current value is not an array
488
-
489
- if (isNotArray(plainValue)) {
490
- return result.setFailed(true);
491
- }
492
-
493
- for (let i = 0; i < plainValue.length; i++) {
494
- // Set result per each item in the array|
495
- result.setChild(i, runCompoundChain(EnforceContext.wrap(plainValue[i]).setFailFast(value.failFast), ruleChains, {
496
- mode: MODE_ANY
497
- }));
498
- }
499
-
500
- return result;
501
- }
502
-
503
- var isArrayOf$1 = withArgs(isArrayOf);
504
-
505
- /**
506
- * @param {EnforceContext} value
507
- * @param {[{test: Function, run: Function}]} ruleChains
508
- * @return {RuleResult}
509
- */
510
-
511
- function oneOf(value, rules) {
512
- return runCompoundChain(value, rules, {
513
- mode: MODE_ONE
514
- });
515
- }
516
-
517
- var oneOf$1 = withArgs(oneOf);
518
-
519
- function isNull(value) {
520
- return value === null;
521
- }
522
- const isNotNull = bindNot(isNull);
523
-
524
- /**
525
- * @param {Array} ObjectEntry Object and key leading to current value
526
- * @param {Function[]} rules Rules to validate the value with
527
- */
528
-
529
- function optional(inputObject, ruleGroups) {
530
- const {
531
- obj,
532
- key
533
- } = inputObject; // If current value is not defined, undefined or null
534
- // Pass without further assertions
535
-
536
- if (!hasOwnProperty(obj, key) || isUndefined(obj[key] || isNull(obj[key]))) {
537
- return true;
538
- } // Pass if exists but no assertions
539
-
540
-
541
- if (isEmpty(ruleGroups)) {
542
- return true;
543
- } // Run chain with `all` mode
544
-
545
-
546
- return runCompoundChain(obj[key], ruleGroups, {
547
- mode: MODE_ALL
548
- });
549
- }
550
-
551
- var optional$1 = withArgs(optional);
552
-
553
- /**
554
- * @param {EnforceContext} inputObject Data object that gets validated
555
- * @param {Object} shapeObj Shape definition
556
- * @param {Object} options
557
- * @param {boolean} options.loose Ignore extra keys not defined in shapeObj
558
- */
559
-
560
- function shape(inputObject, shapeObj, options) {
561
- // Extract the object from context
562
- const obj = EnforceContext.unwrap(inputObject); // Create a new result object
563
-
564
- const result = new RuleResult(true); // Iterate over the shape keys
565
-
566
- for (const key in shapeObj) {
567
- const current = shapeObj[key];
568
- const value = obj[key];
569
-
570
- if (shouldFailFast(value, result)) {
571
- break;
572
- } // Set each key in the result object
573
-
574
-
575
- result.setChild(key, runLazyRule(current, new EnforceContext({
576
- value,
577
- obj,
578
- key
579
- }).setFailFast(inputObject.failFast)));
580
- } // If mode is not loose
581
-
582
-
583
- if (!(options || {}).loose) {
584
- // Check that each key in the input object exists in the shape
585
- for (const key in obj) {
586
- if (!hasOwnProperty(shapeObj, key)) {
587
- return result.setFailed(true);
588
- }
589
- }
590
- }
591
-
592
- return result;
593
- }
594
- const loose = (obj, shapeObj) => shape(obj, shapeObj, {
595
- loose: true
596
- });
597
-
598
- var compounds = {
599
- allOf: allOf$1,
600
- anyOf: anyOf$1,
601
- isArrayOf: isArrayOf$1,
602
- loose,
603
- oneOf: oneOf$1,
604
- optional: optional$1,
605
- shape
606
- };
607
-
608
- /**
609
- * Takes a value. If it is a function, runs it and returns the result.
610
- * Otherwise, returns the value as is.
611
- *
612
- * @param {Function|*} value Value to return. Run it if a function.
613
- * @param {Any[]} [args] Arguments to pass if a function
614
- * @return {Any}
615
- */
616
-
617
- function optionalFunctionValue(value, args) {
618
- return isFunction(value) ? value.apply(null, args) : value;
619
- }
620
-
621
- function message(value, msg) {
622
- return optionalFunctionValue(msg, [EnforceContext.unwrap(value)]);
623
- }
624
-
625
- function warn(_, isWarn = true) {
626
- return isWarn;
627
- }
628
-
629
- var ruleMeta = {
630
- warn,
631
- message
632
- };
633
-
634
- function isString (v) {
635
- return String(v) === v;
636
- }
637
-
638
- function endsWith(value, arg1) {
639
- return isString(value) && isString(arg1) && value.endsWith(arg1);
640
- }
641
- const doesNotEndWith = bindNot(endsWith);
642
-
643
- function equals(value, arg1) {
644
- return value === arg1;
645
- }
646
- const notEquals = bindNot(equals);
647
-
648
- function greaterThan(value, arg1) {
649
- return isNumeric(value) && isNumeric(arg1) && Number(value) > Number(arg1);
650
- }
651
-
652
- function greaterThanOrEquals(value, arg1) {
653
- return isNumeric(value) && isNumeric(arg1) && Number(value) >= Number(arg1);
654
- }
655
-
656
- function inside(value, arg1) {
657
- if (Array.isArray(arg1) && /^[s|n|b]/.test(typeof value)) {
658
- return arg1.indexOf(value) !== -1;
659
- } // both value and arg1 are strings
660
-
661
-
662
- if (isString(arg1) && isString(value)) {
663
- return arg1.indexOf(value) !== -1;
664
- }
665
-
666
- return false;
667
- }
668
- const notInside = bindNot(inside);
669
-
670
- function lessThanOrEquals(value, arg1) {
671
- return isNumeric(value) && isNumeric(arg1) && Number(value) <= Number(arg1);
672
- }
673
-
674
- function isBetween(value, min, max) {
675
- return greaterThanOrEquals(value, min) && lessThanOrEquals(value, max);
676
- }
677
- const isNotBetween = bindNot(isBetween);
678
-
679
- /**
680
- * Validates that a given value is an even number
681
- * @param {Number|String} value Value to be validated
682
- * @return {Boolean}
683
- */
684
-
685
- const isEven = value => {
686
- if (isNumeric(value)) {
687
- return value % 2 === 0;
688
- }
689
-
690
- return false;
691
- };
692
-
693
- function isNaN$1(value) {
694
- return Number.isNaN(value);
695
- }
696
- const isNotNaN = bindNot(isNaN$1);
697
-
698
- function isNegative(value) {
699
- if (isNumeric(value)) {
700
- return Number(value) < 0;
701
- }
702
-
703
- return false;
704
- }
705
- const isPositive = bindNot(isNegative);
706
-
707
- function isNumber(value) {
708
- return Boolean(typeof value === 'number');
709
- }
710
- const isNotNumber = bindNot(isNumber);
711
-
712
- /**
713
- * Validates that a given value is an odd number
714
- * @param {Number|String} value Value to be validated
715
- * @return {Boolean}
716
- */
717
-
718
- const isOdd = value => {
719
- if (isNumeric(value)) {
720
- return value % 2 !== 0;
721
- }
722
-
723
- return false;
724
- };
725
-
726
- const isNotString = bindNot(isString);
727
-
728
- function isTruthy(value) {
729
- return !!value;
730
- }
731
- const isFalsy = bindNot(isTruthy);
732
-
733
- function lessThan(value, arg1) {
734
- return isNumeric(value) && isNumeric(arg1) && Number(value) < Number(arg1);
735
- }
736
-
737
- function longerThan(value, arg1) {
738
- return value.length > Number(arg1);
739
- }
740
-
741
- function longerThanOrEquals(value, arg1) {
742
- return value.length >= Number(arg1);
743
- }
744
-
745
- function matches(value, regex) {
746
- if (regex instanceof RegExp) {
747
- return regex.test(value);
748
- } else if (isString(regex)) {
749
- return new RegExp(regex).test(value);
750
- } else {
751
- return false;
752
- }
753
- }
754
- const notMatches = bindNot(matches);
755
-
756
- function numberEquals(value, arg1) {
757
- return isNumeric(value) && isNumeric(arg1) && Number(value) === Number(arg1);
758
- }
759
- const numberNotEquals = bindNot(numberEquals);
760
-
761
- function shorterThan(value, arg1) {
762
- return value.length < Number(arg1);
763
- }
764
-
765
- function shorterThanOrEquals(value, arg1) {
766
- return value.length <= Number(arg1);
767
- }
768
-
769
- function startsWith(value, arg1) {
770
- return isString(value) && isString(arg1) && value.startsWith(arg1);
771
- }
772
- const doesNotStartWith = bindNot(startsWith);
773
-
774
- function rules() {
775
- return {
776
- doesNotEndWith,
777
- doesNotStartWith,
778
- endsWith,
779
- equals,
780
- greaterThan,
781
- greaterThanOrEquals,
782
- gt: greaterThan,
783
- gte: greaterThanOrEquals,
784
- inside,
785
- isArray,
786
- isBetween,
787
- isBoolean,
788
- isEmpty,
789
- isEven,
790
- isFalsy,
791
- isNaN: isNaN$1,
792
- isNegative,
793
- isNotArray,
794
- isNotBetween,
795
- isNotBoolean,
796
- isNotEmpty,
797
- isNotNaN,
798
- isNotNull,
799
- isNotNumber,
800
- isNotNumeric,
801
- isNotString,
802
- isNotUndefined,
803
- isNull,
804
- isNumber,
805
- isNumeric,
806
- isOdd,
807
- isPositive,
808
- isString,
809
- isTruthy,
810
- isUndefined,
811
- lengthEquals,
812
- lengthNotEquals,
813
- lessThan,
814
- lessThanOrEquals,
815
- longerThan,
816
- longerThanOrEquals,
817
- lt: lessThan,
818
- lte: lessThanOrEquals,
819
- matches,
820
- notEquals,
821
- notInside,
822
- notMatches,
823
- numberEquals,
824
- numberNotEquals,
825
- shorterThan,
826
- shorterThanOrEquals,
827
- startsWith
828
- };
829
- }
830
-
831
- var runtimeRules = Object.assign(rules(), compounds, ruleMeta);
832
-
833
- /**
834
- * Determines whether a given string is a name of a rule
835
- *
836
- * @param {string} name
837
- * @return {boolean}
838
- */
839
-
840
- const isRule = name => hasOwnProperty(runtimeRules, name) && isFunction(runtimeRules[name]);
841
-
842
- const GLOBAL_OBJECT = Function('return this')();
843
-
844
- const proxySupported = () => isFunction(GLOBAL_OBJECT.Proxy);
845
-
846
- function genRuleProxy(target, output) {
847
- if (proxySupported()) {
848
- return new Proxy(target, {
849
- get: (target, fnName) => {
850
- // A faster bailout when we access `run` and `test`
851
- if (hasOwnProperty(target, fnName)) {
852
- return target[fnName];
853
- }
854
-
855
- if (isRule(fnName)) {
856
- return output(fnName);
857
- }
858
-
859
- return target[fnName];
860
- }
861
- });
862
- } else {
863
- /**
864
- * This method is REALLY not recommended as it is slow and iterates over
865
- * all the rules for each direct enforce reference. We only use it as a
866
- * lightweight alternative for the much faster proxy interface
867
- */
868
- for (const fnName in runtimeRules) {
869
- if (!isFunction(target[fnName])) {
870
- Object.defineProperties(target, {
871
- [fnName]: {
872
- get: () => output(fnName)
873
- }
874
- });
875
- }
876
- }
877
-
878
- return target;
879
- }
880
- }
881
-
882
- /**
883
- * Determines whether a given rule is a compound.
884
- *
885
- * @param {Function} rule
886
- * @return {boolean}
887
- */
888
-
889
- function isCompound(rule) {
890
- return hasOwnProperty(compounds, rule.name);
891
- }
892
-
893
- /**
894
- * Creates a rule of lazily called rules.
895
- * Each rule gets added a `.run()` property
896
- * which runs all the accumulated rules in
897
- * the chain against the supplied value
898
- *
899
- * @param {string} ruleName
900
- * @return {{run: Function}}
901
- */
902
-
903
- function bindLazyRule(ruleName) {
904
- const registeredRules = []; // Chained rules
905
-
906
- const meta = []; // Meta properties to add onto the rule context
907
- // Appends a function to the registeredRules array.
908
- // It gets called every time the consumer usess chaining
909
- // so, for example - enforce.isArray() <- this calles addFn
910
-
911
- const addFn = ruleName => {
912
- return withArgs(args => {
913
- const rule = runtimeRules[ruleName]; // Add a meta function
914
-
915
- if (ruleMeta[rule.name] === rule) {
916
- meta.push((value, ruleResult) => {
917
- ruleResult.setAttribute(rule.name, rule(value, args[0]));
918
- });
919
- } else {
920
- // Register a rule
921
- registeredRules.push(setFnName(value => {
922
- return rule.apply(null, [// If the rule is compound - wraps the value with context
923
- // Otherwise - unwraps it
924
- isCompound(rule) ? EnforceContext.wrap(value) : EnforceContext.unwrap(value)].concat(args));
925
- }, ruleName));
926
- } // set addFn as the proxy handler
927
-
928
-
929
- const returnvalue = genRuleProxy({}, addFn);
930
-
931
- returnvalue[RUN_RULE] = value => {
932
- const result = new RuleResult(true); // Run meta chains
933
-
934
- meta.forEach(fn => {
935
- fn(value, result);
936
- }); // Iterate over all the registered rules
937
- // This runs the function that's inside `addFn`
938
-
939
- for (const fn of registeredRules) {
940
- try {
941
- result.extend(fn(value)); // If a chained rule fails, exit. We failed.
942
-
943
- if (!result.pass) {
944
- break;
945
- }
946
- } catch (e) {
947
- result.setFailed(true);
948
- break;
949
- }
950
- }
951
-
952
- return result;
953
- };
954
-
955
- returnvalue[TEST_RULE] = value => returnvalue[RUN_RULE](EnforceContext.wrap(value).setFailFast(true)).pass;
956
-
957
- return returnvalue;
958
- }, ruleName);
959
- }; // Returns the initial rule in the chain
960
-
961
-
962
- return addFn(ruleName);
963
- }
964
-
965
- function bindExtend(enforce, Enforce) {
966
- enforce.extend = customRules => {
967
- Object.assign(runtimeRules, customRules);
968
-
969
- if (!proxySupported()) {
970
- genRuleProxy(Enforce, bindLazyRule);
971
- }
972
-
973
- return enforce;
974
- };
975
- }
976
-
977
- /**
978
- * Throws a timed out error.
979
- * @param {String} message Error message to display.
980
- * @param {Error} [type] Alternative Error type.
981
- */
982
- const throwError = (message, type = Error) => {
983
- throw new type(`[${"n4s"}]: ${message}`);
984
- };
985
-
986
- function validateResult(result, rule) {
987
- // if result is boolean, or if result.pass is boolean
988
- if (isBoolean(result) || result && isBoolean(result.pass)) {
989
- return;
990
- }
991
-
992
- throwError( `${rule.name} wrong return value for the rule please check that the return is valid` );
993
- } // for easier testing and mocking
994
-
995
- function getDefaultResult(value, rule) {
996
- return {
997
- message: formatResultMessage(rule, `invalid ${typeof value} value`)
998
- };
999
- }
1000
- function formatResultMessage(rule, msg) {
1001
- return `[${"n4s"}]:${rule.name} ${msg}`;
1002
- }
1003
- /**
1004
- * Transform the result of a rule into a standard format
1005
- * @param {string} interfaceName to be used in the messages
1006
- * @param {*} result of the rule
1007
- * @param {Object} options
1008
- * @param {function} options.rule
1009
- * @param {*} options.value
1010
- * @returns {Object} result
1011
- * @returns {string} result.message
1012
- * @returns {boolean} result.pass indicates if the test passes or not
1013
- */
1014
-
1015
- function transformResult(result, {
1016
- rule,
1017
- value
1018
- }) {
1019
- const defaultResult = getDefaultResult(value, rule);
1020
- validateResult(result, rule); // if result is boolean
1021
-
1022
- if (isBoolean(result)) {
1023
- return defaultResult.pass = result, defaultResult;
1024
- } else {
1025
- defaultResult.pass = result.pass;
1026
-
1027
- if (result.message) {
1028
- defaultResult.message = formatResultMessage(rule, optionalFunctionValue(result.message));
1029
- }
1030
-
1031
- return defaultResult;
1032
- }
1033
- }
1034
-
1035
- /**
1036
- * Run a single rule against enforced value (e.g. `isNumber()`)
1037
- *
1038
- * @param {Function} rule - rule to run
1039
- * @param {Any} value
1040
- * @param {Array} args list of arguments sent from consumer
1041
- * @throws
1042
- */
1043
-
1044
- function runner(rule, value, args = []) {
1045
- let result;
1046
- const isCompoundRule = isCompound(rule);
1047
- const ruleValue = isCompoundRule ? EnforceContext.wrap(value).setFailFast(true) : EnforceContext.unwrap(value);
1048
- result = rule.apply(null, [ruleValue].concat(args));
1049
-
1050
- if (!isCompoundRule) {
1051
- result = transformResult(result, {
1052
- rule,
1053
- value
1054
- });
1055
- }
1056
-
1057
- if (!result.pass) {
1058
- throw new Error(result.message);
1059
- }
1060
- }
1061
-
1062
- /**
1063
- * Adds `template` property to enforce.
1064
- *
1065
- * @param {Function} enforce
1066
- */
1067
-
1068
- function bindTemplate(enforce) {
1069
- enforce.template = withArgs(rules => {
1070
- const template = value => {
1071
- runner(runLazyRules.bind(null, rules), value);
1072
- const proxy = genRuleProxy({}, ruleName => withArgs(args => {
1073
- runner(runtimeRules[ruleName], value, args);
1074
- return proxy;
1075
- }));
1076
- return proxy;
1077
- }; // `run` returns a deep ResultObject
1078
-
1079
-
1080
- template[RUN_RULE] = value => runLazyRules(rules, value); // `test` returns a boolean
1081
-
1082
-
1083
- template[TEST_RULE] = value => runLazyRules(rules, EnforceContext.wrap(value).setFailFast(true)).pass;
1084
-
1085
- return template;
1086
- });
1087
- }
1088
-
1089
- const Enforce = value => {
1090
- const proxy = genRuleProxy({}, ruleName => withArgs(args => {
1091
- runner(runtimeRules[ruleName], value, args);
1092
- return proxy;
1093
- }));
1094
- return proxy;
1095
- };
1096
-
1097
- const enforce = genRuleProxy(Enforce, bindLazyRule);
1098
- bindExtend(enforce, Enforce);
1099
- bindTemplate(enforce);
1100
-
1101
- export default enforce;