decoders 1.25.5 → 2.0.0-beta10

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 (124) hide show
  1. package/CHANGELOG.md +53 -3
  2. package/Decoder.d.ts +27 -0
  3. package/Decoder.js +199 -0
  4. package/Decoder.js.flow +224 -0
  5. package/Decoder.mjs +192 -0
  6. package/NotSupportedTSVersion.d.ts +1 -0
  7. package/README.md +105 -961
  8. package/_utils.d.ts +9 -0
  9. package/_utils.js +102 -0
  10. package/_utils.js.flow +93 -0
  11. package/_utils.mjs +89 -0
  12. package/annotate.d.ts +62 -0
  13. package/annotate.js +161 -0
  14. package/annotate.js.flow +218 -0
  15. package/annotate.mjs +144 -0
  16. package/format.d.ts +4 -0
  17. package/format.js +151 -0
  18. package/format.js.flow +126 -0
  19. package/format.mjs +140 -0
  20. package/index.d.ts +38 -36
  21. package/index.js +69 -376
  22. package/index.js.flow +39 -51
  23. package/index.mjs +11 -0
  24. package/{helpers.d.ts → lib/_helpers.d.ts} +0 -0
  25. package/lib/arrays.d.ts +37 -0
  26. package/lib/arrays.js +138 -0
  27. package/lib/arrays.js.flow +138 -0
  28. package/lib/arrays.mjs +123 -0
  29. package/lib/basics.d.ts +14 -0
  30. package/lib/basics.js +109 -0
  31. package/lib/basics.js.flow +85 -0
  32. package/lib/basics.mjs +85 -0
  33. package/{boolean.d.ts → lib/booleans.d.ts} +1 -1
  34. package/lib/booleans.js +35 -0
  35. package/lib/booleans.js.flow +22 -0
  36. package/lib/booleans.mjs +25 -0
  37. package/{date.d.ts → lib/dates.d.ts} +1 -1
  38. package/lib/dates.js +44 -0
  39. package/lib/dates.js.flow +40 -0
  40. package/lib/dates.mjs +34 -0
  41. package/{json.d.ts → lib/json.d.ts} +1 -1
  42. package/lib/json.js +55 -0
  43. package/lib/json.js.flow +50 -0
  44. package/lib/json.mjs +40 -0
  45. package/{number.d.ts → lib/numbers.d.ts} +2 -1
  46. package/lib/numbers.js +52 -0
  47. package/lib/numbers.js.flow +49 -0
  48. package/lib/numbers.mjs +42 -0
  49. package/{object.d.ts → lib/objects.d.ts} +11 -6
  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 +13 -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 +78 -0
  58. package/lib/unions.js +161 -0
  59. package/lib/unions.js.flow +158 -0
  60. package/lib/unions.mjs +145 -0
  61. package/lib/utilities.d.ts +10 -0
  62. package/lib/utilities.js +94 -0
  63. package/lib/utilities.js.flow +84 -0
  64. package/lib/utilities.mjs +79 -0
  65. package/package.json +78 -23
  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/array.d.ts +0 -5
  71. package/array.js +0 -133
  72. package/array.js.flow +0 -106
  73. package/boolean.js +0 -42
  74. package/boolean.js.flow +0 -28
  75. package/constants.d.ts +0 -11
  76. package/constants.js +0 -67
  77. package/constants.js.flow +0 -45
  78. package/date.js +0 -42
  79. package/date.js.flow +0 -38
  80. package/describe.d.ts +0 -3
  81. package/describe.js +0 -22
  82. package/describe.js.flow +0 -17
  83. package/dispatch.d.ts +0 -8
  84. package/dispatch.js +0 -58
  85. package/dispatch.js.flow +0 -57
  86. package/either.d.ts +0 -61
  87. package/either.js +0 -85
  88. package/either.js.flow +0 -131
  89. package/fail.d.ts +0 -3
  90. package/fail.js +0 -19
  91. package/fail.js.flow +0 -13
  92. package/guard.d.ts +0 -7
  93. package/guard.js +0 -30
  94. package/guard.js.flow +0 -36
  95. package/instanceOf.d.ts +0 -3
  96. package/instanceOf.js +0 -17
  97. package/instanceOf.js.flow +0 -21
  98. package/json.js +0 -33
  99. package/json.js.flow +0 -28
  100. package/lazy.d.ts +0 -3
  101. package/lazy.js +0 -18
  102. package/lazy.js.flow +0 -15
  103. package/mapping.d.ts +0 -4
  104. package/mapping.js +0 -113
  105. package/mapping.js.flow +0 -71
  106. package/number.js +0 -38
  107. package/number.js.flow +0 -35
  108. package/object.js +0 -254
  109. package/object.js.flow +0 -211
  110. package/optional.d.ts +0 -5
  111. package/optional.js +0 -52
  112. package/optional.js.flow +0 -42
  113. package/string.d.ts +0 -7
  114. package/string.js +0 -93
  115. package/string.js.flow +0 -81
  116. package/tuple.d.ts +0 -30
  117. package/tuple.js +0 -199
  118. package/tuple.js.flow +0 -221
  119. package/types.d.ts +0 -18
  120. package/types.js +0 -5
  121. package/types.js.flow +0 -26
  122. package/utils.d.ts +0 -13
  123. package/utils.js +0 -70
  124. package/utils.js.flow +0 -58
