@sanity/validation 2.29.5 → 2.30.1-dev-preview.1013

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 (191) hide show
  1. package/{dist/dts → lib/dts/src}/Rule.d.ts +3 -3
  2. package/lib/dts/src/Rule.d.ts.map +1 -0
  3. package/lib/dts/src/Rule.js +336 -0
  4. package/lib/dts/src/Rule.js.map +1 -0
  5. package/{dist/dts → lib/dts/src}/ValidationError.d.ts +3 -3
  6. package/lib/dts/src/ValidationError.d.ts.map +1 -0
  7. package/lib/dts/src/ValidationError.js +18 -0
  8. package/lib/dts/src/ValidationError.js.map +1 -0
  9. package/{dist/dts → lib/dts/src}/index.d.ts +12 -12
  10. package/lib/dts/src/index.d.ts.map +1 -0
  11. package/lib/dts/src/index.js +7 -0
  12. package/lib/dts/src/index.js.map +1 -0
  13. package/{dist/dts → lib/dts/src}/inferFromSchema.d.ts +3 -3
  14. package/lib/dts/src/inferFromSchema.d.ts.map +1 -0
  15. package/lib/dts/src/inferFromSchema.js +14 -0
  16. package/lib/dts/src/inferFromSchema.js.map +1 -0
  17. package/{dist/dts → lib/dts/src}/inferFromSchemaType.d.ts +4 -4
  18. package/lib/dts/src/inferFromSchemaType.d.ts.map +1 -0
  19. package/lib/dts/src/inferFromSchemaType.js +33 -0
  20. package/lib/dts/src/inferFromSchemaType.js.map +1 -0
  21. package/{dist/dts → lib/dts/src}/util/convertToValidationMarker.d.ts +5 -5
  22. package/lib/dts/src/util/convertToValidationMarker.d.ts.map +1 -0
  23. package/lib/dts/src/util/convertToValidationMarker.js +51 -0
  24. package/lib/dts/src/util/convertToValidationMarker.js.map +1 -0
  25. package/{dist/dts → lib/dts/src}/util/deepEquals.d.ts +5 -5
  26. package/lib/dts/src/util/deepEquals.d.ts.map +1 -0
  27. package/lib/dts/src/util/deepEquals.js +65 -0
  28. package/lib/dts/src/util/deepEquals.js.map +1 -0
  29. package/{dist/dts → lib/dts/src}/util/escapeRegex.d.ts +2 -2
  30. package/lib/dts/src/util/escapeRegex.d.ts.map +1 -0
  31. package/lib/dts/src/util/escapeRegex.js +6 -0
  32. package/lib/dts/src/util/escapeRegex.js.map +1 -0
  33. package/{dist/dts → lib/dts/src}/util/normalizeValidationRules.d.ts +5 -5
  34. package/lib/dts/src/util/normalizeValidationRules.d.ts.map +1 -0
  35. package/lib/dts/src/util/normalizeValidationRules.js +104 -0
  36. package/lib/dts/src/util/normalizeValidationRules.js.map +1 -0
  37. package/{dist/dts → lib/dts/src}/util/normalizeValidationRules.test.d.ts +0 -0
  38. package/lib/dts/src/util/normalizeValidationRules.test.d.ts.map +1 -0
  39. package/lib/dts/src/util/normalizeValidationRules.test.js +150 -0
  40. package/lib/dts/src/util/normalizeValidationRules.test.js.map +1 -0
  41. package/{dist/dts → lib/dts/src}/util/pathToString.d.ts +2 -2
  42. package/lib/dts/src/util/pathToString.d.ts.map +1 -0
  43. package/lib/dts/src/util/pathToString.js +18 -0
  44. package/lib/dts/src/util/pathToString.js.map +1 -0
  45. package/{dist/dts → lib/dts/src}/util/typeString.d.ts +1 -1
  46. package/lib/dts/src/util/typeString.d.ts.map +1 -0
  47. package/lib/dts/src/util/typeString.js +23 -0
  48. package/lib/dts/src/util/typeString.js.map +1 -0
  49. package/{dist/dts → lib/dts/src}/util/typeString.test.d.ts +0 -0
  50. package/lib/dts/src/util/typeString.test.d.ts.map +1 -0
  51. package/lib/dts/src/util/typeString.test.js +24 -0
  52. package/lib/dts/src/util/typeString.test.js.map +1 -0
  53. package/{dist/dts → lib/dts/src}/validateDocument.d.ts +22 -21
  54. package/lib/dts/src/validateDocument.d.ts.map +1 -0
  55. package/lib/dts/src/validateDocument.js +142 -0
  56. package/lib/dts/src/validateDocument.js.map +1 -0
  57. package/{dist/dts → lib/dts/src}/validateDocument.test.d.ts +0 -0
  58. package/lib/dts/src/validateDocument.test.d.ts.map +1 -0
  59. package/lib/dts/src/validateDocument.test.js +703 -0
  60. package/lib/dts/src/validateDocument.test.js.map +1 -0
  61. package/{dist/dts → lib/dts/src}/validators/arrayValidator.d.ts +3 -3
  62. package/lib/dts/src/validators/arrayValidator.d.ts.map +1 -0
  63. package/lib/dts/src/validators/arrayValidator.js +79 -0
  64. package/lib/dts/src/validators/arrayValidator.js.map +1 -0
  65. package/{dist/dts → lib/dts/src}/validators/booleanValidator.d.ts +3 -3
  66. package/lib/dts/src/validators/booleanValidator.d.ts.map +1 -0
  67. package/lib/dts/src/validators/booleanValidator.js +12 -0
  68. package/lib/dts/src/validators/booleanValidator.js.map +1 -0
  69. package/{dist/dts → lib/dts/src}/validators/dateValidator.d.ts +4 -4
  70. package/lib/dts/src/validators/dateValidator.d.ts.map +1 -0
  71. package/lib/dts/src/validators/dateValidator.js +83 -0
  72. package/lib/dts/src/validators/dateValidator.js.map +1 -0
  73. package/{dist/dts → lib/dts/src}/validators/genericValidator.d.ts +3 -3
  74. package/lib/dts/src/validators/genericValidator.d.ts.map +1 -0
  75. package/lib/dts/src/validators/genericValidator.js +93 -0
  76. package/lib/dts/src/validators/genericValidator.js.map +1 -0
  77. package/{dist/dts → lib/dts/src}/validators/numberValidator.d.ts +3 -3
  78. package/lib/dts/src/validators/numberValidator.d.ts.map +1 -0
  79. package/lib/dts/src/validators/numberValidator.js +47 -0
  80. package/lib/dts/src/validators/numberValidator.js.map +1 -0
  81. package/{dist/dts → lib/dts/src}/validators/objectValidator.d.ts +3 -3
  82. package/lib/dts/src/validators/objectValidator.d.ts.map +1 -0
  83. package/lib/dts/src/validators/objectValidator.js +48 -0
  84. package/lib/dts/src/validators/objectValidator.js.map +1 -0
  85. package/{dist/dts → lib/dts/src}/validators/slugValidator.d.ts +8 -8
  86. package/lib/dts/src/validators/slugValidator.d.ts.map +1 -0
  87. package/lib/dts/src/validators/slugValidator.js +83 -0
  88. package/lib/dts/src/validators/slugValidator.js.map +1 -0
  89. package/{dist/dts → lib/dts/src}/validators/stringValidator.d.ts +3 -3
  90. package/lib/dts/src/validators/stringValidator.d.ts.map +1 -0
  91. package/lib/dts/src/validators/stringValidator.js +94 -0
  92. package/lib/dts/src/validators/stringValidator.js.map +1 -0
  93. package/lib/dts/test/array.test.d.ts +2 -0
  94. package/lib/dts/test/array.test.d.ts.map +1 -0
  95. package/lib/dts/test/array.test.js +55 -0
  96. package/lib/dts/test/array.test.js.map +1 -0
  97. package/lib/dts/test/children.test.d.ts +2 -0
  98. package/lib/dts/test/children.test.d.ts.map +1 -0
  99. package/lib/dts/test/children.test.js +70 -0
  100. package/lib/dts/test/children.test.js.map +1 -0
  101. package/lib/dts/test/createSchema.d.ts +6 -0
  102. package/lib/dts/test/createSchema.d.ts.map +1 -0
  103. package/lib/dts/test/createSchema.js +19 -0
  104. package/lib/dts/test/createSchema.js.map +1 -0
  105. package/lib/dts/test/generics.test.d.ts +2 -0
  106. package/lib/dts/test/generics.test.d.ts.map +1 -0
  107. package/lib/dts/test/generics.test.js +60 -0
  108. package/lib/dts/test/generics.test.js.map +1 -0
  109. package/lib/dts/test/infer.test.d.ts +2 -0
  110. package/lib/dts/test/infer.test.d.ts.map +1 -0
  111. package/lib/dts/test/infer.test.js +243 -0
  112. package/lib/dts/test/infer.test.js.map +1 -0
  113. package/lib/dts/test/mocks/mockSanityClient.d.ts +6 -0
  114. package/lib/dts/test/mocks/mockSanityClient.d.ts.map +1 -0
  115. package/lib/dts/test/mocks/mockSanityClient.js +8 -0
  116. package/lib/dts/test/mocks/mockSanityClient.js.map +1 -0
  117. package/lib/dts/test/nullExport.d.ts +3 -0
  118. package/lib/dts/test/nullExport.d.ts.map +1 -0
  119. package/lib/dts/test/nullExport.js +4 -0
  120. package/lib/dts/test/nullExport.js.map +1 -0
  121. package/lib/dts/test/numbers.test.d.ts +2 -0
  122. package/lib/dts/test/numbers.test.d.ts.map +1 -0
  123. package/lib/dts/test/numbers.test.js +57 -0
  124. package/lib/dts/test/numbers.test.js.map +1 -0
  125. package/lib/dts/test/strings.test.d.ts +2 -0
  126. package/lib/dts/test/strings.test.d.ts.map +1 -0
  127. package/lib/dts/test/strings.test.js +100 -0
  128. package/lib/dts/test/strings.test.js.map +1 -0
  129. package/lib/dts/tsconfig.lib.tsbuildinfo +1 -0
  130. package/lib/dts/tsconfig.tsbuildinfo +1 -0
  131. package/lib/index.cjs +1318 -0
  132. package/lib/index.cjs.map +1 -0
  133. package/lib/index.js +1308 -48
  134. package/lib/index.js.map +1 -0
  135. package/package.json +21 -11
  136. package/src/Rule.ts +6 -2
  137. package/src/inferFromSchema.ts +7 -1
  138. package/src/util/convertToValidationMarker.ts +5 -3
  139. package/src/validateDocument.test.ts +22 -23
  140. package/src/validateDocument.ts +3 -1
  141. package/src/validators/dateValidator.ts +11 -7
  142. package/src/validators/slugValidator.ts +3 -3
  143. package/src/validators/stringValidator.ts +2 -1
  144. package/dist/dts/Rule.d.ts.map +0 -1
  145. package/dist/dts/ValidationError.d.ts.map +0 -1
  146. package/dist/dts/getClient.d.ts +0 -3
  147. package/dist/dts/getClient.d.ts.map +0 -1
  148. package/dist/dts/index.d.ts.map +0 -1
  149. package/dist/dts/inferFromSchema.d.ts.map +0 -1
  150. package/dist/dts/inferFromSchemaType.d.ts.map +0 -1
  151. package/dist/dts/util/convertToValidationMarker.d.ts.map +0 -1
  152. package/dist/dts/util/deepEquals.d.ts.map +0 -1
  153. package/dist/dts/util/escapeRegex.d.ts.map +0 -1
  154. package/dist/dts/util/normalizeValidationRules.d.ts.map +0 -1
  155. package/dist/dts/util/normalizeValidationRules.test.d.ts.map +0 -1
  156. package/dist/dts/util/pathToString.d.ts.map +0 -1
  157. package/dist/dts/util/typeString.d.ts.map +0 -1
  158. package/dist/dts/util/typeString.test.d.ts.map +0 -1
  159. package/dist/dts/validateDocument.d.ts.map +0 -1
  160. package/dist/dts/validateDocument.test.d.ts.map +0 -1
  161. package/dist/dts/validators/arrayValidator.d.ts.map +0 -1
  162. package/dist/dts/validators/booleanValidator.d.ts.map +0 -1
  163. package/dist/dts/validators/dateValidator.d.ts.map +0 -1
  164. package/dist/dts/validators/genericValidator.d.ts.map +0 -1
  165. package/dist/dts/validators/numberValidator.d.ts.map +0 -1
  166. package/dist/dts/validators/objectValidator.d.ts.map +0 -1
  167. package/dist/dts/validators/slugValidator.d.ts.map +0 -1
  168. package/dist/dts/validators/stringValidator.d.ts.map +0 -1
  169. package/jest.config.js +0 -5
  170. package/lib/Rule.js +0 -491
  171. package/lib/ValidationError.js +0 -39
  172. package/lib/getClient.js +0 -20
  173. package/lib/inferFromSchema.js +0 -22
  174. package/lib/inferFromSchemaType.js +0 -86
  175. package/lib/util/convertToValidationMarker.js +0 -65
  176. package/lib/util/deepEquals.js +0 -87
  177. package/lib/util/escapeRegex.js +0 -14
  178. package/lib/util/normalizeValidationRules.js +0 -115
  179. package/lib/util/pathToString.js +0 -30
  180. package/lib/util/typeString.js +0 -29
  181. package/lib/validateDocument.js +0 -231
  182. package/lib/validators/arrayValidator.js +0 -123
  183. package/lib/validators/booleanValidator.js +0 -29
  184. package/lib/validators/dateValidator.js +0 -120
  185. package/lib/validators/genericValidator.js +0 -135
  186. package/lib/validators/numberValidator.js +0 -70
  187. package/lib/validators/objectValidator.js +0 -93
  188. package/lib/validators/slugValidator.js +0 -133
  189. package/lib/validators/stringValidator.js +0 -131
  190. package/src/getClient.ts +0 -13
  191. package/tsconfig.json +0 -10
