decoders 1.25.4 → 2.0.0-beta1

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 (132) hide show
  1. package/CHANGELOG.md +30 -3
  2. package/cjs/_guard.js +26 -0
  3. package/cjs/_guard.js.flow +20 -0
  4. package/cjs/_types.js +1 -0
  5. package/cjs/_types.js.flow +20 -0
  6. package/cjs/_utils.js +108 -0
  7. package/cjs/_utils.js.flow +97 -0
  8. package/cjs/annotate.js +161 -0
  9. package/cjs/annotate.js.flow +218 -0
  10. package/cjs/format/index.js +12 -0
  11. package/cjs/format/index.js.flow +4 -0
  12. package/cjs/format/inline.js +146 -0
  13. package/cjs/format/inline.js.flow +122 -0
  14. package/cjs/format/short.js +10 -0
  15. package/cjs/format/short.js.flow +8 -0
  16. package/cjs/index.js +120 -0
  17. package/{index.js.flow → cjs/index.js.flow} +31 -24
  18. package/cjs/result.js +172 -0
  19. package/cjs/result.js.flow +166 -0
  20. package/cjs/stdlib/array.js +108 -0
  21. package/{array.js.flow → cjs/stdlib/array.js.flow} +22 -25
  22. package/cjs/stdlib/boolean.js +44 -0
  23. package/{boolean.js.flow → cjs/stdlib/boolean.js.flow} +8 -7
  24. package/cjs/stdlib/composition.js +56 -0
  25. package/{utils.js.flow → cjs/stdlib/composition.js.flow} +7 -22
  26. package/cjs/stdlib/constants.js +69 -0
  27. package/{constants.js.flow → cjs/stdlib/constants.js.flow} +13 -12
  28. package/cjs/stdlib/date.js +46 -0
  29. package/{date.js.flow → cjs/stdlib/date.js.flow} +9 -7
  30. package/cjs/stdlib/describe.js +26 -0
  31. package/{describe.js.flow → cjs/stdlib/describe.js.flow} +4 -4
  32. package/cjs/stdlib/dispatch.js +62 -0
  33. package/{dispatch.js.flow → cjs/stdlib/dispatch.js.flow} +6 -5
  34. package/cjs/stdlib/either.js +117 -0
  35. package/{either.js.flow → cjs/stdlib/either.js.flow} +55 -35
  36. package/cjs/stdlib/fail.js +21 -0
  37. package/cjs/stdlib/fail.js.flow +12 -0
  38. package/cjs/stdlib/instanceOf.js +19 -0
  39. package/{instanceOf.js.flow → cjs/stdlib/instanceOf.js.flow} +7 -8
  40. package/{json.js → cjs/stdlib/json.js} +3 -5
  41. package/{json.js.flow → cjs/stdlib/json.js.flow} +4 -4
  42. package/{lazy.js → cjs/stdlib/lazy.js} +1 -3
  43. package/{lazy.js.flow → cjs/stdlib/lazy.js.flow} +1 -1
  44. package/cjs/stdlib/mapping.js +67 -0
  45. package/cjs/stdlib/mapping.js.flow +54 -0
  46. package/cjs/stdlib/number.js +40 -0
  47. package/{number.js.flow → cjs/stdlib/number.js.flow} +10 -11
  48. package/cjs/stdlib/object.js +194 -0
  49. package/{object.js.flow → cjs/stdlib/object.js.flow} +44 -52
  50. package/cjs/stdlib/optional.js +54 -0
  51. package/{optional.js.flow → cjs/stdlib/optional.js.flow} +6 -7
  52. package/cjs/stdlib/string.js +98 -0
  53. package/{string.js.flow → cjs/stdlib/string.js.flow} +13 -12
  54. package/cjs/stdlib/tuple.js +173 -0
  55. package/{tuple.js.flow → cjs/stdlib/tuple.js.flow} +62 -63
  56. package/es/_guard.js +15 -0
  57. package/es/_types.js +0 -0
  58. package/es/_utils.js +93 -0
  59. package/es/annotate.js +144 -0
  60. package/es/format/index.js +2 -0
  61. package/es/format/inline.js +137 -0
  62. package/es/format/short.js +4 -0
  63. package/es/index.js +37 -0
  64. package/es/result.js +139 -0
  65. package/es/stdlib/array.js +91 -0
  66. package/es/stdlib/boolean.js +28 -0
  67. package/es/stdlib/composition.js +42 -0
  68. package/es/stdlib/constants.js +46 -0
  69. package/es/stdlib/date.js +28 -0
  70. package/{describe.js → es/stdlib/describe.js} +5 -11
  71. package/{dispatch.js → es/stdlib/dispatch.js} +8 -15
  72. package/es/stdlib/either.js +90 -0
  73. package/es/stdlib/fail.js +11 -0
  74. package/es/stdlib/instanceOf.js +8 -0
  75. package/es/stdlib/json.js +15 -0
  76. package/es/stdlib/lazy.js +11 -0
  77. package/es/stdlib/mapping.js +54 -0
  78. package/es/stdlib/number.js +25 -0
  79. package/es/stdlib/object.js +175 -0
  80. package/es/stdlib/optional.js +38 -0
  81. package/{string.js → es/stdlib/string.js} +18 -35
  82. package/es/stdlib/tuple.js +155 -0
  83. package/package.json +12 -7
  84. package/ts/_guard.d.ts +7 -0
  85. package/ts/_helpers.d.ts +79 -0
  86. package/{types.d.ts → ts/_types.d.ts} +3 -5
  87. package/{utils.d.ts → ts/_utils.d.ts} +3 -3
  88. package/ts/annotate.d.ts +58 -0
  89. package/{array.d.ts → ts/array.d.ts} +1 -1
  90. package/{boolean.d.ts → ts/boolean.d.ts} +1 -1
  91. package/{constants.d.ts → ts/constants.d.ts} +1 -1
  92. package/{date.d.ts → ts/date.d.ts} +1 -1
  93. package/{describe.d.ts → ts/describe.d.ts} +1 -1
  94. package/{dispatch.d.ts → ts/dispatch.d.ts} +3 -3
  95. package/{either.d.ts → ts/either.d.ts} +8 -8
  96. package/{fail.d.ts → ts/fail.d.ts} +1 -1
  97. package/ts/index.d.ts +42 -0
  98. package/ts/inline.d.ts +3 -0
  99. package/{instanceOf.d.ts → ts/instanceOf.d.ts} +1 -1
  100. package/{json.d.ts → ts/json.d.ts} +1 -1
  101. package/{lazy.d.ts → ts/lazy.d.ts} +1 -1
  102. package/{mapping.d.ts → ts/mapping.d.ts} +1 -1
  103. package/{number.d.ts → ts/number.d.ts} +1 -1
  104. package/{object.d.ts → ts/object.d.ts} +8 -8
  105. package/{optional.d.ts → ts/optional.d.ts} +1 -1
  106. package/ts/result.d.ts +39 -0
  107. package/ts/short.d.ts +3 -0
  108. package/{string.d.ts → ts/string.d.ts} +1 -1
  109. package/{tuple.d.ts → ts/tuple.d.ts} +5 -5
  110. package/array.js +0 -133
  111. package/boolean.js +0 -42
  112. package/constants.js +0 -67
  113. package/date.js +0 -42
  114. package/either.js +0 -85
  115. package/fail.js +0 -19
  116. package/fail.js.flow +0 -13
  117. package/guard.d.ts +0 -7
  118. package/guard.js +0 -30
  119. package/guard.js.flow +0 -36
  120. package/helpers.d.ts +0 -62
  121. package/index.d.ts +0 -38
  122. package/index.js +0 -397
  123. package/instanceOf.js +0 -17
  124. package/mapping.js +0 -113
  125. package/mapping.js.flow +0 -71
  126. package/number.js +0 -38
  127. package/object.js +0 -254
  128. package/optional.js +0 -52
  129. package/tuple.js +0 -199
  130. package/types.js +0 -5
  131. package/types.js.flow +0 -26
  132. package/utils.js +0 -70
