decoders 2.0.0-beta1 → 2.0.0-beta13

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 (165) hide show
  1. package/CHANGELOG.md +53 -5
  2. package/Decoder.d.ts +94 -0
  3. package/Decoder.js +222 -0
  4. package/Decoder.js.flow +286 -0
  5. package/Decoder.mjs +215 -0
  6. package/NotSupportedTSVersion.d.ts +1 -0
  7. package/README.md +124 -961
  8. package/_utils.d.ts +9 -0
  9. package/{cjs/_utils.js → _utils.js} +12 -18
  10. package/{cjs/_utils.js.flow → _utils.js.flow} +15 -19
  11. package/{es/_utils.js → _utils.mjs} +11 -15
  12. package/{ts/annotate.d.ts → annotate.d.ts} +25 -21
  13. package/{cjs/annotate.js → annotate.js} +0 -0
  14. package/{cjs/annotate.js.flow → annotate.js.flow} +0 -0
  15. package/{es/annotate.js → annotate.mjs} +0 -0
  16. package/format.d.ts +6 -0
  17. package/{cjs/format/inline.js → format.js} +7 -2
  18. package/{cjs/format/inline.js.flow → format.js.flow} +9 -3
  19. package/{es/format/inline.js → format.mjs} +5 -2
  20. package/index.d.ts +40 -0
  21. package/index.js +89 -0
  22. package/index.js.flow +44 -0
  23. package/index.mjs +11 -0
  24. package/{ts → lib}/_helpers.d.ts +0 -0
  25. package/lib/arrays.d.ts +59 -0
  26. package/lib/arrays.js +139 -0
  27. package/lib/arrays.js.flow +138 -0
  28. package/lib/arrays.mjs +124 -0
  29. package/lib/basics.d.ts +93 -0
  30. package/lib/basics.js +144 -0
  31. package/lib/basics.js.flow +124 -0
  32. package/lib/basics.mjs +120 -0
  33. package/lib/booleans.d.ts +16 -0
  34. package/lib/booleans.js +35 -0
  35. package/lib/booleans.js.flow +22 -0
  36. package/lib/booleans.mjs +25 -0
  37. package/lib/dates.d.ts +15 -0
  38. package/lib/dates.js +44 -0
  39. package/lib/dates.js.flow +40 -0
  40. package/lib/dates.mjs +34 -0
  41. package/lib/json.d.ts +35 -0
  42. package/lib/json.js +55 -0
  43. package/lib/json.js.flow +50 -0
  44. package/lib/json.mjs +40 -0
  45. package/lib/numbers.d.ts +31 -0
  46. package/lib/numbers.js +51 -0
  47. package/lib/numbers.js.flow +48 -0
  48. package/lib/numbers.mjs +41 -0
  49. package/lib/objects.d.ts +75 -0
  50. package/lib/objects.js +240 -0
  51. package/lib/objects.js.flow +246 -0
  52. package/lib/objects.mjs +223 -0
  53. package/lib/strings.d.ts +56 -0
  54. package/lib/strings.js +101 -0
  55. package/lib/strings.js.flow +90 -0
  56. package/lib/strings.mjs +82 -0
  57. package/lib/unions.d.ts +55 -0
  58. package/lib/unions.js +160 -0
  59. package/lib/unions.js.flow +155 -0
  60. package/lib/unions.mjs +146 -0
  61. package/lib/utilities.d.ts +34 -0
  62. package/lib/utilities.js +75 -0
  63. package/lib/utilities.js.flow +65 -0
  64. package/lib/utilities.mjs +60 -0
  65. package/package.json +79 -29
  66. package/result.d.ts +16 -0
  67. package/result.js +34 -0
  68. package/result.js.flow +26 -0
  69. package/result.mjs +27 -0
  70. package/cjs/_guard.js +0 -26
  71. package/cjs/_guard.js.flow +0 -20
  72. package/cjs/_types.js +0 -1
  73. package/cjs/_types.js.flow +0 -20
  74. package/cjs/format/index.js +0 -12
  75. package/cjs/format/index.js.flow +0 -4
  76. package/cjs/format/short.js +0 -10
  77. package/cjs/format/short.js.flow +0 -8
  78. package/cjs/index.js +0 -120
  79. package/cjs/index.js.flow +0 -63
  80. package/cjs/result.js +0 -172
  81. package/cjs/result.js.flow +0 -166
  82. package/cjs/stdlib/array.js +0 -108
  83. package/cjs/stdlib/array.js.flow +0 -103
  84. package/cjs/stdlib/boolean.js +0 -44
  85. package/cjs/stdlib/boolean.js.flow +0 -29
  86. package/cjs/stdlib/composition.js +0 -56
  87. package/cjs/stdlib/composition.js.flow +0 -43
  88. package/cjs/stdlib/constants.js +0 -69
  89. package/cjs/stdlib/constants.js.flow +0 -46
  90. package/cjs/stdlib/date.js +0 -46
  91. package/cjs/stdlib/date.js.flow +0 -40
  92. package/cjs/stdlib/describe.js +0 -26
  93. package/cjs/stdlib/describe.js.flow +0 -17
  94. package/cjs/stdlib/dispatch.js +0 -62
  95. package/cjs/stdlib/dispatch.js.flow +0 -58
  96. package/cjs/stdlib/either.js +0 -117
  97. package/cjs/stdlib/either.js.flow +0 -151
  98. package/cjs/stdlib/fail.js +0 -21
  99. package/cjs/stdlib/fail.js.flow +0 -12
  100. package/cjs/stdlib/instanceOf.js +0 -19
  101. package/cjs/stdlib/instanceOf.js.flow +0 -20
  102. package/cjs/stdlib/json.js +0 -31
  103. package/cjs/stdlib/json.js.flow +0 -28
  104. package/cjs/stdlib/lazy.js +0 -16
  105. package/cjs/stdlib/lazy.js.flow +0 -15
  106. package/cjs/stdlib/mapping.js +0 -67
  107. package/cjs/stdlib/mapping.js.flow +0 -54
  108. package/cjs/stdlib/number.js +0 -40
  109. package/cjs/stdlib/number.js.flow +0 -34
  110. package/cjs/stdlib/object.js +0 -194
  111. package/cjs/stdlib/object.js.flow +0 -203
  112. package/cjs/stdlib/optional.js +0 -54
  113. package/cjs/stdlib/optional.js.flow +0 -41
  114. package/cjs/stdlib/string.js +0 -98
  115. package/cjs/stdlib/string.js.flow +0 -82
  116. package/cjs/stdlib/tuple.js +0 -173
  117. package/cjs/stdlib/tuple.js.flow +0 -220
  118. package/es/_guard.js +0 -15
  119. package/es/_types.js +0 -0
  120. package/es/format/index.js +0 -2
  121. package/es/format/short.js +0 -4
  122. package/es/index.js +0 -37
  123. package/es/result.js +0 -139
  124. package/es/stdlib/array.js +0 -91
  125. package/es/stdlib/boolean.js +0 -28
  126. package/es/stdlib/composition.js +0 -42
  127. package/es/stdlib/constants.js +0 -46
  128. package/es/stdlib/date.js +0 -28
  129. package/es/stdlib/describe.js +0 -16
  130. package/es/stdlib/dispatch.js +0 -51
  131. package/es/stdlib/either.js +0 -90
  132. package/es/stdlib/fail.js +0 -11
  133. package/es/stdlib/instanceOf.js +0 -8
  134. package/es/stdlib/json.js +0 -15
  135. package/es/stdlib/lazy.js +0 -11
  136. package/es/stdlib/mapping.js +0 -54
  137. package/es/stdlib/number.js +0 -25
  138. package/es/stdlib/object.js +0 -175
  139. package/es/stdlib/optional.js +0 -38
  140. package/es/stdlib/string.js +0 -76
  141. package/es/stdlib/tuple.js +0 -155
  142. package/ts/_guard.d.ts +0 -7
  143. package/ts/_types.d.ts +0 -16
  144. package/ts/_utils.d.ts +0 -13
  145. package/ts/array.d.ts +0 -5
  146. package/ts/boolean.d.ts +0 -5
  147. package/ts/constants.d.ts +0 -11
  148. package/ts/date.d.ts +0 -4
  149. package/ts/describe.d.ts +0 -3
  150. package/ts/dispatch.d.ts +0 -8
  151. package/ts/either.d.ts +0 -61
  152. package/ts/fail.d.ts +0 -3
  153. package/ts/index.d.ts +0 -42
  154. package/ts/inline.d.ts +0 -3
  155. package/ts/instanceOf.d.ts +0 -3
  156. package/ts/json.d.ts +0 -11
  157. package/ts/lazy.d.ts +0 -3
  158. package/ts/mapping.d.ts +0 -4
  159. package/ts/number.d.ts +0 -6
  160. package/ts/object.d.ts +0 -33
  161. package/ts/optional.d.ts +0 -5
  162. package/ts/result.d.ts +0 -39
  163. package/ts/short.d.ts +0 -3
  164. package/ts/string.d.ts +0 -7
  165. package/ts/tuple.d.ts +0 -30