@@ -1,65 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = convertToValidationMarker;
7
- exports.isNonNullable = isNonNullable;
8
-
9
- var _ValidationError = _interopRequireDefault(require("../ValidationError"));
10
-
11
- var _pathToString = _interopRequireDefault(require("../util/pathToString"));
12
-
13
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
-
15
- function isNonNullable(t) {
16
- return t !== null || t !== undefined;
17
- }
18
-
19
- function convertToValidationMarker(validatorResult, level, context) {
20
- var _validatorResult$path;
21
-
22
- if (validatorResult === true) return [];
23
-
24
- if (Array.isArray(validatorResult)) {
25
- return validatorResult.flatMap(child => convertToValidationMarker(child, level, context)).filter(isNonNullable);
26
- }
27
-
28
- if (typeof validatorResult === 'string') {
29
- return convertToValidationMarker(new _ValidationError.default(validatorResult), level, context);
30
- }
31
-
32
- if (!(validatorResult instanceof _ValidationError.default)) {
33
- // in order to accept the `ValidationErrorLike`, it at least needs to have
34
- // a `message` in the object
35
- if (typeof (validatorResult === null || validatorResult === void 0 ? void 0 : validatorResult.message) !== 'string') {
36
- throw new Error("".concat((0, _pathToString.default)(context.path), ": Validator must return 'true' if valid or an error message as a string on errors"));
37
- } // this is the occurs when an object is returned that wasn't created with the
38
- // `ValidationErrorClass`. in this case, we want to convert it to a class
39
-
40
-
41
- return convertToValidationMarker(new _ValidationError.default(validatorResult.message, validatorResult), level, context);
42
- }
43
-
44
- var results = []; // the validator result does not include any item-level relative paths,
45
- // then just return the top-level path with the validation result
46
-
47
- if (!((_validatorResult$path = validatorResult.paths) !== null && _validatorResult$path !== void 0 && _validatorResult$path.length)) {
48
- return [{
49
- type: 'validation',
50
- level: level || 'error',
51
- item: validatorResult,
52
- path: context.path || []
53
- }];
54
- } // if the validator result did include item-level relative paths, then for
55
- // each item-level relative path, create a validation marker that concatenates
56
- // the relative path with the path from the validation context
57
-
58
-
59
- return results.concat(validatorResult.paths.map(path => ({
60
- type: 'validation',
61
- path: (context.path || []).concat(path),
62
- level: level || 'error',
63
- item: validatorResult
64
- })));
65
- }
@@ -1,87 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = deepEquals;
7
-
8
- /**
9
- * Modified version of fast-deep-equal (https://github.com/epoberezkin/fast-deep-equal)
10
- * MIT-licensed, copyright (c) 2017 Evgeny Poberezkin
11
- **/
12
- // NOTE: when converting to typescript, some of the checks were inlined (vs
13
- // having them in a variable) because the type predicate type narrowing only
14
- // works when type predicate is called inline in the condition that starts the
15
- // control flow branch.
16
- // see here: https://www.typescriptlang.org/docs/handbook/2/narrowing.html
17
- function deepEquals(a, b) {
18
- if (a === b) {
19
- return true;
20
- }
21
-
22
- if (Array.isArray(a) && Array.isArray(b)) {
23
- if (a.length != b.length) return false;
24
-
25
- for (var i = 0; i < a.length; i++) {
26
- if (!deepEquals(a[i], b[i])) {
27
- return false;
28
- }
29
- }
30
-
31
- return true;
32
- }
33
-
34
- if (Array.isArray(a) != Array.isArray(b)) {
35
- return false;
36
- }
37
-
38
- if (a && b && typeof a === 'object' && typeof b === 'object') {
39
- var keys = Object.keys(a);
40
-
41
- if (keys.length !== Object.keys(b).length) {
42
- return false;
43
- }
44
-
45
- if (a instanceof Date && b instanceof Date) {
46
- return a.getTime() === b.getTime();
47
- }
48
-
49
- if (a instanceof Date != b instanceof Date) {
50
- return false;
51
- }
52
-
53
- if (a instanceof RegExp && b instanceof RegExp) {
54
- return a.toString() == b.toString();
55
- }
56
-
57
- if (a instanceof RegExp != b instanceof RegExp) {
58
- return false;
59
- }
60
-
61
- for (var _i = 0; _i < keys.length; _i++) {
62
- if (keys[_i] === '_key') {
63
- continue;
64
- }
65
-
66
- if (!Object.prototype.hasOwnProperty.call(b, keys[_i])) {
67
- return false;
68
- }
69
- }
70
-
71
- for (var _i2 = 0; _i2 < keys.length; _i2++) {
72
- var key = keys[_i2];
73
-
74
- if (key === '_key') {
75
- continue;
76
- }
77
-
78
- if (!deepEquals(a[key], b[key])) {
79
- return false;
80
- }
81
- }
82
-
83
- return true;
84
- }
85
-
86
- return false;
87
- }
@@ -1,14 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
-
8
- /* eslint-disable no-useless-escape */
9
- var _default = string => {
10
- // Escape ^$.*+-?=!:|\/()[]{},
11
- return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
12
- };
13
-
14
- exports.default = _default;
@@ -1,115 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = normalizeValidationRules;
7
-
8
- var _Rule = _interopRequireDefault(require("../Rule"));
9
-
10
- var _slugValidator = require("../validators/slugValidator");
11
-
12
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
-
14
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
15
-
16
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
17
-
18
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
19
-
20
- var ruleConstraintTypes = {
21
- array: true,
22
- boolean: true,
23
- date: true,
24
- number: true,
25
- object: true,
26
- string: true
27
- };
28
-
29
- var isRuleConstraint = typeString => typeString in ruleConstraintTypes;
30
-
31
- function getTypeChain(type, visited) {
32
- if (!type) return [];
33
- if (visited.has(type)) return [];
34
- visited.add(type);
35
- var next = type.type ? getTypeChain(type.type, visited) : [];
36
- return [...next, type];
37
- }
38
-
39
- function baseRuleReducer(inputRule, type) {
40
- var baseRule = inputRule;
41
-
42
- if (isRuleConstraint(type.jsonType)) {
43
- baseRule = baseRule.type(type.jsonType);
44
- }
45
-
46
- var typeOptionsList = // if type.options is truthy
47
- (type === null || type === void 0 ? void 0 : type.options) && // and type.options is an object (non-null from the previous)
48
- typeof type.options === 'object' && // and if `list` is in options
49
- 'list' in type.options && // then finally access the list
50
- type.options.list;
51
-
52
- if (Array.isArray(typeOptionsList)) {
53
- baseRule = baseRule.valid(typeOptionsList.map(option => extractValueFromListOption(option, type)));
54
- }
55
-
56
- if (type.name === 'datetime') return baseRule.type('Date');
57
- if (type.name === 'date') return baseRule.type('Date');
58
- if (type.name === 'url') return baseRule.uri();
59
- if (type.name === 'slug') return baseRule.custom(_slugValidator.slugValidator);
60
- if (type.name === 'reference') return baseRule.reference();
61
- if (type.name === 'email') return baseRule.email();
62
- return baseRule;
63
- }
64
-
65
- function hasValueField(typeDef) {
66
- if (!typeDef) return false;
67
- if (!('fields' in typeDef) && typeDef.type) return hasValueField(typeDef.type);
68
- if (!('fields' in typeDef)) return false;
69
- if (!Array.isArray(typeDef.fields)) return false;
70
- return typeDef.fields.some(field => field.name === 'value');
71
- }
72
-
73
- function extractValueFromListOption(option, typeDef) {
74
- // If you define a `list` option with object items, where the item has a `value` field,
75
- // we don't want to treat that as the value but rather the surrounding object
76
- // This differs from the case where you have a title/value pair setup for a string/number, for instance
77
- if (typeDef.jsonType === 'object' && hasValueField(typeDef)) return option;
78
- return option.value === undefined ? option : option.value;
79
- }
80
- /**
81
- * Takes in `SchemaValidationValue` and returns an array of `Rule` instances.
82
- */
83
-
84
-
85
- function normalizeValidationRules(typeDef) {
86
- if (!typeDef) {
87
- return [];
88
- }
89
-
90
- var validation = typeDef.validation;
91
-
92
- if (Array.isArray(validation)) {
93
- return validation.flatMap(i => normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
94
- validation: i
95
- })));
96
- }
97
-
98
- if (validation instanceof _Rule.default) {
99
- return [validation];
100
- }
101
-
102
- var baseRule = // using an object + Object.values to de-dupe the type chain by type name
103
- Object.values(getTypeChain(typeDef, new Set()).reduce((acc, type) => {
104
- acc[type.name] = type;
105
- return acc;
106
- }, {})).reduce(baseRuleReducer, new _Rule.default(typeDef));
107
-
108
- if (!validation) {
109
- return [baseRule];
110
- }
111
-
112
- return normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
113
- validation: validation(baseRule)
114
- }));
115
- }
@@ -1,30 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = pathToString;
7
-
8
- var _types = require("@sanity/types");
9
-
10
- function pathToString() {
11
- var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
12
- return path.reduce((target, segment, i) => {
13
- var segmentType = typeof segment;
14
-
15
- if (segmentType === 'number') {
16
- return "".concat(target, "[").concat(segment, "]");
17
- }
18
-
19
- if (segmentType === 'string') {
20
- var separator = i === 0 ? '' : '.';
21
- return "".concat(target).concat(separator).concat(segment);
22
- }
23
-
24
- if ((0, _types.isKeyedObject)(segment)) {
25
- return "".concat(target, "[_key==\"").concat(segment._key, "\"]");
26
- }
27
-
28
- throw new Error("Unsupported path segment \"".concat(segment, "\""));
29
- }, '');
30
- }
@@ -1,29 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = typeString;
7
- // this file was adapted from a previous dependency `type-of-is`
8
- // https://github.com/stephenhandley/type-of-is/blob/7138a7e79f5af7c286bf8123f60843a91aaebf38/index.js
9
- var _toString = {}.toString;
10
- var builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error];
11
-
12
- function isBuiltIn(_constructor) {
13
- for (var i = 0; i < builtIns.length; i++) {
14
- if (builtIns[i] === _constructor) return true;
15
- }
16
-
17
- return false;
18
- }
19
-
20
- function typeString(obj) {
21
- // [object Blah] -> Blah
22
- var stringType = _toString.call(obj).slice(8, -1);
23
-
24
- if (obj === null || obj === undefined) return stringType.toLowerCase(); // eslint-disable-next-line @typescript-eslint/ban-types
25
-
26
- var constructorType = obj.constructor;
27
- if (constructorType && !isBuiltIn(constructorType)) return constructorType.name;
28
- return stringType;
29
- }
@@ -1,231 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = validateDocument;
7
- exports.resolveTypeForArrayItem = resolveTypeForArrayItem;
8
- exports.validateItem = validateItem;
9
-
10
- var _uniqBy2 = _interopRequireDefault(require("lodash/uniqBy"));
11
-
12
- var _types = require("@sanity/types");
13
-
14
- var _typeString = _interopRequireDefault(require("./util/typeString"));
15
-
16
- var _ValidationError = _interopRequireDefault(require("./ValidationError"));
17
-
18
- var _normalizeValidationRules = _interopRequireDefault(require("./util/normalizeValidationRules"));
19
-
20
- var _excluded = ["value", "type", "path", "parent"];
21
-
22
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23
-
24
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
25
-
26
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
27
-
28
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
29
-
30
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
31
-
32
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
33
-
34
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
35
-
36
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
37
-
38
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
39
-
40
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
41
-
42
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
43
-
44
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
45
-
46
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
47
-
48
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
49
-
50
- var isRecord = maybeRecord => typeof maybeRecord === 'object' && maybeRecord !== null && !Array.isArray(maybeRecord);
51
-
52
- var isNonNullable = value => value !== null && value !== undefined;
53
- /**
54
- * @internal
55
- */
56
-
57
-
58
- function resolveTypeForArrayItem(item, candidates) {
59
- // if there is only one type available, assume that it's the correct one
60
- if (candidates.length === 1) return candidates[0];
61
-
62
- var itemType = (0, _types.isTypedObject)(item) && item._type;
63
-
64
- var primitive = item === undefined || item === null || !itemType && (0, _typeString.default)(item).toLowerCase();
65
-
66
- if (primitive && primitive !== 'object') {
67
- return candidates.find(candidate => candidate.jsonType === primitive);
68
- }
69
-
70
- return candidates.find(candidate => {
71
- var _candidate$type;
72
-
73
- return ((_candidate$type = candidate.type) === null || _candidate$type === void 0 ? void 0 : _candidate$type.name) === itemType;
74
- }) || candidates.find(candidate => candidate.name === itemType) || candidates.find(candidate => candidate.name === 'object' && primitive === 'object');
75
- }
76
-
77
- function validateDocument(_x, _x2, _x3) {
78
- return _validateDocument.apply(this, arguments);
79
- }
80
- /**
81
- * this is used make optional properties required by replacing optionals with
82
- * `T[P] | undefined`. this is used to prevent errors in `validateItem` where
83
- * an option from a previous invocation would be incorrectly passed down.
84
- *
85
- * https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585
86
- */
87
-
88
-
89
- function _validateDocument() {
90
- _validateDocument = _asyncToGenerator(function* (doc, schema, context) {
91
- var documentType = schema.get(doc._type);
92
-
93
- if (!documentType) {
94
- console.warn('Schema type for object type "%s" not found, skipping validation', doc._type);
95
- return [];
96
- }
97
-
98
- try {
99
- return yield validateItem({
100
- parent: undefined,
101
- value: doc,
102
- path: [],
103
- document: doc,
104
- type: documentType,
105
- getDocumentExists: context === null || context === void 0 ? void 0 : context.getDocumentExists
106
- });
107
- } catch (err) {
108
- console.error(err);
109
- return [{
110
- type: 'validation',
111
- level: 'error',
112
- path: [],
113
- item: new _ValidationError.default(err === null || err === void 0 ? void 0 : err.message)
114
- }];
115
- }
116
- });
117
- return _validateDocument.apply(this, arguments);
118
- }
119
-
120
- function validateItem(_x4) {
121
- return _validateItem.apply(this, arguments);
122
- }
123
-
124
- function _validateItem() {
125
- _validateItem = _asyncToGenerator(function* (_ref) {
126
- var value = _ref.value,
127
- type = _ref.type,
128
- _ref$path = _ref.path,
129
- path = _ref$path === void 0 ? [] : _ref$path,
130
- parent = _ref.parent,
131
- restOfContext = _objectWithoutProperties(_ref, _excluded);
132
-
133
- var rules = (0, _normalizeValidationRules.default)(type); // run validation for the current value
134
-
135
- var selfChecks = rules.map(rule => rule.validate(value, _objectSpread(_objectSpread({}, restOfContext), {}, {
136
- parent,
137
- path,
138
- type
139
- }))); // run validation for nested values (conditionally)
140
-
141
- var nestedChecks = [];
142
- var selfIsRequired = rules.some(rule => rule.isRequired());
143
- var shouldRunNestedObjectValidation = // run nested validation for objects
144
- (type === null || type === void 0 ? void 0 : type.jsonType) === 'object' && ( // if the value is truthy
145
- !!value || // or
146
- // (the value is null or undefined) and the top-level value is required
147
- (value === null || value === undefined) && selfIsRequired);
148
-
149
- if (shouldRunNestedObjectValidation) {
150
- var fieldTypes = type.fields.reduce((acc, field) => {
151
- acc[field.name] = field.type;
152
- return acc;
153
- }, {}); // Validation for rules set at the object level with `Rule.fields({/* ... */})`
154
-
155
- nestedChecks = nestedChecks.concat(rules.map(rule => rule._fieldRules).filter(isNonNullable).flatMap(fieldResults => Object.entries(fieldResults)).flatMap(_ref2 => {
156
- var _ref3 = _slicedToArray(_ref2, 2),
157
- name = _ref3[0],
158
- validation = _ref3[1];
159
-
160
- var fieldType = fieldTypes[name];
161
- return (0, _normalizeValidationRules.default)(_objectSpread(_objectSpread({}, fieldType), {}, {
162
- validation
163
- })).map(subRule => {
164
- var nestedValue = isRecord(value) ? value[name] : undefined;
165
- return subRule.validate(nestedValue, _objectSpread(_objectSpread({}, restOfContext), {}, {
166
- parent: value,
167
- path: path.concat(name),
168
- type: fieldType
169
- }));
170
- });
171
- })); // Validation from each field's schema `validation: Rule => {/* ... */}` function
172
-
173
- nestedChecks = nestedChecks.concat(type.fields.map(field => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
174
- parent: value,
175
- value: isRecord(value) ? value[field.name] : undefined,
176
- path: path.concat(field.name),
177
- type: field.type
178
- }))));
179
- } // note: unlike objects, arrays should not run nested validation for undefined
180
- // values because we won't have a valid path to put a marker (i.e. missing the
181
- // key or index in the path) and the downstream form builder won't have a
182
- // valid target component
183
-
184
-
185
- var shouldRunNestedValidationForArrays = (type === null || type === void 0 ? void 0 : type.jsonType) === 'array' && Array.isArray(value);
186
-
187
- if (shouldRunNestedValidationForArrays) {
188
- nestedChecks = nestedChecks.concat(value.map(item => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
189
- parent: value,
190
- value: item,
191
- path: path.concat((0, _types.isKeyedObject)(item) ? {
192
- _key: item._key
193
- } : value.indexOf(item)),
194
- type: resolveTypeForArrayItem(item, type.of)
195
- }))));
196
- } // markDefs also do no run nested validation if the parent object is undefined
197
- // for a similar reason to arrays
198
-
199
-
200
- var shouldRunNestedValidationForMarkDefs = (0, _types.isBlock)(value) && value.markDefs.length && (0, _types.isBlockSchemaType)(type);
201
-
202
- if (shouldRunNestedValidationForMarkDefs) {
203
- var _type$fields = _slicedToArray(type.fields, 1),
204
- spanChildrenField = _type$fields[0];
205
-
206
- var spanType = spanChildrenField.type.of.find(_types.isSpanSchemaType);
207
- var annotations = ((spanType === null || spanType === void 0 ? void 0 : spanType.annotations) || []).reduce((map, annotationType) => {
208
- map.set(annotationType.name, annotationType);
209
- return map;
210
- }, new Map());
211
- nestedChecks = nestedChecks.concat(value.markDefs.map(markDef => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
212
- parent: value,
213
- value: markDef,
214
- path: path.concat(['markDefs', {
215
- _key: markDef._key
216
- }]),
217
- type: annotations.get(markDef._type)
218
- }))));
219
- }
220
-
221
- var results = (yield Promise.all([...selfChecks, ...nestedChecks])).flat(); // run `uniqBy` if `_fieldRules` are present because they can
222
- // cause repeat markers
223
-
224
- if (rules.some(rule => rule._fieldRules)) {
225
- return (0, _uniqBy2.default)(results, rule => JSON.stringify(rule));
226
- }
227
-
228
- return results;
229
- });
230
- return _validateItem.apply(this, arguments);
231
- }