@@ -0,0 +1,175 @@
1
+ function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
2
+
3
+ import * as Result from '../result';
4
+ import { annotate, annotateObject, merge, updateText } from '../annotate';
5
+ import { compose, map } from './composition';
6
+
7
+ function isPojo(o) {
8
+ return o !== null && o !== undefined && typeof o === 'object' && // This still seems to be the only reliable way to determine whether
9
+ // something is a pojo... ¯\_(ツ)_/¯
10
+ // $FlowFixMe[method-unbinding]
11
+ Object.prototype.toString.call(o) === '[object Object]';
12
+ }
13
+
14
+ function subtract(xs, ys) {
15
+ var result = new Set();
16
+ xs.forEach(function (x) {
17
+ if (!ys.has(x)) {
18
+ result.add(x);
19
+ }
20
+ });
21
+ return result;
22
+ }
23
+
24
+ export var pojo = function pojo(blob) {
25
+ return isPojo(blob) ? Result.ok( // NOTE:
26
+ // Since Flow 0.98, typeof o === 'object' refines to
27
+ // {| +[string]: mixed |}
28
+ // instead of
29
+ // {| [string]: mixed |}
30
+ //
31
+ // For rationale, see https://github.com/facebook/flow/issues/7685.
32
+ // In this case, we don't want to output a read-only version of
33
+ // the object because it's up to the user of decoders to
34
+ // determine what they want to do with the decoded output. If they
35
+ // want to write items into the array, that's fine! The fastest
36
+ // way to turn a read-only Object to a writeable one in ES6 seems
37
+ // to be to use object-spread. (Going off this benchmark:
38
+ // https://thecodebarbarian.com/object-assign-vs-object-spread.html)
39
+ _extends({}, blob)) : Result.err(annotate(blob, 'Must be an object'));
40
+ };
41
+ /**
42
+ * Given a mapping of fields-to-decoders, builds a decoder for an object type.
43
+ *
44
+ * For example, given decoders for a number and a string, we can construct an
45
+ * "object description" like so:
46
+ *
47
+ * { id: number, name: string }
48
+ *
49
+ * Which is of type:
50
+ *
51
+ * { id: Decoder<number>, name: Decoder<string> }
52
+ *
53
+ * Passing this to object() will produce the following return type:
54
+ *
55
+ * Decoder<{ id: number, name: string }>
56
+ *
57
+ * Put simply: it'll "peel off" all of the nested Decoders, puts them together
58
+ * in an object, and wraps it in a Decoder<...>.
59
+ */
60
+
61
+ export function object(mapping) {
62
+ var known = new Set(Object.keys(mapping));
63
+ return compose(pojo, function (blob) {
64
+ var actual = new Set(Object.keys(blob)); // At this point, "missing" will also include all fields that may
65
+ // validly be optional. We'll let the underlying decoder decide and
66
+ // remove the key from this missing set if the decoder accepts the
67
+ // value.
68
+
69
+ var missing = subtract(known, actual);
70
+ var record = {};
71
+ var errors = null;
72
+ Object.keys(mapping).forEach(function (key) {
73
+ var decoder = mapping[key];
74
+ var rawValue = blob[key];
75
+ var result = decoder(rawValue);
76
+
77
+ if (result.type === 'ok') {
78
+ var value = result.value;
79
+
80
+ if (value !== undefined) {
81
+ record[key] = value;
82
+ } // If this succeeded, remove the key from the missing keys
83
+ // tracker
84
+
85
+
86
+ missing["delete"](key);
87
+ } else {
88
+ var ann = result.error; // Keep track of the annotation, but don't return just yet. We
89
+ // want to collect more error information.
90
+
91
+ if (rawValue === undefined) {
92
+ // Explicitly add it to the missing set if the value is
93
+ // undefined. This covers explicit undefineds to be
94
+ // treated the same as implicit undefineds (aka missing
95
+ // keys).
96
+ missing.add(key);
97
+ } else {
98
+ if (errors === null) {
99
+ errors = {};
100
+ }
101
+
102
+ errors[key] = ann;
103
+ }
104
+ }
105
+ }); // Deal with errors now. There are two classes of errors we want to
106
+ // report. First of all, we want to report any inline errors in this
107
+ // object. Lastly, any fields that are missing should be annotated on
108
+ // the outer object itself.
109
+
110
+ if (errors || missing.size > 0) {
111
+ var objAnn = annotateObject(blob);
112
+
113
+ if (errors) {
114
+ objAnn = merge(objAnn, errors);
115
+ }
116
+
117
+ if (missing.size > 0) {
118
+ var errMsg = Array.from(missing).map(function (key) {
119
+ return "\"" + key + "\"";
120
+ }).join(', ');
121
+ var pluralized = missing.size > 1 ? 'keys' : 'key';
122
+ objAnn = updateText(objAnn, "Missing " + pluralized + ": " + errMsg);
123
+ }
124
+
125
+ return Result.err(objAnn);
126
+ }
127
+
128
+ return Result.ok(record);
129
+ });
130
+ }
131
+ export function exact(mapping) {
132
+ // Check the inputted object for any superfluous keys
133
+ var allowed = new Set(Object.keys(mapping));
134
+ var checked = compose(pojo, function (blob) {
135
+ var actual = new Set(Object.keys(blob));
136
+ var superfluous = subtract(actual, allowed);
137
+
138
+ if (superfluous.size > 0) {
139
+ return Result.err(annotate(blob, "Superfluous keys: " + Array.from(superfluous).join(', ')));
140
+ }
141
+
142
+ return Result.ok(blob);
143
+ }); // Defer to the "object" decoder for doing the real decoding work. Since
144
+ // we made sure there are no superfluous keys in this structure, it's now
145
+ // safe to force-cast it to an $Exact<> type.
146
+
147
+ var decoder = object(mapping);
148
+ return compose(checked, decoder);
149
+ }
150
+ export function inexact(mapping) {
151
+ return compose(pojo, function (blob) {
152
+ var allkeys = new Set(Object.keys(blob));
153
+ var decoder = map(object(mapping), function (safepart) {
154
+ var safekeys = new Set(Object.keys(mapping)); // To account for hard-coded keys that aren't part of the input
155
+
156
+ safekeys.forEach(function (k) {
157
+ return allkeys.add(k);
158
+ });
159
+ var rv = {};
160
+ allkeys.forEach(function (k) {
161
+ if (safekeys.has(k)) {
162
+ var value = safepart[k];
163
+
164
+ if (value !== undefined) {
165
+ rv[k] = value;
166
+ }
167
+ } else {
168
+ rv[k] = blob[k];
169
+ }
170
+ });
171
+ return rv;
172
+ });
173
+ return decoder(blob);
174
+ });
175
+ }
@@ -0,0 +1,38 @@
1
+ import * as Result from '../result';
2
+ import { annotate } from '../annotate';
3
+ import { either } from './either';
4
+ import { null_, undefined_ } from './constants';
5
+
6
+ /**
7
+ * Builds a Decoder that returns Ok for either `undefined` or `T` values,
8
+ * given a Decoder for `T`. Err otherwise.
9
+ */
10
+ export function optional(decoder) {
11
+ return either(undefined_, decoder);
12
+ }
13
+ /**
14
+ * Builds a Decoder that returns Ok for either `null` or `T` values,
15
+ * given a Decoder for `T`. Err otherwise.
16
+ */
17
+
18
+ export function nullable(decoder) {
19
+ return either(null_, decoder);
20
+ }
21
+ /**
22
+ * Decoder that only returns Ok for `null` or `undefined` inputs.
23
+ * This is effectively equivalent to either(null_, undefined_), but combines
24
+ * their error message output into a single line for convenience.
25
+ */
26
+
27
+ var undefined_or_null = function undefined_or_null(blob) {
28
+ return blob === undefined || blob === null ? Result.ok(blob) : // Combine error message into a single line
29
+ Result.err(annotate(blob, 'Must be undefined or null'));
30
+ };
31
+ /**
32
+ * Decoder that only returns Ok for `null` or `undefined` inputs.
33
+ */
34
+
35
+
36
+ export function maybe(decoder) {
37
+ return either(undefined_or_null, decoder);
38
+ }
@@ -1,17 +1,6 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.nonEmptyString = exports.email = void 0;
7
- exports.regex = regex;
8
- exports.url = exports.string = void 0;
9
-
10
- var _debrief = require("debrief");
11
-
12
- var _Result = require("lemons/Result");
13
-
14
- var _utils = require("./utils");
1
+ import * as Result from '../result';
2
+ import { annotate } from '../annotate';
3
+ import { compose, predicate } from './composition';
15
4
 