package/index.js.flow CHANGED
@@ -1,56 +1,44 @@
1
1
  // @flow strict
2
2
 
3
- /**
4
- * Elm-like JSON decoders, for use with Flow.
5
- * See http://elmplayground.com/decoding-json-in-elm-1 for an introduction.
6
- *
7
- * Why? All JSON responses coming from our API endpoints are just that: free-form
8
- * JSON data. To Flow, the only type classification possilbe is "any" -- effectively
9
- * turning off all type checks for anything related to JSON. To the receiving end
10
- * (our frontend), the structure of that data is completely opaque to any type
11
- * checkers since JSON values can be anything: an object, an array, null, a string,
12
- * a bool, etc. Our type system is not a runtime type system, so we need a way of
13
- * "converting" an any-type JSON value into a type that we want to work with in our
14
- * frontend code base.
15
- *
16
- * Elm's solution to this problem is to define composable decoders: functions that
17
- * take anything and either fail with an error, or guarantee to return the expected
18
- * type. In our case, it's fine to fail with a runtime error.
19
- *
20
- */
21
- import type { $DecoderType, $GuardType, Decoder, Guard } from './types';
3
+ export type { Decoder, DecodeResult, DecoderType, Scalar } from './Decoder';
4
+ export type { JSONValue, JSONObject, JSONArray } from './lib/json';
22
5
 
23
- export { guard } from './guard';
24
- export { compose, map, predicate } from './utils';
6
+ export { define } from './Decoder';
25
7
 
