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