@@ -1,28 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
- import { map } from './composition';
4
- import { number } from './number';
5
-
6
- /**
7
- * Decoder that only returns Ok for boolean inputs. Err otherwise.
8
- */
9
- var _boolean = function _boolean(blob) {
10
- return typeof blob === 'boolean' ? Result.ok(blob) : Result.err(annotate(blob, 'Must be boolean'));
11
- };
12
- /**
13
- * Decoder that returns true for all truthy values, and false otherwise. Never fails.
14
- */
15
-
16
-
17
- export { _boolean as boolean };
18
- export var truthy = function truthy(blob) {
19
- return Result.ok(!!blob);
20
- };
21
- /**
22
- * Decoder that only returns Ok for numeric input values representing booleans.
23
- * Returns their boolean representation. Err otherwise.
24
- */
25
-
26
- export var numericBoolean = map(number, function (n) {
27
- return !!n;
28
- });
@@ -1,42 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
-
4
- /**
5
- * Given a decoder T and a mapping function from T's to V's, returns a decoder
6
- * for V's. This is useful to change the original input data.
7
- */
8
- export function map(decoder, mapper) {
9
- return compose(decoder, function (x) {
10
- try {
11
- return Result.ok(mapper(x));
12
- } catch (e) {
13
- return Result.err(annotate(x, e instanceof Error ? e.message : String(e)));
14
- }
15
- });
16
- }
17
- /**
18
- * Compose two decoders by passing the result of the first into the second.
19
- * The second decoder may assume as its input type the output type of the first
20
- * decoder (so it's not necessary to accept the typical "mixed"). This is
21
- * useful for "narrowing down" the checks. For example, if you want to write
22
- * a decoder for positive numbers, you can compose it from an existing decoder
23
- * for any number, and a decoder that, assuming a number, checks if it's
24
- * positive. Very often combined with the predicate() helper as the second
25
- * argument.
26
- */
27
-
28
- export function compose(decoder, next) {
29
- return function (blob) {
30
- return Result.andThen(decoder(blob), next);
31
- };
32
- }
33
- /**
34
- * Factory function returning a Decoder<T>, given a predicate function that
35
- * accepts/rejects the input of type T.
36
- */
37
-
38
- export function predicate(predicate, msg) {
39
- return function (value) {
40
- return predicate(value) ? Result.ok(value) : Result.err(annotate(value, msg));
41
- };
42
- }
@@ -1,46 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
-
4
- /**
5
- * Decoder that only returns Ok for `null` inputs. Err otherwise.
6
- */
7
- export var null_ = function null_(blob) {
8
- return blob === null ? Result.ok(blob) : Result.err(annotate(blob, 'Must be null'));
9
- };
10
- /**
11
- * Decoder that only returns Ok for `undefined` inputs. Err otherwise.
12
- */
13
-
14
- export var undefined_ = function undefined_(blob) {
15
- return blob === undefined ? Result.ok(blob) : Result.err(annotate(blob, 'Must be undefined'));
16
- };
17
- /**
18
- * Decoder that only returns Ok for the given value constant. Err otherwise.
19
- */
20
-
21
- export function constant(value) {
22
- return function (blob) {
23
- return blob === value ? Result.ok(value) : Result.err(annotate(blob, "Must be constant " + String(value)));
24
- };
25
- }
26
- /**
27
- * Decoder that always returns Ok for the given hardcoded value, no matter what the input.
28
- */
29
-
30
- export function hardcoded(value) {
31
- return function () {
32
- return Result.ok(value);
33
- };
34
- }
35
- /**
36
- * Decoder that always returns Ok for the given hardcoded value, no matter what the input.
37
- */
38
-
39
- export var unknown = function unknown(blob) {
40
- return Result.ok(blob);
41
- };
42
- /**
43
- * Alias of unknown.
44
- */
45
-
46
- export var mixed = unknown;
package/es/stdlib/date.js DELETED
@@ -1,28 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
- import { isDate } from '../_utils';
4
- import { map } from './composition';
5
- import { regex } from './string';
6
- // Only matches the shape. This "over-matches" some values that still aren't
7
- // valid dates (like 9999-99-99), but those will be caught by JS Date's
8
- // internal validations
9
- var iso8601_re = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?(?:Z|[+-]\d{2}:?\d{2})$/;
10
- export var date = function date(value) {
11
- return isDate(value) ? Result.ok(value) : Result.err(annotate(value, 'Must be a Date'));
12
- };
13
- /**
14
- * Decoder that only returns Ok for strings that are valid ISO8601 date
15
- * strings. Err otherwise.
16
- */
17
-
18
- export var iso8601 = map( // Input itself needs to match the ISO8601 regex...
19
- regex(iso8601_re, 'Must be ISO8601 format'), // Make sure it is a _valid_ date
20
- function (value) {
21
- var date = new Date(value);
22
-
23
- if (isNaN(date.getTime())) {
24
- throw new Error('Must be valid date/time value');
25
- }
26
-
27
- return date;
28
- });
@@ -1,16 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
-
4
- /**
5
- * Wrap another decoder, and override the error message in case it fails. This
6
- * is useful to "simplify" otherwise potentially complex error messages, or to
7
- * use language in those error messages that can be relayed to end users (for
8
- * example to show in form errors).
9
- */
10
- export function describe(decoder, message) {
11
- return function (blob) {
12
- return Result.mapError(decoder(blob), function (err) {
13
- return annotate(err, message);
14
- });
15
- };
16
- }
@@ -1,51 +0,0 @@
1
- import * as Result from '../result';
2
- import { object } from './object';
3
- import { oneOf } from './either';
4
-
5
- /**
6
- * Dispatches to one of several given decoders, based on the value found at
7
- * runtime in the given field. For example, suppose you have these decoders:
8
- *
9
- * const rectangle = object({
10
- * type: constant('rect'),
11
- * x: number,
12
- * y: number,
13
- * width: number,
14
- * height: number,
15
- * });
16
- *
17
- * const circle = object({
18
- * type: constant('circle'),
19
- * cx: number,
20
- * cy: number,
21
- * r: number,
22
- * });
23
- *
24
- * Then these two decoders are equivalent:
25
- *
26
- * const shape = either(rectangle, circle)
27
- * const shape = dispatch('type', { rectangle, circle })
28
- *
29
- * Will be of type Decoder<Rectangle | Circle>.
30
- *
31
- * But the dispatch version will typically be more runtime-efficient. The
32
- * reason is that it will first do minimal work to "look ahead" into the `type`
33
- * field here, and based on that value, pick the decoder to invoke.
34
- *
35
- * The `either` version will simply try to invoke each decoder, until it finds
36
- * one that matches.
37
- *
38
- * Also, the error messages will be less ambiguous using `dispatch()`.
39
- */
40
- export function dispatch(field, mapping) {
41
- var _object;
42
-
43
- var base = object((_object = {}, _object[field] = oneOf(Object.keys(mapping)), _object));
44
- return function (blob) {
45
- return Result.andThen(base(blob), function (baseObj) {
46
- var decoderName = baseObj[field];
47
- var decoder = mapping[decoderName];
48
- return decoder(blob);
49
- });
50
- };
51
- }
@@ -1,90 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
- import { indent, summarize } from '../_utils';
4
-
5
- /**
6
- * Indents and adds a dash in front of this (potentially multiline) string.
7
- */
8
- function itemize(s) {
9
- return '-' + indent(s).substring(1);
10
- }
11
- /**
12
- * Nests another error as an item under a new-to-be-created "Either error". If
13
- * the given subitem already is an "Either error" of itself, don't indent, but
14
- * just "inject" its items at the same error level, for nicely flattened either
15
- * expressions.
16
- *
17
- * Avoids:
18
- *
19
- * Either:
20
- * - Either:
21
- * - Must be P
22
- * - Either:
23
- * - Must be Q
24
- * - Must be R
25
- * - Must be S
26
- *
27
- * And "flattens" these to:
28
- *
29
- * Either:
30
- * - Must be P
31
- * - Must be Q
32
- * - Must be R
33
- * - Must be S
34
- *
35
- */
36
-
37
-
38
- function nest(errText) {
39
- var EITHER_PREFIX = 'Either:\n';
40
- return errText.startsWith(EITHER_PREFIX) ? errText.substr(EITHER_PREFIX.length) : itemize(errText);
41
- }
42
-
43
- export function either(d1, d2) {
44
- return function (blob) {
45
- return Result.orElse(d1(blob), function (err1) {
46
- return Result.orElse(d2(blob), function (err2) {
47
- var serr1 = summarize(err1).join('\n');
48
- var serr2 = summarize(err2).join('\n');
49
- var text = ['Either:', nest(serr1), nest(serr2)].join('\n');
50
- return Result.err(annotate(blob, text));
51
- });
52
- });
53
- };
54
- }
55
- export function either3(d1, d2, d3) {
56
- return either(d1, either(d2, d3));
57
- }
58
- export function either4(d1, d2, d3, d4) {
59
- return either(d1, either3(d2, d3, d4));
60
- }
61
- export function either5(d1, d2, d3, d4, d5) {
62
- return either(d1, either4(d2, d3, d4, d5));
63
- }
64
- export function either6(d1, d2, d3, d4, d5, d6) {
65
- return either(d1, either5(d2, d3, d4, d5, d6));
66
- }
67
- export function either7(d1, d2, d3, d4, d5, d6, d7) {
68
- return either(d1, either6(d2, d3, d4, d5, d6, d7));
69
- }
70
- export function either8(d1, d2, d3, d4, d5, d6, d7, d8) {
71
- return either(d1, either7(d2, d3, d4, d5, d6, d7, d8));
72
- }
73
- export function either9(d1, d2, d3, d4, d5, d6, d7, d8, d9) {
74
- return either(d1, either8(d2, d3, d4, d5, d6, d7, d8, d9));
75
- }
76
- export function oneOf(constants) {
77
- return function (blob) {
78
- var winner = constants.find(function (c) {
79
- return c === blob;
80
- });
81
-
82
- if (winner !== undefined) {
83
- return Result.ok(winner);
84
- }
85
-
86
- return Result.err(annotate(blob, "Must be one of " + constants.map(function (value) {
87
- return JSON.stringify(value);
88
- }).join(', ')));
89
- };
90
- }
package/es/stdlib/fail.js DELETED
@@ -1,11 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
-
4
- /**
5
- * Decoder that always fails with the given error message, no matter what the input.
6
- */
7
- export function fail(msg) {
8
- return function (blob) {
9
- return Result.err(annotate(blob, msg));
10
- };
11
- }
@@ -1,8 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
- export function instanceOf(klass) {
4
- return function (blob) {
5
- return blob instanceof klass ? Result.ok(blob) : Result.err(annotate(blob, "Must be " + // $FlowFixMe[incompatible-use] - klass.name is fine?
6
- klass.name + " instance"));
7
- };
8
- }
package/es/stdlib/json.js DELETED
@@ -1,15 +0,0 @@
1
- import { array } from './array';
2
- import { boolean as _boolean } from './boolean';
3
- import { dict } from './mapping';
4
- import { either6 } from './either';
5
- import { lazy } from './lazy';
6
- import { null_ } from './constants';
7
- import { number } from './number';
8
- import { string } from './string';
9
- export var jsonObject = lazy(function () {
10
- return dict(json);
11
- });
12
- export var jsonArray = lazy(function () {
13
- return array(json);
14
- });
15
- export var json = either6(null_, string, number, _boolean, jsonObject, jsonArray);
package/es/stdlib/lazy.js DELETED
@@ -1,11 +0,0 @@
1
- /**
2
- * Given an function returning a Decoder, will use that decoder to decode the
3
- * value. This is typically used to build decoders for recursive or
4
- * self-referential types.
5
- */
6
- export function lazy(decoderFn) {
7
- return function (blob) {
8
- var decoder = decoderFn();
9
- return decoder(blob);
10
- };
11
- }
@@ -1,54 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotateObject } from '../annotate';
3
- import { compose, map } from './composition';
4
- import { merge } from '../annotate';
5
- import { pojo } from './object';
6
-
7
- /**
8
- * Given an object, will decode a Map of string keys to whatever values.
9
- *
10
- * For example, given a decoder for a Person, we can verify a Person lookup
11
- * table structure (of type Map<string, Person>) like so:
12
- *
13
- * mapping(person)
14
- *
15
- */
16
- export function mapping(decoder) {
17
- return compose(pojo, function (blob) {
18
- var tuples = [];
19
- var errors = null;
20
- Object.keys(blob).forEach(function (key) {
21
- var value = blob[key];
22
- var result = decoder(value);
23
-
24
- if (result.type === 'ok') {
25
- if (errors === null) {
26
- tuples.push([key, result.value]);
27
- }
28
- } else {
29
- tuples.length = 0; // Clear the tuples array
30
-
31
- if (errors === null) {
32
- errors = {};
33
- }
34
-
35
- errors[key] = result.error;
36
- }
37
- });
38
-
39
- if (errors !== null) {
40
- return Result.err(merge(annotateObject(blob), errors));
41
- } else {
42
- return Result.ok(new Map(tuples));
43
- }
44
- });
45
- }
46
- /**
47
- * Like mapping(), but returns an object rather than a Map instance.
48
- */
49
-
50
- export function dict(decoder) {
51
- return map(mapping(decoder), function (m) {
52
- return Object.fromEntries(m);
53
- });
54
- }
@@ -1,25 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
- import { compose, predicate } from './composition';
4
-
5
- var anyNumber = function anyNumber(blob) {
6
- return typeof blob === 'number' && !Number.isNaN(blob) ? Result.ok(blob) : Result.err(annotate(blob, 'Must be number'));
7
- };
8
-
9
- var isInteger = function isInteger(n) {
10
- return Number.isInteger(n);
11
- };
12
-
13
- var isFinite = function isFinite(n) {
14
- return Number.isFinite(n);
15
- };
16
-
17
- export var number = compose(anyNumber, predicate(isFinite, 'Number must be finite'));
18
- export var positiveNumber = compose(number, predicate(function (n) {
19
- return n >= 0;
20
- }, 'Number must be positive')); // Integers
21
-
22
- export var integer = compose(number, predicate(isInteger, 'Number must be an integer'));
23
- export var positiveInteger = compose(integer, predicate(function (n) {
24
- return n >= 0;
25
- }, 'Number must be positive'));
@@ -1,175 +0,0 @@
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
- }
@@ -1,38 +0,0 @@
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
- }