16
5
  /** Match groups in this regex:
17
6
  * \1 - the scheme
@@ -27,26 +16,22 @@ var DEFAULT_SCHEMES = ['https'];
27
16
  * Decoder that only returns Ok for string inputs. Err otherwise.
28
17
  */
29
18
 
30
- var string = function string(blob) {
31
- return typeof blob === 'string' ? (0, _Result.Ok)(blob) : (0, _Result.Err)((0, _debrief.annotate)(blob, 'Must be string'));
19
+ export var string = function string(blob) {
20
+ return typeof blob === 'string' ? Result.ok(blob) : Result.err(annotate(blob, 'Must be string'));
32
21
  };
33
22
  /**
34
23
  * Decoder that only returns Ok for non-empty string inputs. Err otherwise.
35
24
  */
36
25
 
37
-
38
- exports.string = string;
39
- var nonEmptyString = regex(/\S/, 'Must be non-empty string');
26
+ export var nonEmptyString = regex(/\S/, 'Must be non-empty string');
40
27
  /**
41
28
  * Decoder that only returns Ok for string inputs that match the regular
42
29
  * expression. Err otherwise. Will always validate that the input is a string
43
30
  * before testing the regex.
44
31
  */
45
32
 
46
- exports.nonEmptyString = nonEmptyString;
47
-
48
- function regex(regex, msg) {
49
- return (0, _utils.compose)(string, (0, _utils.predicate)(function (s) {
33
+ export function regex(regex, msg) {
34
+ return compose(string, predicate(function (s) {
50
35
  return regex.test(s);
51
36
  }, msg));
52
37
  }
@@ -55,8 +40,7 @@ function regex(regex, msg) {
55
40
  * email regex, taken from http://emailregex.com. Err otherwise.
56
41
  */
57
42
 
58
-
59
- var email = regex(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, 'Must be email');
43
+ export var email = regex(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, 'Must be email');
60
44
  /**
61
45
  * Decoder that only returns Ok for string inputs that match URLs of the
62
46
  * expected scheme. Defaults to only accept HTTPS URLs. Err otherwise.
@@ -69,25 +53,24 @@ var email = regex(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@(
69
53
  * - url(['https', 'git+ssh']) accepts both https:// and git+ssh:// URLs
70
54
  */
71
55
 
72
- exports.email = email;
56
+ export var url = function url(schemes) {
57
+ if (schemes === void 0) {
58
+ schemes = DEFAULT_SCHEMES;
59
+ }
73
60
 
74
- var url = function url() {
75
- var schemes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_SCHEMES;
76
- return (0, _utils.compose)(string, function (value) {
61
+ return compose(string, function (value) {
77
62
  var matches = value.match(url_re);
78
63
 
79
64
  if (!matches) {
80
- return (0, _Result.Err)((0, _debrief.annotate)(value, 'Must be URL'));
65
+ return Result.err(annotate(value, 'Must be URL'));
81
66
  } else {
82
67
  var scheme = matches[1];
83
68
 
84
69
  if (schemes.length === 0 || schemes.includes(scheme.toLowerCase())) {
85
- return (0, _Result.Ok)(value);
70
+ return Result.ok(value);
86
71
  } else {
87
- return (0, _Result.Err)((0, _debrief.annotate)(value, "URL scheme must be any of: ".concat(schemes.join(', '))));
72
+ return Result.err(annotate(value, "URL scheme must be any of: " + schemes.join(', ')));
88
73
  }
89
74
  }
90
75
  });
91
- };
92
-
93
- exports.url = url;
76
+ };
@@ -0,0 +1,155 @@
1
+ import { annotate } from '../annotate';
2
+ import { compose, predicate } from './composition';
3
+ import { err, errValue, isErr, ok, unwrap, value } from '../result';
4
+ import { poja } from './array';
5
+
6
+ var ntuple = function ntuple(n) {
7
+ return compose(poja, predicate(function (arr) {
8
+ return arr.length === n;
9
+ }, "Must be a " + n + "-tuple"));
10
+ };
11
+ /**
12
+ * Builds a Decoder that returns Ok for 1-tuple of [T], given a Decoder for T.
13
+ * Err otherwise.
14
+ */
15
+
16
+
17
+ export function tuple1(decoder1) {
18
+ return compose(ntuple(1), function (blobs) {
19
+ var blob1 = blobs[0];
20
+ var result1 = decoder1(blob1);
21
+
22
+ try {
23
+ return ok([unwrap(result1)]);
24
+ } catch (e) {
25
+ // If a decoder error has happened while unwrapping all the
26
+ // results, try to construct a good error message
27
+ return err(annotate(errValue(result1)));
28
+ }
29
+ });
30
+ }
31
+ /**
32
+ * Builds a Decoder that returns Ok for 2-tuples of [T1, T2], given Decoders
33
+ * for T1 and T2. Err otherwise.
34
+ */
35
+
36
+ export function tuple2(decoder1, decoder2) {
37
+ return compose(ntuple(2), function (blobs) {
38
+ var blob1 = blobs[0],
39
+ blob2 = blobs[1];
40
+ var result1 = decoder1(blob1);
41
+ var result2 = decoder2(blob2);
42
+
43
+ try {
44
+ return ok([unwrap(result1), unwrap(result2)]);
45
+ } catch (e) {
46
+ // If a decoder error has happened while unwrapping all the
47
+ // results, try to construct a good error message
48
+ return err(annotate([isErr(result1) ? errValue(result1) : value(result1), isErr(result2) ? errValue(result2) : value(result2)]));
49
+ }
50
+ });
51
+ }
52
+ /**
53
+ * Builds a Decoder that returns Ok for 3-tuples of [T1, T2, T3], given
54
+ * Decoders for T1, T2, and T3. Err otherwise.
55
+ */
56
+
57
+ export function tuple3(decoder1, decoder2, decoder3) {
58
+ return compose(ntuple(3), function (blobs) {
59
+ var blob1 = blobs[0],
60
+ blob2 = blobs[1],
61
+ blob3 = blobs[2];
62
+ var result1 = decoder1(blob1);
63
+ var result2 = decoder2(blob2);
64
+ var result3 = decoder3(blob3);
65
+
66
+ try {
67
+ return ok([unwrap(result1), unwrap(result2), unwrap(result3)]);
68
+ } catch (e) {
69
+ // If a decoder error has happened while unwrapping all the
70
+ // results, try to construct a good error message
71
+ return err(annotate([isErr(result1) ? errValue(result1) : value(result1), isErr(result2) ? errValue(result2) : value(result2), isErr(result3) ? errValue(result3) : value(result3)]));
72
+ }
73
+ });
74
+ }
75
+ /**
76
+ * Builds a Decoder that returns Ok for 4-tuples of [T1, T2, T3, T4], given
77
+ * Decoders for T1, T2, T3, and T4. Err otherwise.
78
+ */
79
+
80
+ export function tuple4(decoder1, decoder2, decoder3, decoder4) {
81
+ return compose(ntuple(4), function (blobs) {
82
+ var blob1 = blobs[0],
83
+ blob2 = blobs[1],
84
+ blob3 = blobs[2],
85
+ blob4 = blobs[3];
86
+ var result1 = decoder1(blob1);
87
+ var result2 = decoder2(blob2);
88
+ var result3 = decoder3(blob3);
89
+ var result4 = decoder4(blob4);
90
+
91
+ try {
92
+ return ok([unwrap(result1), unwrap(result2), unwrap(result3), unwrap(result4)]);
93
+ } catch (e) {
94
+ // If a decoder error has happened while unwrapping all the
95
+ // results, try to construct a good error message
96
+ return err(annotate([isErr(result1) ? errValue(result1) : value(result1), isErr(result2) ? errValue(result2) : value(result2), isErr(result3) ? errValue(result3) : value(result3), isErr(result4) ? errValue(result4) : value(result4)]));
97
+ }
98
+ });
99
+ }
100
+ /**
101
+ * Builds a Decoder that returns Ok for 5-tuples of [T1, T2, T3, T4, T5], given
102
+ * Decoders for T1, T2, T3, T4, and T5. Err otherwise.
103
+ */
104
+
105
+ export function tuple5(decoder1, decoder2, decoder3, decoder4, decoder5) {
106
+ return compose(ntuple(5), function (blobs) {
107
+ var blob1 = blobs[0],
108
+ blob2 = blobs[1],
109
+ blob3 = blobs[2],
110
+ blob4 = blobs[3],
111
+ blob5 = blobs[4];
112
+ var result1 = decoder1(blob1);
113
+ var result2 = decoder2(blob2);
114
+ var result3 = decoder3(blob3);
115
+ var result4 = decoder4(blob4);
116
+ var result5 = decoder5(blob5);
117
+
118
+ try {
119
+ return ok([unwrap(result1), unwrap(result2), unwrap(result3), unwrap(result4), unwrap(result5)]);
120
+ } catch (e) {
121
+ // If a decoder error has happened while unwrapping all the
122
+ // results, try to construct a good error message
123
+ return err(annotate([isErr(result1) ? errValue(result1) : value(result1), isErr(result2) ? errValue(result2) : value(result2), isErr(result3) ? errValue(result3) : value(result3), isErr(result4) ? errValue(result4) : value(result4), isErr(result5) ? errValue(result5) : value(result5)]));
124
+ }
125
+ });
126
+ }
127
+ /**
128
+ * Builds a Decoder that returns Ok for 5-tuples of [T1, T2, T3, T4, T5], given
129
+ * Decoders for T1, T2, T3, T4, T5, and T6. Err otherwise.
130
+ */
131
+
132
+ export function tuple6(decoder1, decoder2, decoder3, decoder4, decoder5, decoder6) {
133
+ return compose(ntuple(6), function (blobs) {
134
+ var blob1 = blobs[0],
135
+ blob2 = blobs[1],
136
+ blob3 = blobs[2],
137
+ blob4 = blobs[3],
138
+ blob5 = blobs[4],
139
+ blob6 = blobs[5];
140
+ var result1 = decoder1(blob1);
141
+ var result2 = decoder2(blob2);
142
+ var result3 = decoder3(blob3);
143
+ var result4 = decoder4(blob4);
144
+ var result5 = decoder5(blob5);
145
+ var result6 = decoder6(blob6);
146
+
147
+ try {
148
+ return ok([unwrap(result1), unwrap(result2), unwrap(result3), unwrap(result4), unwrap(result5), unwrap(result6)]);
149
+ } catch (e) {
150
+ // If a decoder error has happened while unwrapping all the
151
+ // results, try to construct a good error message
152
+ return err(annotate([isErr(result1) ? errValue(result1) : value(result1), isErr(result2) ? errValue(result2) : value(result2), isErr(result3) ? errValue(result3) : value(result3), isErr(result4) ? errValue(result4) : value(result4), isErr(result5) ? errValue(result5) : value(result5), isErr(result6) ? errValue(result6) : value(result6)]));
153
+ }
154
+ });
155
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decoders",
3
- "version": "1.25.4",
3
+ "version": "2.0.0-beta1",
4
4
  "description": "Elegant and battle-tested validation library for type-safe input data (for TypeScript and Flow)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -12,7 +12,16 @@
12
12
  "bugs": {
13
13
  "url": "https://github.com/nvie/decoders/issues"
14
14
  },
15
- "main": "./index.js",
15
+ "main": "./cjs/index.js",
16
+ "module": "./es/index.js",
17
+ "type": "module",
18
+ "exports": {
19
+ "require": "./cjs/index.js",
20
+ "import": "./es/index.js"
21
+ },
22
+ "engines": {
23
+ "node": ">=12"
24
+ },
16
25
  "keywords": [
17
26
  "decoder",
18
27
  "decoders",
@@ -39,11 +48,7 @@
39
48
  "map",
40
49
  "predicate"
41
50
  ],
42
- "dependencies": {
43
- "debrief": "^1.5.0",
44
- "lemons": "^1.4.0"
45
- },
46
- "types": "./index.d.ts",
51
+ "types": "./ts/index.d.ts",
47
52
  "githubUrl": "https://github.com/nvie/decoders",
48
53
  "sideEffects": false
49
54
  }
package/ts/_guard.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { Annotation } from './annotate';
2
+ import { Decoder, Guard } from './_types';
3
+
4
+ export function guard<T>(
5
+ decoder: Decoder<T>,
6
+ formatter?: (annotation: Annotation) => string,
7
+ ): Guard<T>;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Given a type like:
3
+ *
4
+ * {
5
+ * a: string;
6
+ * b: number | undefined;
7
+ * c: null | undefined;
8
+ * d: null;
9
+ * e: undefined;
10
+ * }
11
+ *
12
+ * Will drop all the "undefined" types. In this case, only "e":
13
+ *
14
+ * {
15
+ * a: string;
16
+ * b: number | undefined;
17
+ * c: null | undefined;
18
+ * d: null;
19
+ * }
20
+ *
21
+ */
22
+ type Compact<T> = { [K in IsDefined<T, keyof T>]: T[K] };
23
+
24
+ type IsDefined<T, K extends keyof T> = K extends any
25
+ ? T[K] extends undefined
26
+ ? never
27
+ : K
28
+ : never;
29
+
30
+ //
31
+ // HACK:
32
+ // These weird conditionals test whether TypeScript is configured with the
33
+ // `strictNullChecks` compiler option. We use these definitions to influence
34
+ // what's considered a "required" vs an "optional" key for the AllowImplicit
35
+ // type.
36
+ //
37
+ // If strictNullChecks is false, then we should not be emitting any `?` fields
38
+ // and consider all fields "required" because everything is optional by default
39
+ // in that mode anyway.
40
+ //
41
+ type NoStrictNullChecks = undefined extends string ? 1 : undefined;
42
+ // ^^^^^^^^^^^^^^^^^^^^^^^^
43
+ type StrictNullChecks = undefined extends string ? undefined : 1;
44
+ // ^^^^^^^^^^^^^^^^^^^^^^^^
45
+
46
+ export type RequiredKeys<T> = keyof Compact<{
47
+ [K in keyof T]: undefined extends T[K] ? NoStrictNullChecks : 1;
48
+ }>;
49
+
50
+ export type OptionalKeys<T> = keyof Compact<{
51
+ [K in keyof T]: undefined extends T[K] ? 1 : StrictNullChecks;
52
+ }>;
53
+
54
+ /**
55
+ * Transforms an object type, by marking all fields that contain "undefined"
56
+ * with a question mark, i.e. allowing implicit-undefineds when
57
+ * explicit-undefined are also allowed.
58
+ *
59
+ * For example, if:
60
+ *
61
+ * type User = {
62
+ * name: string;
63
+ * age: number | null | undefined;
64
+ * }
65
+ *
66
+ * Then AllowImplicit<User> will become equivalent to:
67
+ *
68
+ * {
69
+ * name: string;
70
+ * age?: number | null;
71
+ * ^
72
+ * Note the question mark
73
+ * }
74
+ */
75
+ type AllowImplicit<T> = { [K in RequiredKeys<T>]-?: T[K] } & {
76
+ [K in OptionalKeys<T>]+?: Exclude<T[K], undefined>;
77
+ };
78
+
79
+ export { AllowImplicit };
@@ -1,5 +1,5 @@
1
- import { Annotation } from 'debrief';
2
- import Result from 'lemons/Result';
1
+ import { Annotation } from './annotate';
2
+ import { Result } from './result';
3
3
 
4
4
  export type Scalar = string | number | boolean | symbol | undefined | null;
5
5
 
@@ -7,12 +7,10 @@ export interface Guard<T> {
7
7
  (blob: unknown): T;
8
8
  }
9
9
  export type Predicate<T> = (value: T) => boolean;
10
- export type DecodeResult<T> = Result<Annotation, T>;
10
+ export type DecodeResult<T> = Result<T, Annotation>;
11
11
  export interface Decoder<T, F = unknown> {
12
12
  (blob: F): DecodeResult<T>;
13
13
  }
14
14
 
15
15
  export type DecoderType<T> = T extends Decoder<infer V> ? V : never;
16
- export type $DecoderType<T> = DecoderType<T>; // Alias for backward compatibility
17
-
18
16
  export type GuardType<T> = T extends Guard<infer V> ? V : never;
@@ -1,13 +1,13 @@
1
- import { Decoder } from './types';
1
+ import { Decoder } from './_types';
2
2
 
3
3
  export function isDate(value: unknown): boolean;
4
4
  export function map<T, V>(decoder: Decoder<T>, mapper: (value: T) => V): Decoder<V>;
5
5
  export function compose<T, V>(decoder: Decoder<T>, next: Decoder<V, T>): Decoder<V>;
6
6
  export function predicate<T extends F, F = unknown>(
7
7
  predicate: (value: F) => value is T,
8
- msg: string
8
+ msg: string,
9
9
  ): Decoder<T, F>;
10
10
  export function predicate<T>(
11
11
  predicate: (value: T) => boolean,
12
- msg: string
12
+ msg: string,
13
13
  ): Decoder<T, T>;
@@ -0,0 +1,58 @@
1
+ export interface ObjectAnnotation {
2
+ type: 'object';
3
+ fields: { [key: string]: Annotation };
4
+ text?: string;
5
+ }
6
+
7
+ export interface ArrayAnnotation {
8
+ type: 'array';
9
+ items: readonly Annotation[];
10
+ text?: string;
11
+ }
12
+
13
+ export interface ScalarAnnotation {
14
+ type: 'scalar';
15
+ value: unknown;
16
+ text?: string;
17
+ }
18
+
19
+ export interface FunctionAnnotation {
20
+ type: 'function';
21
+ text?: string;
22
+ }
23
+
24
+ export interface CircularRefAnnotation {
25
+ type: 'circular-ref';
26
+ text?: string;
27
+ }
28
+
29
+ export type Annotation =
30
+ | ObjectAnnotation
31
+ | ArrayAnnotation
32
+ | ScalarAnnotation
33
+ | FunctionAnnotation
34
+ | CircularRefAnnotation;
35
+
36
+ export function object(
37
+ fields: { [key: string]: Annotation },
38
+ text?: string,
39
+ ): ObjectAnnotation;
40
+ export function array(items: readonly Annotation[], text?: string): ArrayAnnotation;
41
+ export function func(text?: string): FunctionAnnotation;
42
+ export function scalar(value: unknown, text?: string): ScalarAnnotation;
43
+ export function circularRef(text?: string): CircularRefAnnotation;
44
+
45
+ export function updateText<A extends Annotation>(annotation: A, text?: string): A;
46
+
47
+ export function merge(
48
+ objAnnotation: ObjectAnnotation,
49
+ fields: { [key: string]: Annotation },
50
+ ): ObjectAnnotation;
51
+
52
+ export function asAnnotation(thing: unknown): Annotation | void;
53
+
54
+ export function annotate(value: unknown, text?: string): Annotation;
55
+ export function annotateObject(
56
+ obj: { [key: string]: unknown },
57
+ text?: string,
58
+ ): ObjectAnnotation;