26
- export { array, nonEmptyArray, poja } from './array';
27
- export { boolean, numericBoolean, truthy } from './boolean';
28
- export { constant, hardcoded, mixed, null_, undefined_, unknown } from './constants';
29
- export { date, iso8601 } from './date';
30
- export { describe } from './describe';
31
- export { dispatch } from './dispatch';
32
8
  export {
33
- either,
34
- either3,
35
- either4,
36
- either5,
37
- either6,
38
- either7,
39
- either8,
40
- either9,
41
- oneOf,
42
- } from './either';
43
- export { fail } from './fail';
44
- export { instanceOf } from './instanceOf';
45
- export { json, jsonObject, jsonArray } from './json';
46
- export { lazy } from './lazy';
47
- export { mapping, dict } from './mapping';
48
- export { integer, number, positiveInteger, positiveNumber } from './number';
49
- export { exact, inexact, object, pojo } from './object';
50
- export { maybe, nullable, optional } from './optional';
51
- export { email, nonEmptyString, regex, string, url } from './string';
52
- export { tuple1, tuple2, tuple3, tuple4, tuple5, tuple6 } from './tuple';
53
-
54
- export type { Decoder, Guard };
55
- export type { $DecoderType, $GuardType };
56
- export type { JSONValue, JSONObject, JSONArray } from './json';
9
+ always,
10
+ constant,
11
+ hardcoded,
12
+ maybe,
13
+ mixed,
14
+ nullable,
15
+ null_,
16
+ optional,
17
+ undefined_,
18
+ unknown,
19
+ } from './lib/basics';
20
+ export { array, nonEmptyArray, poja, set, tuple } from './lib/arrays';
21
+ export { boolean, numericBoolean, truthy } from './lib/booleans';
22
+ export { date, iso8601 } from './lib/dates';
23
+ export { dict, exact, inexact, mapping, object, pojo } from './lib/objects';
24
+ export { either, oneOf, taggedUnion, dispatch } from './lib/unions';
25
+ export {
26
+ email,
27
+ httpsUrl,
28
+ nonEmptyString,
29
+ regex,
30
+ string,
31
+ url,
32
+ uuid,
33
+ uuidv1,
34
+ uuidv4,
35
+ } from './lib/strings';
36
+ export { fail, instanceOf, lazy, never, prep } from './lib/utilities';
37
+ export {
38
+ anyNumber,
39
+ integer,
40
+ number,
41
+ positiveInteger,
42
+ positiveNumber,
43
+ } from './lib/numbers';
44
+ export { json, jsonObject, jsonArray } from './lib/json';
package/index.mjs ADDED
@@ -0,0 +1,11 @@
1
+ export { define } from './Decoder.mjs';
2
+ export { always, constant, hardcoded, maybe, mixed, nullable, null_, optional, undefined_, unknown } from './lib/basics.mjs';
3
+ export { array, nonEmptyArray, poja, set, tuple } from './lib/arrays.mjs';
4
+ export { boolean, numericBoolean, truthy } from './lib/booleans.mjs';
5
+ export { date, iso8601 } from './lib/dates.mjs';
6
+ export { dict, exact, inexact, mapping, object, pojo } from './lib/objects.mjs';
7
+ export { either, oneOf, taggedUnion, dispatch } from './lib/unions.mjs';
8
+ export { email, httpsUrl, nonEmptyString, regex, string, url, uuid, uuidv1, uuidv4 } from './lib/strings.mjs';
9
+ export { fail, instanceOf, lazy, never, prep } from './lib/utilities.mjs';
10
+ export { anyNumber, integer, number, positiveInteger, positiveNumber } from './lib/numbers.mjs';
11
+ export { json, jsonObject, jsonArray } from './lib/json.mjs';
File without changes
@@ -0,0 +1,37 @@
1
+ /// <reference lib="es6" />
2
+
3
+ import { Decoder } from '../Decoder';
4
+
5
+ export const poja: Decoder<unknown[]>;
6
+ export function array<T>(decoder: Decoder<T>): Decoder<T[]>;
7
+ export function nonEmptyArray<T>(decoder: Decoder<T>): Decoder<[T, ...T[]]>;
8
+ export function set<T>(decoder: Decoder<T>): Decoder<Set<T>>;
9
+
10
+ export function tuple<A>(a: Decoder<A>): Decoder<[A]>;
11
+ export function tuple<A, B>(a: Decoder<A>, b: Decoder<B>): Decoder<[A, B]>;
12
+ export function tuple<A, B, C>(
13
+ a: Decoder<A>,
14
+ b: Decoder<B>,
15
+ c: Decoder<C>,
16
+ ): Decoder<[A, B, C]>;
17
+ export function tuple<A, B, C, D>(
18
+ a: Decoder<A>,
19
+ b: Decoder<B>,
20
+ c: Decoder<C>,
21
+ d: Decoder<D>,
22
+ ): Decoder<[A, B, C, D]>;
23
+ export function tuple<A, B, C, D, E>(
24
+ a: Decoder<A>,
25
+ b: Decoder<B>,
26
+ c: Decoder<C>,
27
+ d: Decoder<D>,
28
+ e: Decoder<E>,
29
+ ): Decoder<[A, B, C, D, E]>;
30
+ export function tuple<A, B, C, D, E, F>(
31
+ a: Decoder<A>,
32
+ b: Decoder<B>,
33
+ c: Decoder<C>,
34
+ d: Decoder<D>,
35
+ e: Decoder<E>,
36
+ f: Decoder<F>,
37
+ ): Decoder<[A, B, C, D, E, F]>;
package/lib/arrays.js ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.array = array;
5
+ exports.nonEmptyArray = nonEmptyArray;
6
+ exports.poja = void 0;
7
+ exports.set = set;
8
+ exports.tuple = void 0;
9
+
10
+ var _annotate = require("../annotate");
11
+
12
+ var _Decoder = require("../Decoder");
13
+
14
+ /**
15
+ * Accepts any array, but doesn't validate its items further.
16
+ *
17
+ * "poja" means "plain old JavaScript array", a play on `pojo()`.
18
+ */
19
+ var poja = (0, _Decoder.define)(function (blob, ok, err) {
20
+ if (!Array.isArray(blob)) {
21
+ return err('Must be an array');
22
+ }
23
+
24
+ return ok( // NOTE: Since Flow 0.98, Array.isArray() returns $ReadOnlyArray<mixed>
25
+ // instead of Array<mixed>. For rationale, see
26
+ // https://github.com/facebook/flow/issues/7684. In this case, we
27
+ // don't want to output read-only types because it's up to the user of
28
+ // decoders to determine what they want to do with the decoded output.
29
+ // If they want to write items into the array, that's fine!
30
+ // The fastest way to turn a read-only array into a normal array in
31
+ // Javascript is to use .slice() on it, see this benchmark:
32
+ // http://jsben.ch/lO6C5
33
+ blob.slice());
34
+ });
35
+ /**
36
+ * Given an array of Result instances, loop over them all and return:
37
+ * - An [index, err] tuple, indicating the (index of the) first Err instance
38
+ * encountered; or
39
+ * - a new Ok with an array of all unwrapped Ok'ed values
40
+ */
41
+
42
+ exports.poja = poja;
43
+
44
+ function all(items, blobs, // TODO: Make this less ugly
45
+ ok, err) {
46
+ var results = [];
47
+
48
+ for (var index = 0; index < items.length; ++index) {
49
+ var result = items[index];
50
+
51
+ if (result.ok) {
52
+ results.push(result.value);
53
+ } else {
54
+ var ann = result.error; // Rewrite the annotation to include the index information, and inject it into the original blob
55
+
56
+ var clone = [].concat(blobs);
57
+ clone.splice(index, 1, (0, _annotate.annotate)(ann, ann.text ? ann.text + " (at index " + index + ")" : "index " + index));
58
+ return err((0, _annotate.annotate)(clone));
59
+ }
60
+ }
61
+
62
+ return ok(results);
63
+ }
64
+ /**
65
+ * Accepts arrays of whatever the given decoder accepts.
66
+ */
67
+
68
+
69
+ function array(decoder) {
70
+ return poja.then(function (blobs, ok, err) {
71
+ var results = blobs.map(decoder.decode);
72
+ return all(results, blobs, ok, err);
73
+ });
74
+ }
75
+ /**
76
+ * Like `array()`, but will reject arrays with 0 elements.
77
+ */
78
+
79
+
80
+ function nonEmptyArray(decoder) {
81
+ return array(decoder).refine(function (arr) {
82
+ return arr.length > 0;
83
+ }, 'Must be non-empty array');
84
+ }
85
+ /**
86
+ * Similar to `array()`, but returns the result as an [ES6
87
+ * Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set).
88
+ */
89
+
90
+
91
+ function set(decoder) {
92
+ return array(decoder).transform(function (items) {
93
+ return new Set(items);
94
+ });
95
+ }
96
+
97
+ var ntuple = function ntuple(n) {
98
+ return poja.refine(function (arr) {
99
+ return arr.length === n;
100
+ }, "Must be a " + n + "-tuple");
101
+ }; // prettier-ignore
102
+
103
+
104
+ /**
105
+ * Accepts a tuple (an array with exactly _n_ items) of values accepted by the
106
+ * _n_ given decoders.
107
+ */
108
+ function _tuple() {
109
+ for (var _len = arguments.length, decoders = new Array(_len), _key = 0; _key < _len; _key++) {
110
+ decoders[_key] = arguments[_key];
111
+ }
112
+
113
+ return ntuple(decoders.length).then(function (blobs, ok, err) {
114
+ var allOk = true;
115
+ var rvs = decoders.map(function (decoder, i) {
116
+ var blob = blobs[i];
117
+ var result = decoder.decode(blob);
118
+
119
+ if (result.ok) {
120
+ return result.value;
121
+ } else {
122
+ allOk = false;
123
+ return result.error;
124
+ }
125
+ });
126
+
127
+ if (allOk) {
128
+ return ok(rvs);
129
+ } else {
130
+ // If a decoder error has happened while unwrapping all the
131
+ // results, try to construct a good error message
132
+ return err((0, _annotate.annotate)(rvs));
133
+ }
134
+ });
135
+ }
136
+
137
+ var tuple = _tuple;
138
+ exports.tuple = tuple;
@@ -0,0 +1,138 @@
1
+ // @flow strict
2
+
3
+ import { annotate } from '../annotate';
4
+ import { define } from '../Decoder';
5
+ import type { _Any } from '../_utils';
6
+ import type { Annotation } from '../annotate';
7
+ import type { Decoder, DecodeResult } from '../Decoder';
8
+
9
+ /**
10
+ * Accepts any array, but doesn't validate its items further.
11
+ *
12
+ * "poja" means "plain old JavaScript array", a play on `pojo()`.
13
+ */
14
+ export const poja: Decoder<Array<mixed>> = define((blob, ok, err) => {
15
+ if (!Array.isArray(blob)) {
16
+ return err('Must be an array');
17
+ }
18
+ return ok(
19
+ // NOTE: Since Flow 0.98, Array.isArray() returns $ReadOnlyArray<mixed>
20
+ // instead of Array<mixed>. For rationale, see
21
+ // https://github.com/facebook/flow/issues/7684. In this case, we
22
+ // don't want to output read-only types because it's up to the user of
23
+ // decoders to determine what they want to do with the decoded output.
24
+ // If they want to write items into the array, that's fine!
25
+ // The fastest way to turn a read-only array into a normal array in
26
+ // Javascript is to use .slice() on it, see this benchmark:
27
+ // http://jsben.ch/lO6C5
28
+ blob.slice(),
29
+ );
30
+ });
31
+
32
+ /**
33
+ * Given an array of Result instances, loop over them all and return:
34
+ * - An [index, err] tuple, indicating the (index of the) first Err instance
35
+ * encountered; or
36
+ * - a new Ok with an array of all unwrapped Ok'ed values
37
+ */
38
+ function all<T>(
39
+ items: $ReadOnlyArray<DecodeResult<T>>,
40
+ blobs: $ReadOnlyArray<mixed>,
41
+
42
+ // TODO: Make this less ugly
43
+ ok: (Array<T>) => DecodeResult<Array<T>>,
44
+ err: (Annotation) => DecodeResult<Array<T>>,
45
+ ): DecodeResult<Array<T>> {
46
+ const results: Array<T> = [];
47
+ for (let index = 0; index < items.length; ++index) {
48
+ const result = items[index];
49
+ if (result.ok) {
50
+ results.push(result.value);
51
+ } else {
52
+ const ann = result.error;
53
+
54
+ // Rewrite the annotation to include the index information, and inject it into the original blob
55
+ const clone = [...blobs];
56
+ clone.splice(
57
+ index,
58
+ 1,
59
+ annotate(
60
+ ann,
61
+ ann.text ? `${ann.text} (at index ${index})` : `index ${index}`,
62
+ ),
63
+ );
64
+
65
+ return err(annotate(clone));
66
+ }
67
+ }
68
+ return ok(results);
69
+ }
70
+
71
+ /**
72
+ * Accepts arrays of whatever the given decoder accepts.
73
+ */
74
+ export function array<T>(decoder: Decoder<T>): Decoder<Array<T>> {
75
+ return poja.then((blobs: $ReadOnlyArray<mixed>, ok, err) => {
76
+ const results = blobs.map(decoder.decode);
77
+ return all(results, blobs, ok, err);
78
+ });
79
+ }
80
+
81
+ /**
82
+ * Like `array()`, but will reject arrays with 0 elements.
83
+ */
84
+ export function nonEmptyArray<T>(decoder: Decoder<T>): Decoder<Array<T>> {
85
+ return array(decoder).refine((arr) => arr.length > 0, 'Must be non-empty array');
86
+ }
87
+
88
+ /**
89
+ * Similar to `array()`, but returns the result as an [ES6
90
+ * Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set).
91
+ */
92
+ export function set<T>(decoder: Decoder<T>): Decoder<Set<T>> {
93
+ return array(decoder).transform((items) => new Set(items));
94
+ }
95
+
96
+ const ntuple = (n: number) =>
97
+ poja.refine((arr) => arr.length === n, `Must be a ${n}-tuple`);
98
+
99
+ // prettier-ignore
100
+ interface TupleFuncSignature {
101
+ <A>(a: Decoder<A>): Decoder<[A]>;
102
+ <A, B>(a: Decoder<A>, b: Decoder<B>): Decoder<[A, B]>;
103
+ <A, B, C>(a: Decoder<A>, b: Decoder<B>, c: Decoder<C>): Decoder<[A, B, C]>;
104
+ <A, B, C, D>(a: Decoder<A>, b: Decoder<B>, c: Decoder<C>, d: Decoder<D>): Decoder<[A, B, C, D]>;
105
+ <A, B, C, D, E>(a: Decoder<A>, b: Decoder<B>, c: Decoder<C>, d: Decoder<D>, e: Decoder<E>): Decoder<[A, B, C, D, E]>;
106
+ <A, B, C, D, E, F>(a: Decoder<A>, b: Decoder<B>, c: Decoder<C>, d: Decoder<D>, e: Decoder<E>, f: Decoder<F>): Decoder<[A, B, C, D, E, F]>;
107
+ }
108
+
109
+ /**
110
+ * Accepts a tuple (an array with exactly _n_ items) of values accepted by the
111
+ * _n_ given decoders.
112
+ */
113
+ function _tuple(...decoders: $ReadOnlyArray<Decoder<mixed>>): Decoder<Array<mixed>> {
114
+ return ntuple(decoders.length).then((blobs, ok, err) => {
115
+ let allOk = true;
116
+
117
+ const rvs = decoders.map((decoder, i) => {
118
+ const blob = blobs[i];
119
+ const result = decoder.decode(blob);
120
+ if (result.ok) {
121
+ return result.value;
122
+ } else {
123
+ allOk = false;
124
+ return result.error;
125
+ }
126
+ });
127
+
128
+ if (allOk) {
129
+ return ok(rvs);
130
+ } else {
131
+ // If a decoder error has happened while unwrapping all the
132
+ // results, try to construct a good error message
133
+ return err(annotate(rvs));
134
+ }
135
+ });
136
+ }
137
+
138
+ export const tuple: TupleFuncSignature = (_tuple: _Any);
package/lib/arrays.mjs ADDED
@@ -0,0 +1,123 @@
1
+ import { annotate } from '../annotate.mjs';
2
+ import { define } from '../Decoder.mjs';
3
+
4
+ /**
5
+ * Accepts any array, but doesn't validate its items further.
6
+ *
7
+ * "poja" means "plain old JavaScript array", a play on `pojo()`.
8
+ */
9
+ export var poja = define(function (blob, ok, err) {
10
+ if (!Array.isArray(blob)) {
11
+ return err('Must be an array');
12
+ }
13
+
14
+ return ok( // NOTE: Since Flow 0.98, Array.isArray() returns $ReadOnlyArray<mixed>
15
+ // instead of Array<mixed>. For rationale, see
16
+ // https://github.com/facebook/flow/issues/7684. In this case, we
17
+ // don't want to output read-only types because it's up to the user of
18
+ // decoders to determine what they want to do with the decoded output.
19
+ // If they want to write items into the array, that's fine!
20
+ // The fastest way to turn a read-only array into a normal array in
21
+ // Javascript is to use .slice() on it, see this benchmark:
22
+ // http://jsben.ch/lO6C5
23
+ blob.slice());
24
+ });
25
+ /**
26
+ * Given an array of Result instances, loop over them all and return:
27
+ * - An [index, err] tuple, indicating the (index of the) first Err instance
28
+ * encountered; or
29
+ * - a new Ok with an array of all unwrapped Ok'ed values
30
+ */
31
+
32
+ function all(items, blobs, // TODO: Make this less ugly
33
+ ok, err) {
34
+ var results = [];
35
+
36
+ for (var index = 0; index < items.length; ++index) {
37
+ var result = items[index];
38
+
39
+ if (result.ok) {
40
+ results.push(result.value);
41
+ } else {
42
+ var ann = result.error; // Rewrite the annotation to include the index information, and inject it into the original blob
43
+
44
+ var clone = [].concat(blobs);
45
+ clone.splice(index, 1, annotate(ann, ann.text ? ann.text + " (at index " + index + ")" : "index " + index));
46
+ return err(annotate(clone));
47
+ }
48
+ }
49
+
50
+ return ok(results);
51
+ }
52
+ /**
53
+ * Accepts arrays of whatever the given decoder accepts.
54
+ */
55
+
56
+
57
+ export function array(decoder) {
58
+ return poja.then(function (blobs, ok, err) {
59
+ var results = blobs.map(decoder.decode);
60
+ return all(results, blobs, ok, err);
61
+ });
62
+ }
63
+ /**
64
+ * Like `array()`, but will reject arrays with 0 elements.
65
+ */
66
+
67
+ export function nonEmptyArray(decoder) {
68
+ return array(decoder).refine(function (arr) {
69
+ return arr.length > 0;
70
+ }, 'Must be non-empty array');
71
+ }
72
+ /**
73
+ * Similar to `array()`, but returns the result as an [ES6
74
+ * Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set).
75
+ */
76
+
77
+ export function set(decoder) {
78
+ return array(decoder).transform(function (items) {
79
+ return new Set(items);
80
+ });
81
+ }
82
+
83
+ var ntuple = function ntuple(n) {
84
+ return poja.refine(function (arr) {
85
+ return arr.length === n;
86
+ }, "Must be a " + n + "-tuple");
87
+ }; // prettier-ignore
88
+
89
+
90
+ /**
91
+ * Accepts a tuple (an array with exactly _n_ items) of values accepted by the
92
+ * _n_ given decoders.
93
+ */
94
+ function _tuple() {
95
+ for (var _len = arguments.length, decoders = new Array(_len), _key = 0; _key < _len; _key++) {
96
+ decoders[_key] = arguments[_key];
97
+ }
98
+
99
+ return ntuple(decoders.length).then(function (blobs, ok, err) {
100
+ var allOk = true;
101
+ var rvs = decoders.map(function (decoder, i) {
102
+ var blob = blobs[i];
103
+ var result = decoder.decode(blob);
104
+
105
+ if (result.ok) {
106
+ return result.value;
107
+ } else {
108
+ allOk = false;
109
+ return result.error;
110
+ }
111
+ });
112
+
113
+ if (allOk) {
114
+ return ok(rvs);
115
+ } else {
116
+ // If a decoder error has happened while unwrapping all the
117
+ // results, try to construct a good error message
118
+ return err(annotate(rvs));
119
+ }
120
+ });
121
+ }
122
+
123
+ export var tuple = _tuple;
@@ -0,0 +1,14 @@
1
+ import { Decoder, Scalar } from '../Decoder';
2
+
3
+ export const null_: Decoder<null>;
4
+ export const undefined_: Decoder<undefined>;
5
+ export function optional<T>(decoder: Decoder<T>): Decoder<T | undefined>;
6
+ export function nullable<T>(decoder: Decoder<T>): Decoder<T | null>;
7
+ export function maybe<T>(decoder: Decoder<T>): Decoder<T | null | undefined>;
8
+ export function constant<T extends Scalar>(value: T): Decoder<T>;
9
+ export function always<T extends Scalar>(value: T): Decoder<T>;
10
+ export function always<T>(value: T): Decoder<T>;
11
+ export function hardcoded<T extends Scalar>(value: T): Decoder<T>;
12
+ export function hardcoded<T>(value: T): Decoder<T>;
13
+ export const mixed: Decoder<unknown>;
14
+ export const unknown: Decoder<unknown>;
package/lib/basics.js ADDED
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.always = always;
5
+ exports.constant = constant;
6
+ exports.hardcoded = void 0;
7
+ exports.maybe = maybe;
8
+ exports.null_ = exports.mixed = void 0;
9
+ exports.nullable = nullable;
10
+ exports.optional = optional;
11
+ exports.unknown = exports.undefined_ = void 0;
12
+
13
+ var _Decoder = require("../Decoder");
14
+
15
+ var _unions = require("./unions");
16
+
17
+ /**
18
+ * Accepts and returns only the literal `null` value.
19
+ */
20
+ var null_ = (0, _Decoder.define)(function (blob, ok, err) {
21
+ return blob === null ? ok(blob) : err('Must be null');
22
+ });
23
+ /**
24
+ * Accepts and returns only the literal `undefined` value.
25
+ */
26
+
27
+ exports.null_ = null_;
28
+ var undefined_ = (0, _Decoder.define)(function (blob, ok, err) {
29
+ return blob === undefined ? ok(blob) : err('Must be undefined');
30
+ });
31
+ /**
32
+ * Accepts whatever the given decoder accepts, or `undefined`.
33
+ */
34
+
35
+ exports.undefined_ = undefined_;
36
+
37
+ function optional(decoder) {
38
+ return (0, _unions.either)(undefined_, decoder);
39
+ }
40
+ /**
41
+ * Accepts whatever the given decoder accepts, or `null`.
42
+ */
43
+
44
+
45
+ function nullable(decoder) {
46
+ return (0, _unions.either)(null_, decoder);
47
+ }
48
+
49
+ var undefined_or_null = (0, _Decoder.define)(function (blob, ok, err) {
50
+ return blob === undefined || blob === null ? ok(blob) : // Combine error message into a single line for readability
51
+ err('Must be undefined or null');
52
+ });
53
+ /**
54
+ * Accepts whatever the given decoder accepts, or `null`, or `undefined`.
55
+ */
56
+
57
+ function maybe(decoder) {
58
+ return (0, _unions.either)(undefined_or_null, decoder);
59
+ }
60
+ /**
61
+ * Accepts only the given constant value.
62
+ */
63
+
64
+
65
+ function constant(value) {
66
+ return (0, _Decoder.define)(function (blob, ok, err) {
67
+ return blob === value ? ok(value) : err("Must be constant " + String(value));
68
+ });
69
+ }
70
+ /**
71
+ * Accepts anything, completely ignores it, and always returns the provided
72
+ * value instead.
73
+ *
74
+ * This is useful to manually add extra fields to object decoders.
75
+ */
76
+
77
+
78
+ function always(value) {
79
+ return (0, _Decoder.define)(function (blob
80
+ /* ignored */
81
+ , ok, _) {
82
+ return ok(value);
83
+ });
84
+ }
85
+ /**
86
+ * Alias of always.
87
+ */
88
+
89
+
90
+ var hardcoded = always;
91
+ /**
92
+ * Accepts anything and returns it unchanged.
93
+ *
94
+ * Useful for situation in which you don't know or expect a specific type. Of
95
+ * course, the downside is that you won't know the type of the value statically
96
+ * and you'll have to further refine it yourself.
97
+ */
98
+
99
+ exports.hardcoded = hardcoded;
100
+ var unknown = (0, _Decoder.define)(function (blob, ok, _) {
101
+ return ok(blob);
102
+ });
103
+ /**
104
+ * Alias of unknown.
105
+ */
106
+
107
+ exports.unknown = unknown;
108
+ var mixed = unknown;
109
+ exports.mixed = mixed;