@sanity/validation 3.0.0-dev-preview.20 → 3.0.0-dev-preview.22

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 (142) hide show
  1. package/lib/dts/src/index.d.ts +36 -13
  2. package/lib/index.esm.js +1259 -0
  3. package/lib/index.esm.js.map +1 -0
  4. package/lib/index.js +1253 -1310
  5. package/lib/index.js.map +1 -1
  6. package/package.json +23 -18
  7. package/src/index.ts +3 -1
  8. package/src/util/requestIdleCallback.ts +31 -0
  9. package/src/validateDocument.test.ts +0 -80
  10. package/src/validateDocument.ts +84 -45
  11. package/src/validators/slugValidator.ts +16 -2
  12. package/lib/dts/src/Rule.d.ts +0 -4
  13. package/lib/dts/src/Rule.d.ts.map +0 -1
  14. package/lib/dts/src/Rule.js +0 -336
  15. package/lib/dts/src/Rule.js.map +0 -1
  16. package/lib/dts/src/ValidationError.d.ts +0 -4
  17. package/lib/dts/src/ValidationError.d.ts.map +0 -1
  18. package/lib/dts/src/ValidationError.js +0 -18
  19. package/lib/dts/src/ValidationError.js.map +0 -1
  20. package/lib/dts/src/index.d.ts.map +0 -1
  21. package/lib/dts/src/index.js +0 -7
  22. package/lib/dts/src/index.js.map +0 -1
  23. package/lib/dts/src/inferFromSchema.d.ts +0 -4
  24. package/lib/dts/src/inferFromSchema.d.ts.map +0 -1
  25. package/lib/dts/src/inferFromSchema.js +0 -14
  26. package/lib/dts/src/inferFromSchema.js.map +0 -1
  27. package/lib/dts/src/inferFromSchemaType.d.ts +0 -5
  28. package/lib/dts/src/inferFromSchemaType.d.ts.map +0 -1
  29. package/lib/dts/src/inferFromSchemaType.js +0 -33
  30. package/lib/dts/src/inferFromSchemaType.js.map +0 -1
  31. package/lib/dts/src/util/convertToValidationMarker.d.ts +0 -6
  32. package/lib/dts/src/util/convertToValidationMarker.d.ts.map +0 -1
  33. package/lib/dts/src/util/convertToValidationMarker.js +0 -51
  34. package/lib/dts/src/util/convertToValidationMarker.js.map +0 -1
  35. package/lib/dts/src/util/deepEquals.d.ts +0 -6
  36. package/lib/dts/src/util/deepEquals.d.ts.map +0 -1
  37. package/lib/dts/src/util/deepEquals.js +0 -65
  38. package/lib/dts/src/util/deepEquals.js.map +0 -1
  39. package/lib/dts/src/util/escapeRegex.d.ts +0 -3
  40. package/lib/dts/src/util/escapeRegex.d.ts.map +0 -1
  41. package/lib/dts/src/util/escapeRegex.js +0 -6
  42. package/lib/dts/src/util/escapeRegex.js.map +0 -1
  43. package/lib/dts/src/util/normalizeValidationRules.d.ts +0 -6
  44. package/lib/dts/src/util/normalizeValidationRules.d.ts.map +0 -1
  45. package/lib/dts/src/util/normalizeValidationRules.js +0 -104
  46. package/lib/dts/src/util/normalizeValidationRules.js.map +0 -1
  47. package/lib/dts/src/util/normalizeValidationRules.test.d.ts +0 -2
  48. package/lib/dts/src/util/normalizeValidationRules.test.d.ts.map +0 -1
  49. package/lib/dts/src/util/normalizeValidationRules.test.js +0 -150
  50. package/lib/dts/src/util/normalizeValidationRules.test.js.map +0 -1
  51. package/lib/dts/src/util/pathToString.d.ts +0 -3
  52. package/lib/dts/src/util/pathToString.d.ts.map +0 -1
  53. package/lib/dts/src/util/pathToString.js +0 -18
  54. package/lib/dts/src/util/pathToString.js.map +0 -1
  55. package/lib/dts/src/util/typeString.d.ts +0 -2
  56. package/lib/dts/src/util/typeString.d.ts.map +0 -1
  57. package/lib/dts/src/util/typeString.js +0 -23
  58. package/lib/dts/src/util/typeString.js.map +0 -1
  59. package/lib/dts/src/util/typeString.test.d.ts +0 -2
  60. package/lib/dts/src/util/typeString.test.d.ts.map +0 -1
  61. package/lib/dts/src/util/typeString.test.js +0 -24
  62. package/lib/dts/src/util/typeString.test.js.map +0 -1
  63. package/lib/dts/src/validateDocument.d.ts +0 -25
  64. package/lib/dts/src/validateDocument.d.ts.map +0 -1
  65. package/lib/dts/src/validateDocument.js +0 -165
  66. package/lib/dts/src/validateDocument.js.map +0 -1
  67. package/lib/dts/src/validateDocument.test.d.ts +0 -2
  68. package/lib/dts/src/validateDocument.test.d.ts.map +0 -1
  69. package/lib/dts/src/validateDocument.test.js +0 -717
  70. package/lib/dts/src/validateDocument.test.js.map +0 -1
  71. package/lib/dts/src/validators/arrayValidator.d.ts +0 -4
  72. package/lib/dts/src/validators/arrayValidator.d.ts.map +0 -1
  73. package/lib/dts/src/validators/arrayValidator.js +0 -79
  74. package/lib/dts/src/validators/arrayValidator.js.map +0 -1
  75. package/lib/dts/src/validators/booleanValidator.d.ts +0 -4
  76. package/lib/dts/src/validators/booleanValidator.d.ts.map +0 -1
  77. package/lib/dts/src/validators/booleanValidator.js +0 -12
  78. package/lib/dts/src/validators/booleanValidator.js.map +0 -1
  79. package/lib/dts/src/validators/dateValidator.d.ts +0 -5
  80. package/lib/dts/src/validators/dateValidator.d.ts.map +0 -1
  81. package/lib/dts/src/validators/dateValidator.js +0 -83
  82. package/lib/dts/src/validators/dateValidator.js.map +0 -1
  83. package/lib/dts/src/validators/genericValidator.d.ts +0 -4
  84. package/lib/dts/src/validators/genericValidator.d.ts.map +0 -1
  85. package/lib/dts/src/validators/genericValidator.js +0 -93
  86. package/lib/dts/src/validators/genericValidator.js.map +0 -1
  87. package/lib/dts/src/validators/numberValidator.d.ts +0 -4
  88. package/lib/dts/src/validators/numberValidator.d.ts.map +0 -1
  89. package/lib/dts/src/validators/numberValidator.js +0 -47
  90. package/lib/dts/src/validators/numberValidator.js.map +0 -1
  91. package/lib/dts/src/validators/objectValidator.d.ts +0 -4
  92. package/lib/dts/src/validators/objectValidator.d.ts.map +0 -1
  93. package/lib/dts/src/validators/objectValidator.js +0 -48
  94. package/lib/dts/src/validators/objectValidator.js.map +0 -1
  95. package/lib/dts/src/validators/slugValidator.d.ts +0 -9
  96. package/lib/dts/src/validators/slugValidator.d.ts.map +0 -1
  97. package/lib/dts/src/validators/slugValidator.js +0 -83
  98. package/lib/dts/src/validators/slugValidator.js.map +0 -1
  99. package/lib/dts/src/validators/stringValidator.d.ts +0 -4
  100. package/lib/dts/src/validators/stringValidator.d.ts.map +0 -1
  101. package/lib/dts/src/validators/stringValidator.js +0 -94
  102. package/lib/dts/src/validators/stringValidator.js.map +0 -1
  103. package/lib/dts/test/array.test.d.ts +0 -2
  104. package/lib/dts/test/array.test.d.ts.map +0 -1
  105. package/lib/dts/test/array.test.js +0 -55
  106. package/lib/dts/test/array.test.js.map +0 -1
  107. package/lib/dts/test/children.test.d.ts +0 -2
  108. package/lib/dts/test/children.test.d.ts.map +0 -1
  109. package/lib/dts/test/children.test.js +0 -70
  110. package/lib/dts/test/children.test.js.map +0 -1
  111. package/lib/dts/test/createSchema.d.ts +0 -6
  112. package/lib/dts/test/createSchema.d.ts.map +0 -1
  113. package/lib/dts/test/createSchema.js +0 -19
  114. package/lib/dts/test/createSchema.js.map +0 -1
  115. package/lib/dts/test/generics.test.d.ts +0 -2
  116. package/lib/dts/test/generics.test.d.ts.map +0 -1
  117. package/lib/dts/test/generics.test.js +0 -60
  118. package/lib/dts/test/generics.test.js.map +0 -1
  119. package/lib/dts/test/infer.test.d.ts +0 -2
  120. package/lib/dts/test/infer.test.d.ts.map +0 -1
  121. package/lib/dts/test/infer.test.js +0 -244
  122. package/lib/dts/test/infer.test.js.map +0 -1
  123. package/lib/dts/test/mocks/mockSanityClient.d.ts +0 -6
  124. package/lib/dts/test/mocks/mockSanityClient.d.ts.map +0 -1
  125. package/lib/dts/test/mocks/mockSanityClient.js +0 -8
  126. package/lib/dts/test/mocks/mockSanityClient.js.map +0 -1
  127. package/lib/dts/test/nullExport.d.ts +0 -3
  128. package/lib/dts/test/nullExport.d.ts.map +0 -1
  129. package/lib/dts/test/nullExport.js +0 -4
  130. package/lib/dts/test/nullExport.js.map +0 -1
  131. package/lib/dts/test/numbers.test.d.ts +0 -2
  132. package/lib/dts/test/numbers.test.d.ts.map +0 -1
  133. package/lib/dts/test/numbers.test.js +0 -57
  134. package/lib/dts/test/numbers.test.js.map +0 -1
  135. package/lib/dts/test/strings.test.d.ts +0 -2
  136. package/lib/dts/test/strings.test.d.ts.map +0 -1
  137. package/lib/dts/test/strings.test.js +0 -100
  138. package/lib/dts/test/strings.test.js.map +0 -1
  139. package/lib/dts/tsconfig.lib.tsbuildinfo +0 -1
  140. package/lib/dts/tsconfig.tsbuildinfo +0 -1
  141. package/lib/index.cjs +0 -1341
  142. package/lib/index.cjs.map +0 -1
package/lib/index.js CHANGED
@@ -1,1331 +1,1274 @@
1
- import { cloneDeep, get, memoize, uniqBy } from 'lodash';
2
- import { isKeyedObject, isReference, isBlock, isBlockSchemaType, isSpanSchemaType, isTypedObject } from '@sanity/types';
3
- import formatDate from 'date-fns/format';
1
+ 'use strict';
4
2
 
5
- // Follows the same pattern as Rule and RuleClass. @see Rule
6
- const ValidationError = class ValidationError {
7
- message;
8
- paths;
9
- children;
10
- operation;
11
- constructor(message, options = {}) {
12
- this.message = message;
13
- this.paths = options.paths || [];
14
- this.children = options.children;
15
- this.operation = options.operation;
16
- }
17
- cloneWithMessage(msg) {
18
- return new ValidationError(msg, {
19
- paths: this.paths,
20
- children: this.children,
21
- operation: this.operation,
22
- });
23
- }
3
+ const _excluded = ["value", "type", "path", "parent"];
4
+ 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; }
5
+ 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; }
6
+ 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; }
7
+ 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; }
8
+ 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; }
9
+ Object.defineProperty(exports, '__esModule', {
10
+ value: true
11
+ });
12
+ var lodash = require('lodash');
13
+ var types = require('@sanity/types');
14
+ var formatDate = require('date-fns/format');
15
+ var rxjs = require('rxjs');
16
+ var operators = require('rxjs/operators');
17
+ function _interopDefaultLegacy(e) {
18
+ return e && typeof e === 'object' && 'default' in e ? e : {
19
+ 'default': e
20
+ };
21
+ }
22
+ var formatDate__default = /*#__PURE__*/_interopDefaultLegacy(formatDate);
23
+ const ValidationError = class ValidationError2 {
24
+ constructor(message) {
25
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
26
+ this.message = message;
27
+ this.paths = options.paths || [];
28
+ this.children = options.children;
29
+ this.operation = options.operation;
30
+ }
31
+ cloneWithMessage(msg) {
32
+ return new ValidationError2(msg, {
33
+ paths: this.paths,
34
+ children: this.children,
35
+ operation: this.operation
36
+ });
37
+ }
24
38
  };
25
-
26
- /* eslint-disable no-useless-escape */
27
- var escapeRegex = (string) => {
28
- // Escape ^$.*+-?=!:|\/()[]{},
29
- return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
39
+ var escapeRegex = string => {
40
+ return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, "\\$&");
30
41
  };
31
-
32
- function pathToString(path = []) {
33
- return path.reduce((target, segment, i) => {
34
- const segmentType = typeof segment;
35
- if (segmentType === 'number') {
36
- return `${target}[${segment}]`;
37
- }
38
- if (segmentType === 'string') {
39
- const separator = i === 0 ? '' : '.';
40
- return `${target}${separator}${segment}`;
41
- }
42
- if (isKeyedObject(segment)) {
43
- return `${target}[_key=="${segment._key}"]`;
44
- }
45
- throw new Error(`Unsupported path segment "${segment}"`);
46
- }, '');
42
+ function pathToString() {
43
+ let path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
44
+ return path.reduce((target, segment, i) => {
45
+ const segmentType = typeof segment;
46
+ if (segmentType === "number") {
47
+ return "".concat(target, "[").concat(segment, "]");
48
+ }
49
+ if (segmentType === "string") {
50
+ const separator = i === 0 ? "" : ".";
51
+ return "".concat(target).concat(separator).concat(segment);
52
+ }
53
+ if (types.isKeyedObject(segment)) {
54
+ return "".concat(target, "[_key==\"").concat(segment._key, "\"]");
55
+ }
56
+ throw new Error("Unsupported path segment \"".concat(segment, "\""));
57
+ }, "");
47
58
  }
48
-
49
- function isNonNullable$1(t) {
50
- return t !== null || t !== undefined;
51
- }
52
- function convertToValidationMarker(validatorResult, level, context) {
53
- if (!context) {
54
- throw new Error('missing context');
55
- }
56
- if (validatorResult === true)
57
- return [];
58
- if (Array.isArray(validatorResult)) {
59
- return validatorResult
60
- .flatMap((child) => convertToValidationMarker(child, level, context))
61
- .filter(isNonNullable$1);
62
- }
63
- if (typeof validatorResult === 'string') {
64
- return convertToValidationMarker(new ValidationError(validatorResult), level, context);
65
- }
66
- if (!(validatorResult instanceof ValidationError)) {
67
- // in order to accept the `ValidationErrorLike`, it at least needs to have
68
- // a `message` in the object
69
- if (typeof validatorResult?.message !== 'string') {
70
- throw new Error(`${pathToString(context.path)}: Validator must return 'true' if valid or an error message as a string on errors`);
71
- }
72
- // this is the occurs when an object is returned that wasn't created with the
73
- // `ValidationErrorClass`. in this case, we want to convert it to a class
74
- return convertToValidationMarker(new ValidationError(validatorResult.message, validatorResult), level, context);
75
- }
76
- const results = [];
77
- // the validator result does not include any item-level relative paths,
78
- // then just return the top-level path with the validation result
79
- if (!validatorResult.paths?.length) {
80
- return [
81
- {
82
- level: level || 'error',
83
- item: validatorResult,
84
- path: context.path || [],
85
- },
86
- ];
87
- }
88
- // if the validator result did include item-level relative paths, then for
89
- // each item-level relative path, create a validation marker that concatenates
90
- // the relative path with the path from the validation context
91
- return results.concat(validatorResult.paths.map((path) => ({
92
- path: (context.path || []).concat(path),
93
- level: level || 'error',
94
- item: validatorResult,
95
- })));
59
+ function isNonNullable$1(t) {
60
+ return t !== null || t !== void 0;
96
61
  }
97
-
98
- // this file was adapted from a previous dependency `type-of-is`
99
- // https://github.com/stephenhandley/type-of-is/blob/7138a7e79f5af7c286bf8123f60843a91aaebf38/index.js
100
- const _toString = {}.toString;
101
- const builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error];
102
- function isBuiltIn(_constructor) {
103
- for (let i = 0; i < builtIns.length; i++) {
104
- if (builtIns[i] === _constructor)
105
- return true;
106
- }
107
- return false;
108
- }
109
- function typeString(obj) {
110
- // [object Blah] -> Blah
111
- const stringType = _toString.call(obj).slice(8, -1);
112
- if (obj === null || obj === undefined)
113
- return stringType.toLowerCase();
114
- // eslint-disable-next-line @typescript-eslint/ban-types
115
- const constructorType = obj.constructor;
116
- if (constructorType && !isBuiltIn(constructorType))
117
- return constructorType.name;
118
- return stringType;
62
+ function convertToValidationMarker(validatorResult, level, context) {
63
+ var _a;
64
+ if (!context) {
65
+ throw new Error("missing context");
66
+ }
67
+ if (validatorResult === true) return [];
68
+ if (Array.isArray(validatorResult)) {
69
+ return validatorResult.flatMap(child => convertToValidationMarker(child, level, context)).filter(isNonNullable$1);
70
+ }
71
+ if (typeof validatorResult === "string") {
72
+ return convertToValidationMarker(new ValidationError(validatorResult), level, context);
73
+ }
74
+ if (!(validatorResult instanceof ValidationError)) {
75
+ if (typeof (validatorResult == null ? void 0 : validatorResult.message) !== "string") {
76
+ throw new Error("".concat(pathToString(context.path), ": Validator must return 'true' if valid or an error message as a string on errors"));
77
+ }
78
+ return convertToValidationMarker(new ValidationError(validatorResult.message, validatorResult), level, context);
79
+ }
80
+ const results = [];
81
+ if (!((_a = validatorResult.paths) == null ? void 0 : _a.length)) {
82
+ return [{
83
+ level: level || "error",
84
+ item: validatorResult,
85
+ path: context.path || []
86
+ }];
87
+ }
88
+ return results.concat(validatorResult.paths.map(path => ({
89
+ path: (context.path || []).concat(path),
90
+ level: level || "error",
91
+ item: validatorResult
92
+ })));
119
93
  }
120
-
121
- /**
122
- * Modified version of fast-deep-equal (https://github.com/epoberezkin/fast-deep-equal)
123
- * MIT-licensed, copyright (c) 2017 Evgeny Poberezkin
124
- **/
125
- // NOTE: when converting to typescript, some of the checks were inlined (vs
126
- // having them in a variable) because the type predicate type narrowing only
127
- // works when type predicate is called inline in the condition that starts the
128
- // control flow branch.
129
- // see here: https://www.typescriptlang.org/docs/handbook/2/narrowing.html
130
- function deepEquals(a, b) {
131
- if (a === b) {
132
- return true;
133
- }
134
- if (Array.isArray(a) && Array.isArray(b)) {
135
- if (a.length != b.length)
136
- return false;
137
- for (let i = 0; i < a.length; i++) {
138
- if (!deepEquals(a[i], b[i])) {
139
- return false;
140
- }
141
- }
142
- return true;
143
- }
144
- if (Array.isArray(a) != Array.isArray(b)) {
145
- return false;
146
- }
147
- if (a && b && typeof a === 'object' && typeof b === 'object') {
148
- const keys = Object.keys(a);
149
- if (keys.length !== Object.keys(b).length) {
150
- return false;
151
- }
152
- if (a instanceof Date && b instanceof Date) {
153
- return a.getTime() === b.getTime();
154
- }
155
- if (a instanceof Date != b instanceof Date) {
156
- return false;
157
- }
158
- if (a instanceof RegExp && b instanceof RegExp) {
159
- return a.toString() == b.toString();
160
- }
161
- if (a instanceof RegExp != b instanceof RegExp) {
162
- return false;
163
- }
164
- for (let i = 0; i < keys.length; i++) {
165
- if (keys[i] === '_key') {
166
- continue;
167
- }
168
- if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
169
- return false;
170
- }
171
- }
172
- for (let i = 0; i < keys.length; i++) {
173
- const key = keys[i];
174
- if (key === '_key') {
175
- continue;
176
- }
177
- if (!deepEquals(a[key], b[key])) {
178
- return false;
179
- }
180
- }
181
- return true;
182
- }
183
- return false;
94
+ const _toString = {}.toString;
95
+ const builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error];
96
+ function isBuiltIn(_constructor) {
97
+ for (let i = 0; i < builtIns.length; i++) {
98
+ if (builtIns[i] === _constructor) return true;
99
+ }
100
+ return false;
184
101
  }
185
-
186
- const SLOW_VALIDATOR_TIMEOUT = 5000;
187
- const formatValidationErrors = (options) => {
188
- let message;
189
- if (options.message) {
190
- message = options.message;
191
- }
192
- else if (options.results.length === 1) {
193
- message = options.results[0]?.item.message;
194
- }
195
- else {
196
- message = `[${options.results
197
- .map((err) => err.item.message)
198
- .join(` - ${options.operation} - `)}]`;
199
- }
200
- return new ValidationError(message, {
201
- children: options.results.length > 1 ? options.results : undefined,
202
- operation: options.operation,
203
- });
204
- };
205
- const genericValidators = {
206
- type: (expected, value, message) => {
207
- const actualType = typeString(value);
208
- if (actualType !== expected && actualType !== 'undefined') {
209
- return message || `Expected type "${expected}", got "${actualType}"`;
210
- }
211
- return true;
212
- },
213
- presence: (expected, value, message) => {
214
- if (value === undefined && expected === 'required') {
215
- return message || 'Value is required';
216
- }
217
- return true;
218
- },
219
- all: async (children, value, message, context) => {
220
- const resolved = await Promise.all(children.map((child) => child.validate(value, context)));
221
- const results = resolved.flat();
222
- if (!results.length)
223
- return true;
224
- return formatValidationErrors({
225
- message,
226
- results,
227
- operation: 'AND',
228
- });
229
- },
230
- either: async (children, value, message, context) => {
231
- const resolved = await Promise.all(children.map((child) => child.validate(value, context)));
232
- const results = resolved.flat();
233
- // Read: There is at least one rule that matched
234
- if (results.length < children.length)
235
- return true;
236
- return formatValidationErrors({
237
- message,
238
- results,
239
- operation: 'OR',
240
- });
241
- },
242
- valid: (allowedValues, actual, message) => {
243
- const valueType = typeof actual;
244
- if (valueType === 'undefined') {
245
- return true;
246
- }
247
- const value = (valueType === 'number' || valueType === 'string') && `${actual}`;
248
- const strValue = value && value.length > 30 ? `${value.slice(0, 30)}…` : value;
249
- const defaultMessage = value
250
- ? `Value "${strValue}" did not match any allowed values`
251
- : 'Value did not match any allowed values';
252
- return allowedValues.some((expected) => deepEquals(expected, actual))
253
- ? true
254
- : message || defaultMessage;
255
- },
256
- custom: async (fn, value, message, context) => {
257
- const slowTimer = setTimeout(() => {
258
- // eslint-disable-next-line no-console
259
- console.warn(`Custom validator at ${pathToString(context.path)} has taken more than ${SLOW_VALIDATOR_TIMEOUT}ms to respond`);
260
- }, SLOW_VALIDATOR_TIMEOUT);
261
- let result;
262
- try {
263
- result = await fn(value, context);
264
- }
265
- finally {
266
- clearTimeout(slowTimer);
267
- }
268
- if (typeof result === 'string')
269
- return message || result;
270
- return result;
271
- },
102
+ function typeString(obj) {
103
+ const stringType = _toString.call(obj).slice(8, -1);
104
+ if (obj === null || obj === void 0) return stringType.toLowerCase();
105
+ const constructorType = obj.constructor;
106
+ if (constructorType && !isBuiltIn(constructorType)) return constructorType.name;
107
+ return stringType;
108
+ }
109
+ function deepEquals(a, b) {
110
+ if (a === b) {
111
+ return true;
112
+ }
113
+ if (Array.isArray(a) && Array.isArray(b)) {
114
+ if (a.length != b.length) return false;
115
+ for (let i = 0; i < a.length; i++) {
116
+ if (!deepEquals(a[i], b[i])) {
117
+ return false;
118
+ }
119
+ }
120
+ return true;
121
+ }
122
+ if (Array.isArray(a) != Array.isArray(b)) {
123
+ return false;
124
+ }
125
+ if (a && b && typeof a === "object" && typeof b === "object") {
126
+ const keys = Object.keys(a);
127
+ if (keys.length !== Object.keys(b).length) {
128
+ return false;
129
+ }
130
+ if (a instanceof Date && b instanceof Date) {
131
+ return a.getTime() === b.getTime();
132
+ }
133
+ if (a instanceof Date != b instanceof Date) {
134
+ return false;
135
+ }
136
+ if (a instanceof RegExp && b instanceof RegExp) {
137
+ return a.toString() == b.toString();
138
+ }
139
+ if (a instanceof RegExp != b instanceof RegExp) {
140
+ return false;
141
+ }
142
+ for (let i = 0; i < keys.length; i++) {
143
+ if (keys[i] === "_key") {
144
+ continue;
145
+ }
146
+ if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
147
+ return false;
148
+ }
149
+ }
150
+ for (let i = 0; i < keys.length; i++) {
151
+ const key = keys[i];
152
+ if (key === "_key") {
153
+ continue;
154
+ }
155
+ if (!deepEquals(a[key], b[key])) {
156
+ return false;
157
+ }
158
+ }
159
+ return true;
160
+ }
161
+ return false;
162
+ }
163
+ const SLOW_VALIDATOR_TIMEOUT = 5e3;
164
+ const formatValidationErrors = options => {
165
+ var _a;
166
+ let message;
167
+ if (options.message) {
168
+ message = options.message;
169
+ } else if (options.results.length === 1) {
170
+ message = (_a = options.results[0]) == null ? void 0 : _a.item.message;
171
+ } else {
172
+ message = "[".concat(options.results.map(err => err.item.message).join(" - ".concat(options.operation, " - ")), "]");
173
+ }
174
+ return new ValidationError(message, {
175
+ children: options.results.length > 1 ? options.results : void 0,
176
+ operation: options.operation
177
+ });
272
178
  };
273
-
274
- const booleanValidators = {
275
- ...genericValidators,
276
- presence: (flag, value, message) => {
277
- if (flag === 'required' && typeof value !== 'boolean') {
278
- return message || 'Required';
279
- }
280
- return true;
281
- },
179
+ const genericValidators = {
180
+ type: (expected, value, message) => {
181
+ const actualType = typeString(value);
182
+ if (actualType !== expected && actualType !== "undefined") {
183
+ return message || "Expected type \"".concat(expected, "\", got \"").concat(actualType, "\"");
184
+ }
185
+ return true;
186
+ },
187
+ presence: (expected, value, message) => {
188
+ if (value === void 0 && expected === "required") {
189
+ return message || "Value is required";
190
+ }
191
+ return true;
192
+ },
193
+ all: async (children, value, message, context) => {
194
+ const resolved = await Promise.all(children.map(child => child.validate(value, context)));
195
+ const results = resolved.flat();
196
+ if (!results.length) return true;
197
+ return formatValidationErrors({
198
+ message,
199
+ results,
200
+ operation: "AND"
201
+ });
202
+ },
203
+ either: async (children, value, message, context) => {
204
+ const resolved = await Promise.all(children.map(child => child.validate(value, context)));
205
+ const results = resolved.flat();
206
+ if (results.length < children.length) return true;
207
+ return formatValidationErrors({
208
+ message,
209
+ results,
210
+ operation: "OR"
211
+ });
212
+ },
213
+ valid: (allowedValues, actual, message) => {
214
+ const valueType = typeof actual;
215
+ if (valueType === "undefined") {
216
+ return true;
217
+ }
218
+ const value = (valueType === "number" || valueType === "string") && "".concat(actual);
219
+ const strValue = value && value.length > 30 ? "".concat(value.slice(0, 30), "\u2026") : value;
220
+ const defaultMessage = value ? "Value \"".concat(strValue, "\" did not match any allowed values") : "Value did not match any allowed values";
221
+ return allowedValues.some(expected => deepEquals(expected, actual)) ? true : message || defaultMessage;
222
+ },
223
+ custom: async (fn, value, message, context) => {
224
+ const slowTimer = setTimeout(() => {
225
+ console.warn("Custom validator at ".concat(pathToString(context.path), " has taken more than ").concat(SLOW_VALIDATOR_TIMEOUT, "ms to respond"));
226
+ }, SLOW_VALIDATOR_TIMEOUT);
227
+ let result;
228
+ try {
229
+ result = await fn(value, context);
230
+ } finally {
231
+ clearTimeout(slowTimer);
232
+ }
233
+ if (typeof result === "string") return message || result;
234
+ return result;
235
+ }
282
236
  };
283
-
284
- const precisionRx = /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
285
- const numberValidators = {
286
- ...genericValidators,
287
- integer: (_unused, value, message) => {
288
- if (!Number.isInteger(value)) {
289
- return message || 'Must be an integer';
290
- }
291
- return true;
292
- },
293
- precision: (limit, value, message) => {
294
- if (value === undefined)
295
- return true;
296
- const places = value.toString().match(precisionRx);
297
- const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0);
298
- if (decimals > limit) {
299
- return message || `Max precision is ${limit}`;
300
- }
301
- return true;
302
- },
303
- min: (minNum, value, message) => {
304
- if (value >= minNum) {
305
- return true;
306
- }
307
- return message || `Must be greater than or equal ${minNum}`;
308
- },
309
- max: (maxNum, value, message) => {
310
- if (value <= maxNum) {
311
- return true;
312
- }
313
- return message || `Must be less than or equal ${maxNum}`;
314
- },
315
- greaterThan: (num, value, message) => {
316
- if (value > num) {
317
- return true;
318
- }
319
- return message || `Must be greater than ${num}`;
320
- },
321
- lessThan: (maxNum, value, message) => {
322
- if (value < maxNum) {
323
- return true;
324
- }
325
- return message || `Must be less than ${maxNum}`;
326
- },
237
+ const booleanValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
238
+ presence: (flag, value, message) => {
239
+ if (flag === "required" && typeof value !== "boolean") {
240
+ return message || "Required";
241
+ }
242
+ return true;
243
+ }
244
+ });
245
+ const precisionRx = /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
246
+ const numberValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
247
+ integer: (_unused, value, message) => {
248
+ if (!Number.isInteger(value)) {
249
+ return message || "Must be an integer";
250
+ }
251
+ return true;
252
+ },
253
+ precision: (limit, value, message) => {
254
+ if (value === void 0) return true;
255
+ const places = value.toString().match(precisionRx);
256
+ const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0);
257
+ if (decimals > limit) {
258
+ return message || "Max precision is ".concat(limit);
259
+ }
260
+ return true;
261
+ },
262
+ min: (minNum, value, message) => {
263
+ if (value >= minNum) {
264
+ return true;
265
+ }
266
+ return message || "Must be greater than or equal ".concat(minNum);
267
+ },
268
+ max: (maxNum, value, message) => {
269
+ if (value <= maxNum) {
270
+ return true;
271
+ }
272
+ return message || "Must be less than or equal ".concat(maxNum);
273
+ },
274
+ greaterThan: (num, value, message) => {
275
+ if (value > num) {
276
+ return true;
277
+ }
278
+ return message || "Must be greater than ".concat(num);
279
+ },
280
+ lessThan: (maxNum, value, message) => {
281
+ if (value < maxNum) {
282
+ return true;
283
+ }
284
+ return message || "Must be less than ".concat(maxNum);
285
+ }
286
+ });
287
+ const DUMMY_ORIGIN = "http://sanity";
288
+ const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
289
+ const isRelativeUrl = url => /^\.*\//.test(url);
290
+ const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
291
+ min: (minLength, value, message) => {
292
+ if (!value || value.length >= minLength) {
293
+ return true;
294
+ }
295
+ return message || "Must be at least ".concat(minLength, " characters long");
296
+ },
297
+ max: (maxLength, value, message) => {
298
+ if (!value || value.length <= maxLength) {
299
+ return true;
300
+ }
301
+ return message || "Must be at most ".concat(maxLength, " characters long");
302
+ },
303
+ length: (wantedLength, value, message) => {
304
+ const strValue = value || "";
305
+ if (strValue.length === wantedLength) {
306
+ return true;
307
+ }
308
+ return message || "Must be exactly ".concat(wantedLength, " characters long");
309
+ },
310
+ uri: (constraints, value, message) => {
311
+ const strValue = value || "";
312
+ const {
313
+ options
314
+ } = constraints;
315
+ const {
316
+ allowCredentials,
317
+ relativeOnly
318
+ } = options;
319
+ const allowRelative = options.allowRelative || relativeOnly;
320
+ let url;
321
+ try {
322
+ url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue);
323
+ } catch (err) {
324
+ return message || "Not a valid URL";
325
+ }
326
+ if (relativeOnly && url.origin !== DUMMY_ORIGIN) {
327
+ return message || "Only relative URLs are allowed";
328
+ }
329
+ if (!allowRelative && url.origin === DUMMY_ORIGIN && isRelativeUrl(strValue)) {
330
+ return message || "Relative URLs are not allowed";
331
+ }
332
+ if (!allowCredentials && (url.username || url.password)) {
333
+ return message || "Username/password not allowed";
334
+ }
335
+ const urlScheme = url.protocol.replace(/:$/, "");
336
+ const matchesAllowedScheme = options.scheme.some(scheme => scheme.test(urlScheme));
337
+ if (!matchesAllowedScheme) {
338
+ return message || "Does not match allowed protocols/schemes";
339
+ }
340
+ return true;
341
+ },
342
+ stringCasing: (casing, value, message) => {
343
+ const strValue = value || "";
344
+ if (casing === "uppercase" && strValue !== strValue.toLocaleUpperCase()) {
345
+ return message || "Must be all uppercase letters";
346
+ }
347
+ if (casing === "lowercase" && strValue !== strValue.toLocaleLowerCase()) {
348
+ return message || "Must be all lowercase letters";
349
+ }
350
+ return true;
351
+ },
352
+ presence: (flag, value, message) => {
353
+ if (flag === "required" && !value) {
354
+ return message || "Required";
355
+ }
356
+ return true;
357
+ },
358
+ regex: (options, value, message) => {
359
+ const {
360
+ pattern,
361
+ name,
362
+ invert
363
+ } = options;
364
+ const regName = name || "\"".concat(pattern.toString(), "\"");
365
+ const strValue = value || "";
366
+ const matches = pattern.test(strValue);
367
+ if (!invert && !matches || invert && matches) {
368
+ const defaultMessage = invert ? "Should not match ".concat(regName, "-pattern") : "Does not match ".concat(regName, "-pattern");
369
+ return message || defaultMessage;
370
+ }
371
+ return true;
372
+ },
373
+ email: (_unused, value, message) => {
374
+ const strValue = "".concat(value || "").trim();
375
+ if (!strValue || emailRegex.test(strValue)) {
376
+ return true;
377
+ }
378
+ return message || "Must be a valid email address";
379
+ }
380
+ });
381
+ const arrayValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
382
+ min: (minLength, value, message) => {
383
+ if (!value || value.length >= minLength) {
384
+ return true;
385
+ }
386
+ return message || "Must have at least ".concat(minLength, " items");
387
+ },
388
+ max: (maxLength, value, message) => {
389
+ if (!value || value.length <= maxLength) {
390
+ return true;
391
+ }
392
+ return message || "Must have at most ".concat(maxLength, " items");
393
+ },
394
+ length: (wantedLength, value, message) => {
395
+ if (!value || value.length === wantedLength) {
396
+ return true;
397
+ }
398
+ return message || "Must have exactly ".concat(wantedLength, " items");
399
+ },
400
+ presence: (flag, value, message) => {
401
+ if (flag === "required" && !value) {
402
+ return message || "Required";
403
+ }
404
+ return true;
405
+ },
406
+ valid: (allowedValues, values, message) => {
407
+ const valueType = typeof values;
408
+ if (valueType === "undefined") {
409
+ return true;
410
+ }
411
+ const paths = [];
412
+ for (let i = 0; i < values.length; i++) {
413
+ const value = values[i];
414
+ if (allowedValues.some(expected => deepEquals(expected, value))) {
415
+ continue;
416
+ }
417
+ const pathSegment = value && value._key ? {
418
+ _key: value._key
419
+ } : i;
420
+ paths.push([pathSegment]);
421
+ }
422
+ return paths.length === 0 ? true : new ValidationError(message || "Value did not match any allowed values", {
423
+ paths
424
+ });
425
+ },
426
+ unique: (_unused, value, message) => {
427
+ const dupeIndices = [];
428
+ if (!value) {
429
+ return true;
430
+ }
431
+ for (let x = 0; x < value.length; x++) {
432
+ for (let y = x + 1; y < value.length; y++) {
433
+ const itemA = value[x];
434
+ const itemB = value[y];
435
+ if (!deepEquals(itemA, itemB)) {
436
+ continue;
437
+ }
438
+ if (dupeIndices.indexOf(x) === -1) {
439
+ dupeIndices.push(x);
440
+ }
441
+ if (dupeIndices.indexOf(y) === -1) {
442
+ dupeIndices.push(y);
443
+ }
444
+ }
445
+ }
446
+ const paths = dupeIndices.map(idx => {
447
+ const item = value[idx];
448
+ const pathSegment = item && item._key ? {
449
+ _key: item._key
450
+ } : idx;
451
+ return [pathSegment];
452
+ });
453
+ return dupeIndices.length > 0 ? new ValidationError(message || "Can't be a duplicate", {
454
+ paths
455
+ }) : true;
456
+ }
457
+ });
458
+ const metaKeys = ["_key", "_type", "_weak"];
459
+ const objectValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
460
+ presence: (expected, value, message) => {
461
+ if (expected !== "required") {
462
+ return true;
463
+ }
464
+ const keys = value && Object.keys(value).filter(key => !metaKeys.includes(key));
465
+ if (value === void 0 || keys && keys.length === 0) {
466
+ return message || "Required";
467
+ }
468
+ return true;
469
+ },
470
+ reference: async (_unused, value, message, context) => {
471
+ if (!value) {
472
+ return true;
473
+ }
474
+ if (!types.isReference(value)) {
475
+ return message || true;
476
+ }
477
+ const {
478
+ type,
479
+ getDocumentExists
480
+ } = context;
481
+ if (!type) {
482
+ throw new Error("`type` was not provided in validation context");
483
+ }
484
+ if ("weak" in type && type.weak) {
485
+ return true;
486
+ }
487
+ if (!getDocumentExists) {
488
+ throw new Error("`getDocumentExists` was not provided in validation context");
489
+ }
490
+ const exists = await getDocumentExists({
491
+ id: value._ref
492
+ });
493
+ if (!exists) {
494
+ return "This reference must be published";
495
+ }
496
+ return true;
497
+ },
498
+ assetRequired: (flag, value, message) => {
499
+ if (!value || !value.asset || !value.asset._ref) {
500
+ const assetType = flag.assetType || "Asset";
501
+ return message || "".concat(assetType, " required");
502
+ }
503
+ return true;
504
+ }
505
+ });
506
+ function isRecord$1(obj) {
507
+ return typeof obj === "object" && obj !== null && !Array.isArray(obj);
508
+ }
509
+ const isoDate = /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/;
510
+ const getFormattedDate = function () {
511
+ let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
512
+ let value = arguments.length > 1 ? arguments[1] : undefined;
513
+ let options = arguments.length > 2 ? arguments[2] : undefined;
514
+ let format = "yyyy-MM-dd";
515
+ if (options && options.dateFormat) {
516
+ format = options.dateFormat;
517
+ }
518
+ if (type === "date") {
519
+ return formatDate__default["default"](new Date(value), format);
520
+ }
521
+ if (options && options.timeFormat) {
522
+ format += " ".concat(options.timeFormat);
523
+ } else {
524
+ format += " HH:mm";
525
+ }
526
+ return formatDate__default["default"](new Date(value), format);
327
527
  };
328
-
329
- const DUMMY_ORIGIN = 'http://sanity';
330
- const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
331
- const isRelativeUrl = (url) => /^\.*\//.test(url);
332
- const stringValidators = {
333
- ...genericValidators,
334
- min: (minLength, value, message) => {
335
- if (!value || value.length >= minLength) {
336
- return true;
337
- }
338
- return message || `Must be at least ${minLength} characters long`;
339
- },
340
- max: (maxLength, value, message) => {
341
- if (!value || value.length <= maxLength) {
342
- return true;
343
- }
344
- return message || `Must be at most ${maxLength} characters long`;
345
- },
346
- length: (wantedLength, value, message) => {
347
- const strValue = value || '';
348
- if (strValue.length === wantedLength) {
349
- return true;
350
- }
351
- return message || `Must be exactly ${wantedLength} characters long`;
352
- },
353
- uri: (constraints, value, message) => {
354
- const strValue = value || '';
355
- const { options } = constraints;
356
- const { allowCredentials, relativeOnly } = options;
357
- const allowRelative = options.allowRelative || relativeOnly;
358
- let url;
359
- try {
360
- // WARNING: Safari checks for a given `base` param by looking at the length of arguments passed
361
- // to new URL(str, base), and will fail if invoked with new URL(strValue, undefined)
362
- url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue);
363
- }
364
- catch (err) {
365
- return message || 'Not a valid URL';
366
- }
367
- if (relativeOnly && url.origin !== DUMMY_ORIGIN) {
368
- return message || 'Only relative URLs are allowed';
369
- }
370
- if (!allowRelative && url.origin === DUMMY_ORIGIN && isRelativeUrl(strValue)) {
371
- return message || 'Relative URLs are not allowed';
372
- }
373
- if (!allowCredentials && (url.username || url.password)) {
374
- return message || `Username/password not allowed`;
375
- }
376
- const urlScheme = url.protocol.replace(/:$/, '');
377
- const matchesAllowedScheme = options.scheme.some((scheme) => scheme.test(urlScheme));
378
- if (!matchesAllowedScheme) {
379
- return message || 'Does not match allowed protocols/schemes';
380
- }
381
- return true;
382
- },
383
- stringCasing: (casing, value, message) => {
384
- const strValue = value || '';
385
- if (casing === 'uppercase' && strValue !== strValue.toLocaleUpperCase()) {
386
- return message || `Must be all uppercase letters`;
387
- }
388
- if (casing === 'lowercase' && strValue !== strValue.toLocaleLowerCase()) {
389
- return message || `Must be all lowercase letters`;
390
- }
391
- return true;
392
- },
393
- presence: (flag, value, message) => {
394
- if (flag === 'required' && !value) {
395
- return message || 'Required';
396
- }
397
- return true;
398
- },
399
- regex: (options, value, message) => {
400
- const { pattern, name, invert } = options;
401
- const regName = name || `"${pattern.toString()}"`;
402
- const strValue = value || '';
403
- const matches = pattern.test(strValue);
404
- if ((!invert && !matches) || (invert && matches)) {
405
- const defaultMessage = invert
406
- ? `Should not match ${regName}-pattern`
407
- : `Does not match ${regName}-pattern`;
408
- return message || defaultMessage;
409
- }
410
- return true;
411
- },
412
- email: (_unused, value, message) => {
413
- const strValue = `${value || ''}`.trim();
414
- if (!strValue || emailRegex.test(strValue)) {
415
- return true;
416
- }
417
- return message || 'Must be a valid email address';
418
- },
528
+ function parseDate(date) {
529
+ let throwOnError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
530
+ if (!date) return null;
531
+ if (date === "now") return new Date();
532
+ const parsed = new Date(date);
533
+ const isInvalid = isNaN(parsed.getTime());
534
+ if (isInvalid && throwOnError) {
535
+ throw new Error("Unable to parse \"".concat(date, "\" to a date"));
536
+ }
537
+ return isInvalid ? null : parsed;
538
+ }
539
+ const dateValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
540
+ type: (_unused, value, message) => {
541
+ const strVal = "".concat(value);
542
+ if (!strVal || isoDate.test(value)) {
543
+ return true;
544
+ }
545
+ return message || "Must be a valid ISO-8601 formatted date string";
546
+ },
547
+ min: (minDate, value, message, context) => {
548
+ const dateVal = parseDate(value);
549
+ if (!dateVal) {
550
+ return true;
551
+ }
552
+ if (!value || dateVal >= parseDate(minDate, true)) {
553
+ return true;
554
+ }
555
+ if (!context.type) {
556
+ throw new Error("`type` was not provided in validation context.");
557
+ }
558
+ const dateTimeOptions = isRecord$1(context.type.options) ? context.type.options : {};
559
+ const date = getFormattedDate(context.type.name, minDate, dateTimeOptions);
560
+ return message || "Must be at or after ".concat(date);
561
+ },
562
+ max: (maxDate, value, message, context) => {
563
+ const dateVal = parseDate(value);
564
+ if (!dateVal) {
565
+ return true;
566
+ }
567
+ if (!value || dateVal <= parseDate(maxDate, true)) {
568
+ return true;
569
+ }
570
+ if (!context.type) {
571
+ throw new Error("`type` was not provided in validation context.");
572
+ }
573
+ const dateTimeOptions = isRecord$1(context.type.options) ? context.type.options : {};
574
+ const date = getFormattedDate(context.type.name, maxDate, dateTimeOptions);
575
+ return message || "Must be at or before ".concat(date);
576
+ }
577
+ });
578
+ var _a;
579
+ const typeValidators = {
580
+ Boolean: booleanValidators,
581
+ Number: numberValidators,
582
+ String: stringValidators,
583
+ Array: arrayValidators,
584
+ Object: objectValidators,
585
+ Date: dateValidators
419
586
  };
420
-
421
- const arrayValidators = {
422
- ...genericValidators,
423
- min: (minLength, value, message) => {
424
- if (!value || value.length >= minLength) {
425
- return true;
426
- }
427
- return message || `Must have at least ${minLength} items`;
428
- },
429
- max: (maxLength, value, message) => {
430
- if (!value || value.length <= maxLength) {
431
- return true;
432
- }
433
- return message || `Must have at most ${maxLength} items`;
434
- },
435
- length: (wantedLength, value, message) => {
436
- if (!value || value.length === wantedLength) {
437
- return true;
438
- }
439
- return message || `Must have exactly ${wantedLength} items`;
440
- },
441
- presence: (flag, value, message) => {
442
- if (flag === 'required' && !value) {
443
- return message || 'Required';
444
- }
445
- return true;
446
- },
447
- valid: (allowedValues, values, message) => {
448
- const valueType = typeof values;
449
- if (valueType === 'undefined') {
450
- return true;
451
- }
452
- const paths = [];
453
- for (let i = 0; i < values.length; i++) {
454
- const value = values[i];
455
- if (allowedValues.some((expected) => deepEquals(expected, value))) {
456
- continue;
457
- }
458
- const pathSegment = value && value._key ? { _key: value._key } : i;
459
- paths.push([pathSegment]);
460
- }
461
- return paths.length === 0
462
- ? true
463
- : new ValidationError(message || 'Value did not match any allowed values', { paths });
464
- },
465
- unique: (_unused, value, message) => {
466
- const dupeIndices = [];
467
- if (!value) {
468
- return true;
469
- }
470
- for (let x = 0; x < value.length; x++) {
471
- for (let y = x + 1; y < value.length; y++) {
472
- const itemA = value[x];
473
- const itemB = value[y];
474
- if (!deepEquals(itemA, itemB)) {
475
- continue;
476
- }
477
- if (dupeIndices.indexOf(x) === -1) {
478
- dupeIndices.push(x);
479
- }
480
- if (dupeIndices.indexOf(y) === -1) {
481
- dupeIndices.push(y);
482
- }
483
- }
484
- }
485
- const paths = dupeIndices.map((idx) => {
486
- const item = value[idx];
487
- const pathSegment = item && item._key ? { _key: item._key } : idx;
488
- return [pathSegment];
489
- });
490
- return dupeIndices.length > 0
491
- ? new ValidationError(message || `Can't be a duplicate`, { paths })
492
- : true;
493
- },
587
+ const getBaseType = type => {
588
+ return type && type.type ? getBaseType(type.type) : type;
494
589
  };
495
-
496
- const metaKeys = ['_key', '_type', '_weak'];
497
- const objectValidators = {
498
- ...genericValidators,
499
- presence: (expected, value, message) => {
500
- if (expected !== 'required') {
501
- return true;
502
- }
503
- const keys = value && Object.keys(value).filter((key) => !metaKeys.includes(key));
504
- if (value === undefined || (keys && keys.length === 0)) {
505
- return message || 'Required';
506
- }
507
- return true;
508
- },
509
- reference: async (_unused, value, message, context) => {
510
- if (!value) {
511
- return true;
512
- }
513
- if (!isReference(value)) {
514
- return message || true;
515
- }
516
- const { type, getDocumentExists } = context;
517
- if (!type) {
518
- throw new Error(`\`type\` was not provided in validation context`);
519
- }
520
- if ('weak' in type && type.weak) {
521
- return true;
522
- }
523
- if (!getDocumentExists) {
524
- throw new Error(`\`getDocumentExists\` was not provided in validation context`);
525
- }
526
- const exists = await getDocumentExists({ id: value._ref });
527
- if (!exists) {
528
- return 'This reference must be published';
529
- }
530
- return true;
531
- },
532
- assetRequired: (flag, value, message) => {
533
- if (!value || !value.asset || !value.asset._ref) {
534
- const assetType = flag.assetType || 'Asset';
535
- return message || `${assetType} required`;
536
- }
537
- return true;
538
- },
590
+ const isFieldRef = constraint => {
591
+ if (typeof constraint !== "object" || !constraint) return false;
592
+ return constraint.type === Rule.FIELD_REF;
539
593
  };
540
-
541
- function isRecord$1(obj) {
542
- return typeof obj === 'object' && obj !== null && !Array.isArray(obj);
543
- }
544
- const isoDate = /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/;
545
- const getFormattedDate = (type = '', value, options) => {
546
- let format = 'yyyy-MM-dd';
547
- if (options && options.dateFormat) {
548
- format = options.dateFormat;
549
- }
550
- if (type === 'date') {
551
- // If the type is date only
552
- return formatDate(new Date(value), format);
553
- }
554
- // If the type is datetime
555
- if (options && options.timeFormat) {
556
- format += ` ${options.timeFormat}`;
557
- }
558
- else {
559
- format += ' HH:mm';
560
- }
561
- return formatDate(new Date(value), format);
562
- };
563
- function parseDate(date, throwOnError = false) {
564
- if (!date)
565
- return null;
566
- if (date === 'now')
567
- return new Date();
568
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
569
- const parsed = new Date(date);
570
- const isInvalid = isNaN(parsed.getTime());
571
- if (isInvalid && throwOnError) {
572
- throw new Error(`Unable to parse "${date}" to a date`);
573
- }
574
- return isInvalid ? null : parsed;
575
- }
576
- const dateValidators = {
577
- ...genericValidators,
578
- type: (_unused, value, message) => {
579
- const strVal = `${value}`;
580
- if (!strVal || isoDate.test(value)) {
581
- return true;
582
- }
583
- return message || 'Must be a valid ISO-8601 formatted date string';
584
- },
585
- min: (minDate, value, message, context) => {
586
- const dateVal = parseDate(value);
587
- if (!dateVal) {
588
- return true; // `type()` should catch parse errors
589
- }
590
- if (!value || dateVal >= parseDate(minDate, true)) {
591
- return true;
592
- }
593
- if (!context.type) {
594
- throw new Error(`\`type\` was not provided in validation context.`);
595
- }
596
- const dateTimeOptions = isRecord$1(context.type.options)
597
- ? context.type.options
598
- : {};
599
- const date = getFormattedDate(context.type.name, minDate, dateTimeOptions);
600
- return message || `Must be at or after ${date}`;
601
- },
602
- max: (maxDate, value, message, context) => {
603
- const dateVal = parseDate(value);
604
- if (!dateVal) {
605
- return true; // `type()` should catch parse errors
606
- }
607
- if (!value || dateVal <= parseDate(maxDate, true)) {
608
- return true;
609
- }
610
- if (!context.type) {
611
- throw new Error(`\`type\` was not provided in validation context.`);
612
- }
613
- const dateTimeOptions = isRecord$1(context.type.options)
614
- ? context.type.options
615
- : {};
616
- const date = getFormattedDate(context.type.name, maxDate, dateTimeOptions);
617
- return message || `Must be at or before ${date}`;
618
- },
594
+ const EMPTY_ARRAY = [];
595
+ const FIELD_REF = Symbol("FIELD_REF");
596
+ const ruleConstraintTypes$1 = ["Array", "Boolean", "Date", "Number", "Object", "String"];
597
+ const Rule = (_a = class {
598
+ constructor(typeDef) {
599
+ this._type = void 0;
600
+ this._level = void 0;
601
+ this._required = void 0;
602
+ this._typeDef = void 0;
603
+ this._message = void 0;
604
+ this._rules = [];
605
+ this._fieldRules = void 0;
606
+ this.valueOfField = _a.valueOfField.bind(_a);
607
+ this._typeDef = typeDef;
608
+ this.reset();
609
+ }
610
+ _mergeRequired(next) {
611
+ if (this._required === "required" || next._required === "required") return "required";
612
+ if (this._required === "optional" || next._required === "optional") return "optional";
613
+ return void 0;
614
+ }
615
+ error(message) {
616
+ const rule = this.clone();
617
+ rule._level = "error";
618
+ rule._message = message || void 0;
619
+ return rule;
620
+ }
621
+ warning(message) {
622
+ const rule = this.clone();
623
+ rule._level = "warning";
624
+ rule._message = message || void 0;
625
+ return rule;
626
+ }
627
+ info(message) {
628
+ const rule = this.clone();
629
+ rule._level = "info";
630
+ rule._message = message || void 0;
631
+ return rule;
632
+ }
633
+ reset() {
634
+ this._type = this._type || void 0;
635
+ this._rules = (this._rules || []).filter(rule => rule.flag === "type");
636
+ this._message = void 0;
637
+ this._required = void 0;
638
+ this._level = "error";
639
+ this._fieldRules = void 0;
640
+ return this;
641
+ }
642
+ isRequired() {
643
+ return this._required === "required";
644
+ }
645
+ clone() {
646
+ const rule = new _a();
647
+ rule._type = this._type;
648
+ rule._message = this._message;
649
+ rule._required = this._required;
650
+ rule._rules = lodash.cloneDeep(this._rules);
651
+ rule._level = this._level;
652
+ rule._fieldRules = this._fieldRules;
653
+ rule._typeDef = this._typeDef;
654
+ return rule;
655
+ }
656
+ cloneWithRules(rules) {
657
+ const rule = this.clone();
658
+ const newRules = /* @__PURE__ */new Set();
659
+ rules.forEach(curr => {
660
+ if (curr.flag === "type") {
661
+ rule._type = curr.constraint;
662
+ }
663
+ newRules.add(curr.flag);
664
+ });
665
+ rule._rules = rule._rules.filter(curr => {
666
+ const disallowDuplicate = ["type", "uri", "email"].includes(curr.flag);
667
+ const isDuplicate = newRules.has(curr.flag);
668
+ return !(disallowDuplicate && isDuplicate);
669
+ }).concat(rules);
670
+ return rule;
671
+ }
672
+ merge(rule) {
673
+ if (this._type && rule._type && this._type !== rule._type) {
674
+ throw new Error("merge() failed: conflicting types");
675
+ }
676
+ const newRule = this.cloneWithRules(rule._rules);
677
+ newRule._type = this._type || rule._type;
678
+ newRule._message = this._message || rule._message;
679
+ newRule._required = this._mergeRequired(rule);
680
+ newRule._level = this._level === "error" ? rule._level : this._level;
681
+ return newRule;
682
+ }
683
+ type(targetType) {
684
+ const type = "".concat(targetType.slice(0, 1).toUpperCase()).concat(targetType.slice(1));
685
+ if (!ruleConstraintTypes$1.includes(type)) {
686
+ throw new Error("Unknown type \"".concat(targetType, "\""));
687
+ }
688
+ const rule = this.cloneWithRules([{
689
+ flag: "type",
690
+ constraint: type
691
+ }]);
692
+ rule._type = type;
693
+ return rule;
694
+ }
695
+ all(children) {
696
+ return this.cloneWithRules([{
697
+ flag: "all",
698
+ constraint: children
699
+ }]);
700
+ }
701
+ either(children) {
702
+ return this.cloneWithRules([{
703
+ flag: "either",
704
+ constraint: children
705
+ }]);
706
+ }
707
+ optional() {
708
+ const rule = this.cloneWithRules([{
709
+ flag: "presence",
710
+ constraint: "optional"
711
+ }]);
712
+ rule._required = "optional";
713
+ return rule;
714
+ }
715
+ required() {
716
+ const rule = this.cloneWithRules([{
717
+ flag: "presence",
718
+ constraint: "required"
719
+ }]);
720
+ rule._required = "required";
721
+ return rule;
722
+ }
723
+ custom(fn) {
724
+ return this.cloneWithRules([{
725
+ flag: "custom",
726
+ constraint: fn
727
+ }]);
728
+ }
729
+ block(fn) {
730
+ return this.cloneWithRules([{
731
+ flag: "custom",
732
+ constraint: fn
733
+ }]);
734
+ }
735
+ min(len) {
736
+ return this.cloneWithRules([{
737
+ flag: "min",
738
+ constraint: len
739
+ }]);
740
+ }
741
+ max(len) {
742
+ return this.cloneWithRules([{
743
+ flag: "max",
744
+ constraint: len
745
+ }]);
746
+ }
747
+ length(len) {
748
+ return this.cloneWithRules([{
749
+ flag: "length",
750
+ constraint: len
751
+ }]);
752
+ }
753
+ valid(value) {
754
+ const values = Array.isArray(value) ? value : [value];
755
+ return this.cloneWithRules([{
756
+ flag: "valid",
757
+ constraint: values
758
+ }]);
759
+ }
760
+ integer() {
761
+ return this.cloneWithRules([{
762
+ flag: "integer"
763
+ }]);
764
+ }
765
+ precision(limit) {
766
+ return this.cloneWithRules([{
767
+ flag: "precision",
768
+ constraint: limit
769
+ }]);
770
+ }
771
+ positive() {
772
+ return this.cloneWithRules([{
773
+ flag: "min",
774
+ constraint: 0
775
+ }]);
776
+ }
777
+ negative() {
778
+ return this.cloneWithRules([{
779
+ flag: "lessThan",
780
+ constraint: 0
781
+ }]);
782
+ }
783
+ greaterThan(num) {
784
+ return this.cloneWithRules([{
785
+ flag: "greaterThan",
786
+ constraint: num
787
+ }]);
788
+ }
789
+ lessThan(num) {
790
+ return this.cloneWithRules([{
791
+ flag: "lessThan",
792
+ constraint: num
793
+ }]);
794
+ }
795
+ uppercase() {
796
+ return this.cloneWithRules([{
797
+ flag: "stringCasing",
798
+ constraint: "uppercase"
799
+ }]);
800
+ }
801
+ lowercase() {
802
+ return this.cloneWithRules([{
803
+ flag: "stringCasing",
804
+ constraint: "lowercase"
805
+ }]);
806
+ }
807
+ regex(pattern, a, b) {
808
+ var _a2, _b;
809
+ const name = typeof a === "string" ? a : (_a2 = a == null ? void 0 : a.name) != null ? _a2 : b == null ? void 0 : b.name;
810
+ const invert = typeof a === "string" ? false : (_b = a == null ? void 0 : a.invert) != null ? _b : b == null ? void 0 : b.invert;
811
+ const constraint = {
812
+ pattern,
813
+ name,
814
+ invert: invert || false
815
+ };
816
+ return this.cloneWithRules([{
817
+ flag: "regex",
818
+ constraint
819
+ }]);
820
+ }
821
+ email() {
822
+ return this.cloneWithRules([{
823
+ flag: "email"
824
+ }]);
825
+ }
826
+ uri(opts) {
827
+ const optsScheme = (opts == null ? void 0 : opts.scheme) || ["http", "https"];
828
+ const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme];
829
+ if (!schemes.length) {
830
+ throw new Error("scheme must have at least 1 scheme specified");
831
+ }
832
+ const constraint = {
833
+ options: {
834
+ scheme: schemes.map(scheme => {
835
+ if (!(scheme instanceof RegExp) && typeof scheme !== "string") {
836
+ throw new Error("scheme must be a RegExp or a String");
837
+ }
838
+ return typeof scheme === "string" ? new RegExp("^".concat(escapeRegex(scheme), "$")) : scheme;
839
+ }),
840
+ allowRelative: (opts == null ? void 0 : opts.allowRelative) || false,
841
+ relativeOnly: (opts == null ? void 0 : opts.relativeOnly) || false,
842
+ allowCredentials: (opts == null ? void 0 : opts.allowCredentials) || false
843
+ }
844
+ };
845
+ return this.cloneWithRules([{
846
+ flag: "uri",
847
+ constraint
848
+ }]);
849
+ }
850
+ unique() {
851
+ return this.cloneWithRules([{
852
+ flag: "unique"
853
+ }]);
854
+ }
855
+ reference() {
856
+ return this.cloneWithRules([{
857
+ flag: "reference"
858
+ }]);
859
+ }
860
+ fields(rules) {
861
+ if (this._type !== "Object") {
862
+ throw new Error("fields() can only be called on an object type");
863
+ }
864
+ const rule = this.cloneWithRules([]);
865
+ rule._fieldRules = rules;
866
+ return rule;
867
+ }
868
+ assetRequired() {
869
+ const base = getBaseType(this._typeDef);
870
+ let assetType;
871
+ if (base && ["image", "file"].includes(base.name)) {
872
+ assetType = base.name === "image" ? "Image" : "File";
873
+ } else {
874
+ assetType = "Asset";
875
+ }
876
+ return this.cloneWithRules([{
877
+ flag: "assetRequired",
878
+ constraint: {
879
+ assetType
880
+ }
881
+ }]);
882
+ }
883
+ async validate(value, context) {
884
+ if (!context) {
885
+ throw new Error("missing context");
886
+ }
887
+ const valueIsEmpty = value === null || value === void 0;
888
+ if (valueIsEmpty && this._required === "optional") {
889
+ return EMPTY_ARRAY;
890
+ }
891
+ const rules = this._required === void 0 && valueIsEmpty ? this._rules.filter(curr => curr.flag === "custom") : this._rules;
892
+ const validators = this._type && typeValidators[this._type] || genericValidators;
893
+ const results = await Promise.all(rules.map(async curr => {
894
+ if (curr.flag === void 0) {
895
+ throw new Error('Invalid rule, did not contain "flag"-property');
896
+ }
897
+ const validator = validators[curr.flag];
898
+ if (!validator) {
899
+ const forType = this._type ? "type \"".concat(this._type, "\"") : "rule without declared type";
900
+ throw new Error("Validator for flag \"".concat(curr.flag, "\" not found for ").concat(forType));
901
+ }
902
+ let specConstraint = "constraint" in curr ? curr.constraint : null;
903
+ if (isFieldRef(specConstraint)) {
904
+ specConstraint = lodash.get(context.parent, specConstraint.path);
905
+ }
906
+ let result;
907
+ try {
908
+ result = await validator(specConstraint, value, this._message, context);
909
+ } catch (err) {
910
+ const errorFromException = new ValidationError("".concat(pathToString(context.path), ": Exception occurred while validating value: ").concat(err.message));
911
+ return convertToValidationMarker(errorFromException, "error", context);
912
+ }
913
+ return convertToValidationMarker(result, this._level, context);
914
+ }));
915
+ return results.flat();
916
+ }
917
+ }, _a.FIELD_REF = FIELD_REF, _a.array = def => new _a(def).type("Array"), _a.object = def => new _a(def).type("Object"), _a.string = def => new _a(def).type("String"), _a.number = def => new _a(def).type("Number"), _a.boolean = def => new _a(def).type("Boolean"), _a.dateTime = def => new _a(def).type("Date"), _a.valueOfField = path => ({
918
+ type: FIELD_REF,
919
+ path
920
+ }), _a);
921
+ const requestIdleCallbackShim = function requestIdleCallbackShim2(callback, options) {
922
+ const start = Date.now();
923
+ return window.setTimeout(() => {
924
+ callback({
925
+ didTimeout: false,
926
+ timeRemaining() {
927
+ return Math.max(0, Date.now() - start);
928
+ }
929
+ });
930
+ }, 0);
619
931
  };
620
-
621
- const typeValidators = {
622
- Boolean: booleanValidators,
623
- Number: numberValidators,
624
- String: stringValidators,
625
- Array: arrayValidators,
626
- Object: objectValidators,
627
- Date: dateValidators,
628
- };
629
- const getBaseType = (type) => {
630
- return type && type.type ? getBaseType(type.type) : type;
631
- };
632
- const isFieldRef = (constraint) => {
633
- if (typeof constraint !== 'object' || !constraint)
634
- return false;
635
- return constraint.type === Rule.FIELD_REF;
636
- };
637
- const EMPTY_ARRAY = [];
638
- const FIELD_REF = Symbol('FIELD_REF');
639
- const ruleConstraintTypes$1 = [
640
- 'Array',
641
- 'Boolean',
642
- 'Date',
643
- 'Number',
644
- 'Object',
645
- 'String',
646
- ];
647
- // Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types`
648
- // setup. Classes are a bit weird in the `@sanity/types` package because classes
649
- // create an actual javascript class while simultaneously creating a type
650
- // definition.
651
- //
652
- // This implicitly creates two types:
653
- // 1. the instance type — `Rule` and
654
- // 2. the static/class type - `RuleClass`
655
- //
656
- // The `RuleClass` type contains the static methods and the `Rule` instance
657
- // contains the instance methods.
658
- //
659
- // This package exports the RuleClass as a value without implicitly exporting
660
- // an instance definition. This should help reminder downstream users to import
661
- // from the `@sanity/types` package.
662
- const Rule = class Rule {
663
- static FIELD_REF = FIELD_REF;
664
- static array = (def) => new Rule(def).type('Array');
665
- static object = (def) => new Rule(def).type('Object');
666
- static string = (def) => new Rule(def).type('String');
667
- static number = (def) => new Rule(def).type('Number');
668
- static boolean = (def) => new Rule(def).type('Boolean');
669
- static dateTime = (def) => new Rule(def).type('Date');
670
- static valueOfField = (path) => ({
671
- type: FIELD_REF,
672
- path,
673
- });
674
- _type = undefined;
675
- _level = undefined;
676
- _required = undefined;
677
- _typeDef = undefined;
678
- _message = undefined;
679
- _rules = [];
680
- _fieldRules = undefined;
681
- constructor(typeDef) {
682
- this._typeDef = typeDef;
683
- this.reset();
684
- }
685
- _mergeRequired(next) {
686
- if (this._required === 'required' || next._required === 'required')
687
- return 'required';
688
- if (this._required === 'optional' || next._required === 'optional')
689
- return 'optional';
690
- return undefined;
691
- }
692
- // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class
693
- valueOfField = Rule.valueOfField.bind(Rule);
694
- error(message) {
695
- const rule = this.clone();
696
- rule._level = 'error';
697
- rule._message = message || undefined;
698
- return rule;
699
- }
700
- warning(message) {
701
- const rule = this.clone();
702
- rule._level = 'warning';
703
- rule._message = message || undefined;
704
- return rule;
705
- }
706
- info(message) {
707
- const rule = this.clone();
708
- rule._level = 'info';
709
- rule._message = message || undefined;
710
- return rule;
711
- }
712
- reset() {
713
- this._type = this._type || undefined;
714
- this._rules = (this._rules || []).filter((rule) => rule.flag === 'type');
715
- this._message = undefined;
716
- this._required = undefined;
717
- this._level = 'error';
718
- this._fieldRules = undefined;
719
- return this;
720
- }
721
- isRequired() {
722
- return this._required === 'required';
723
- }
724
- clone() {
725
- const rule = new Rule();
726
- rule._type = this._type;
727
- rule._message = this._message;
728
- rule._required = this._required;
729
- rule._rules = cloneDeep(this._rules);
730
- rule._level = this._level;
731
- rule._fieldRules = this._fieldRules;
732
- rule._typeDef = this._typeDef;
733
- return rule;
734
- }
735
- cloneWithRules(rules) {
736
- const rule = this.clone();
737
- const newRules = new Set();
738
- rules.forEach((curr) => {
739
- if (curr.flag === 'type') {
740
- rule._type = curr.constraint;
741
- }
742
- newRules.add(curr.flag);
743
- });
744
- rule._rules = rule._rules
745
- .filter((curr) => {
746
- const disallowDuplicate = ['type', 'uri', 'email'].includes(curr.flag);
747
- const isDuplicate = newRules.has(curr.flag);
748
- return !(disallowDuplicate && isDuplicate);
749
- })
750
- .concat(rules);
751
- return rule;
752
- }
753
- merge(rule) {
754
- if (this._type && rule._type && this._type !== rule._type) {
755
- throw new Error('merge() failed: conflicting types');
756
- }
757
- const newRule = this.cloneWithRules(rule._rules);
758
- newRule._type = this._type || rule._type;
759
- newRule._message = this._message || rule._message;
760
- newRule._required = this._mergeRequired(rule);
761
- newRule._level = this._level === 'error' ? rule._level : this._level;
762
- return newRule;
763
- }
764
- // Validation flag setters
765
- type(targetType) {
766
- const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}`;
767
- if (!ruleConstraintTypes$1.includes(type)) {
768
- throw new Error(`Unknown type "${targetType}"`);
769
- }
770
- const rule = this.cloneWithRules([{ flag: 'type', constraint: type }]);
771
- rule._type = type;
772
- return rule;
773
- }
774
- all(children) {
775
- return this.cloneWithRules([{ flag: 'all', constraint: children }]);
776
- }
777
- either(children) {
778
- return this.cloneWithRules([{ flag: 'either', constraint: children }]);
779
- }
780
- // Shared rules
781
- optional() {
782
- const rule = this.cloneWithRules([{ flag: 'presence', constraint: 'optional' }]);
783
- rule._required = 'optional';
784
- return rule;
785
- }
786
- required() {
787
- const rule = this.cloneWithRules([{ flag: 'presence', constraint: 'required' }]);
788
- rule._required = 'required';
789
- return rule;
790
- }
791
- custom(fn) {
792
- return this.cloneWithRules([{ flag: 'custom', constraint: fn }]);
793
- }
794
- /**
795
- * @deprecated use `Rule.custom` instead
796
- */
797
- block(fn) {
798
- return this.cloneWithRules([{ flag: 'custom', constraint: fn }]);
799
- }
800
- min(len) {
801
- return this.cloneWithRules([{ flag: 'min', constraint: len }]);
802
- }
803
- max(len) {
804
- return this.cloneWithRules([{ flag: 'max', constraint: len }]);
805
- }
806
- length(len) {
807
- return this.cloneWithRules([{ flag: 'length', constraint: len }]);
808
- }
809
- valid(value) {
810
- const values = Array.isArray(value) ? value : [value];
811
- return this.cloneWithRules([{ flag: 'valid', constraint: values }]);
812
- }
813
- // Numbers only
814
- integer() {
815
- return this.cloneWithRules([{ flag: 'integer' }]);
816
- }
817
- precision(limit) {
818
- return this.cloneWithRules([{ flag: 'precision', constraint: limit }]);
819
- }
820
- positive() {
821
- return this.cloneWithRules([{ flag: 'min', constraint: 0 }]);
822
- }
823
- negative() {
824
- return this.cloneWithRules([{ flag: 'lessThan', constraint: 0 }]);
825
- }
826
- greaterThan(num) {
827
- return this.cloneWithRules([{ flag: 'greaterThan', constraint: num }]);
828
- }
829
- lessThan(num) {
830
- return this.cloneWithRules([{ flag: 'lessThan', constraint: num }]);
831
- }
832
- // String only
833
- uppercase() {
834
- return this.cloneWithRules([{ flag: 'stringCasing', constraint: 'uppercase' }]);
835
- }
836
- lowercase() {
837
- return this.cloneWithRules([{ flag: 'stringCasing', constraint: 'lowercase' }]);
838
- }
839
- regex(pattern, a, b) {
840
- const name = typeof a === 'string' ? a : a?.name ?? b?.name;
841
- const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert;
842
- const constraint = {
843
- pattern,
844
- name,
845
- invert: invert || false,
846
- };
847
- return this.cloneWithRules([{ flag: 'regex', constraint }]);
848
- }
849
- email() {
850
- return this.cloneWithRules([{ flag: 'email' }]);
851
- }
852
- uri(opts) {
853
- const optsScheme = opts?.scheme || ['http', 'https'];
854
- const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme];
855
- if (!schemes.length) {
856
- throw new Error('scheme must have at least 1 scheme specified');
857
- }
858
- const constraint = {
859
- options: {
860
- scheme: schemes.map((scheme) => {
861
- if (!(scheme instanceof RegExp) && typeof scheme !== 'string') {
862
- throw new Error('scheme must be a RegExp or a String');
863
- }
864
- return typeof scheme === 'string' ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme;
865
- }),
866
- allowRelative: opts?.allowRelative || false,
867
- relativeOnly: opts?.relativeOnly || false,
868
- allowCredentials: opts?.allowCredentials || false,
869
- },
870
- };
871
- return this.cloneWithRules([{ flag: 'uri', constraint }]);
872
- }
873
- // Array only
874
- unique() {
875
- return this.cloneWithRules([{ flag: 'unique' }]);
876
- }
877
- // Objects only
878
- reference() {
879
- return this.cloneWithRules([{ flag: 'reference' }]);
880
- }
881
- fields(rules) {
882
- if (this._type !== 'Object') {
883
- throw new Error('fields() can only be called on an object type');
884
- }
885
- const rule = this.cloneWithRules([]);
886
- rule._fieldRules = rules;
887
- return rule;
888
- }
889
- assetRequired() {
890
- const base = getBaseType(this._typeDef);
891
- let assetType;
892
- if (base && ['image', 'file'].includes(base.name)) {
893
- assetType = base.name === 'image' ? 'Image' : 'File';
894
- }
895
- else {
896
- assetType = 'Asset';
897
- }
898
- return this.cloneWithRules([{ flag: 'assetRequired', constraint: { assetType } }]);
899
- }
900
- async validate(value, context) {
901
- if (!context) {
902
- throw new Error('missing context');
903
- }
904
- const valueIsEmpty = value === null || value === undefined;
905
- // Short-circuit on optional, empty fields
906
- if (valueIsEmpty && this._required === 'optional') {
907
- return EMPTY_ARRAY;
908
- }
909
- const rules =
910
- // Run only the _custom_ functions if the rule is not set to required or optional
911
- this._required === undefined && valueIsEmpty
912
- ? this._rules.filter((curr) => curr.flag === 'custom')
913
- : this._rules;
914
- const validators = (this._type && typeValidators[this._type]) || genericValidators;
915
- const results = await Promise.all(rules.map(async (curr) => {
916
- if (curr.flag === undefined) {
917
- throw new Error('Invalid rule, did not contain "flag"-property');
918
- }
919
- const validator = validators[curr.flag];
920
- if (!validator) {
921
- const forType = this._type ? `type "${this._type}"` : 'rule without declared type';
922
- throw new Error(`Validator for flag "${curr.flag}" not found for ${forType}`);
923
- }
924
- let specConstraint = 'constraint' in curr ? curr.constraint : null;
925
- if (isFieldRef(specConstraint)) {
926
- specConstraint = get(context.parent, specConstraint.path);
927
- }
928
- let result;
929
- try {
930
- result = await validator(specConstraint, value, this._message, context);
931
- }
932
- catch (err) {
933
- const errorFromException = new ValidationError(`${pathToString(context.path)}: Exception occurred while validating value: ${err.message}`);
934
- return convertToValidationMarker(errorFromException, 'error', context);
935
- }
936
- return convertToValidationMarker(result, this._level, context);
937
- }));
938
- return results.flat();
939
- }
932
+ const cancelIdleCallbackShim = function cancelIdleCallbackShim2(handle) {
933
+ return window.clearTimeout(handle);
940
934
  };
941
-
942
- // import getClient from '../getClient'
943
- const memoizedWarnOnArraySlug = memoize(warnOnArraySlug);
944
- function getDocumentIds(id) {
945
- const isDraft = id.indexOf('drafts.') === 0;
946
- return {
947
- published: isDraft ? id.slice('drafts.'.length) : id,
948
- draft: isDraft ? id : `drafts.${id}`,
949
- };
950
- }
951
- function serializePath(path) {
952
- return path.reduce((target, part, i) => {
953
- const isIndex = typeof part === 'number';
954
- const isKey = isKeyedObject(part);
955
- const separator = i === 0 ? '' : '.';
956
- const add = isIndex || isKey ? '[]' : `${separator}${part}`;
957
- return `${target}${add}`;
958
- }, '');
959
- }
960
- const defaultIsUnique = (slug, context) => {
961
- const { getClient, document, path, type } = context;
962
- const schemaOptions = type?.options;
963
- if (!document) {
964
- throw new Error(`\`document\` was not provided in validation context.`);
965
- }
966
- if (!path) {
967
- throw new Error(`\`path\` was not provided in validation context.`);
968
- }
969
- const disableArrayWarning = schemaOptions?.disableArrayWarning || false;
970
- const { published, draft } = getDocumentIds(document._id);
971
- const docType = document._type;
972
- const atPath = serializePath(path.concat('current'));
973
- if (!disableArrayWarning && atPath.includes('[]')) {
974
- memoizedWarnOnArraySlug(serializePath(path));
975
- }
976
- const constraints = [
977
- '_type == $docType',
978
- `!(_id in [$draft, $published])`,
979
- `${atPath} == $slug`,
980
- ].join(' && ');
981
- return getClient({ apiVersion: '2022-09-09' }).fetch(`!defined(*[${constraints}][0]._id)`, {
982
- docType,
983
- draft,
984
- published,
985
- slug,
986
- }, { tag: 'validation.slug-is-unique' });
987
- };
988
- function warnOnArraySlug(serializedPath) {
989
- /* eslint-disable no-console */
990
- console.warn([
991
- `Slug field at path ${serializedPath} is within an array and cannot be automatically checked for uniqueness`,
992
- `If you need to check for uniqueness, provide your own "isUnique" method`,
993
- `To disable this message, set \`disableArrayWarning: true\` on the slug \`options\` field`,
994
- ].join('\n'));
995
- /* eslint-enable no-console */
996
- }
997
- /**
998
- * Validates slugs values by querying for uniqueness from the client.
999
- *
1000
- * This is a custom rule implementation (e.g. `Rule.custom(slugValidator)`)
1001
- * that's populated in `inferFromSchemaType` when the type name is `slug`
1002
- */
1003
- const slugValidator = async (value, context) => {
1004
- if (!value) {
1005
- return true;
1006
- }
1007
- if (typeof value !== 'object') {
1008
- return 'Slug must be an object';
1009
- }
1010
- const slugValue = value.current;
1011
- if (!slugValue) {
1012
- return 'Slug must have a value';
1013
- }
1014
- const options = context?.type?.options;
1015
- const isUnique = options?.isUnique || defaultIsUnique;
1016
- const wasUnique = await isUnique(slugValue, { ...context, defaultIsUnique });
1017
- if (wasUnique) {
1018
- return true;
1019
- }
1020
- return 'Slug is already in use';
935
+ const win = typeof window === "undefined" ? void 0 : window;
936
+ const requestIdleCallback = (win == null ? void 0 : win.requestIdleCallback) || requestIdleCallbackShim;
937
+ const cancelIdleCallback = (win == null ? void 0 : win.cancelIdleCallback) || cancelIdleCallbackShim;
938
+ const memoizedWarnOnArraySlug = lodash.memoize(warnOnArraySlug);
939
+ function getDocumentIds(id) {
940
+ const isDraft = id.indexOf("drafts.") === 0;
941
+ return {
942
+ published: isDraft ? id.slice("drafts.".length) : id,
943
+ draft: isDraft ? id : "drafts.".concat(id)
944
+ };
945
+ }
946
+ function serializePath(path) {
947
+ return path.reduce((target, part, i) => {
948
+ const isIndex = typeof part === "number";
949
+ const isKey = types.isKeyedObject(part);
950
+ const separator = i === 0 ? "" : ".";
951
+ const add = isIndex || isKey ? "[]" : "".concat(separator).concat(part);
952
+ return "".concat(target).concat(add);
953
+ }, "");
954
+ }
955
+ const defaultIsUnique = (slug, context) => {
956
+ const {
957
+ getClient,
958
+ document,
959
+ path,
960
+ type
961
+ } = context;
962
+ const schemaOptions = type == null ? void 0 : type.options;
963
+ if (!document) {
964
+ throw new Error("`document` was not provided in validation context.");
965
+ }
966
+ if (!path) {
967
+ throw new Error("`path` was not provided in validation context.");
968
+ }
969
+ const disableArrayWarning = (schemaOptions == null ? void 0 : schemaOptions.disableArrayWarning) || false;
970
+ const {
971
+ published,
972
+ draft
973
+ } = getDocumentIds(document._id);
974
+ const docType = document._type;
975
+ const atPath = serializePath(path.concat("current"));
976
+ if (!disableArrayWarning && atPath.includes("[]")) {
977
+ memoizedWarnOnArraySlug(serializePath(path));
978
+ }
979
+ const constraints = ["_type == $docType", "!(_id in [$draft, $published])", "".concat(atPath, " == $slug")].join(" && ");
980
+ return getClient({
981
+ apiVersion: "2022-09-09"
982
+ }).fetch("!defined(*[".concat(constraints, "][0]._id)"), {
983
+ docType,
984
+ draft,
985
+ published,
986
+ slug
987
+ }, {
988
+ tag: "validation.slug-is-unique"
989
+ });
1021
990
  };
1022
-
1023
- const ruleConstraintTypes = {
1024
- array: true,
1025
- boolean: true,
1026
- date: true,
1027
- number: true,
1028
- object: true,
1029
- string: true,
1030
- };
1031
- const isRuleConstraint = (typeString) => typeString in ruleConstraintTypes;
1032
- function getTypeChain(type, visited) {
1033
- if (!type)
1034
- return [];
1035
- if (visited.has(type))
1036
- return [];
1037
- visited.add(type);
1038
- const next = type.type ? getTypeChain(type.type, visited) : [];
1039
- return [...next, type];
1040
- }
1041
- function baseRuleReducer(inputRule, type) {
1042
- let baseRule = inputRule;
1043
- if (isRuleConstraint(type.jsonType)) {
1044
- baseRule = baseRule.type(type.jsonType);
1045
- }
1046
- const typeOptionsList =
1047
- // if type.options is truthy
1048
- type?.options &&
1049
- // and type.options is an object (non-null from the previous)
1050
- typeof type.options === 'object' &&
1051
- // and if `list` is in options
1052
- 'list' in type.options &&
1053
- // then finally access the list
1054
- type.options.list;
1055
- if (Array.isArray(typeOptionsList)) {
1056
- baseRule = baseRule.valid(typeOptionsList.map((option) => extractValueFromListOption(option, type)));
1057
- }
1058
- if (type.name === 'datetime')
1059
- return baseRule.type('Date');
1060
- if (type.name === 'date')
1061
- return baseRule.type('Date');
1062
- if (type.name === 'url')
1063
- return baseRule.uri();
1064
- if (type.name === 'slug')
1065
- return baseRule.custom(slugValidator);
1066
- if (type.name === 'reference')
1067
- return baseRule.reference();
1068
- if (type.name === 'email')
1069
- return baseRule.email();
1070
- return baseRule;
1071
- }
1072
- function hasValueField(typeDef) {
1073
- if (!typeDef)
1074
- return false;
1075
- if (!('fields' in typeDef) && typeDef.type)
1076
- return hasValueField(typeDef.type);
1077
- if (!('fields' in typeDef))
1078
- return false;
1079
- if (!Array.isArray(typeDef.fields))
1080
- return false;
1081
- return typeDef.fields.some((field) => field.name === 'value');
1082
- }
1083
- function extractValueFromListOption(option, typeDef) {
1084
- // If you define a `list` option with object items, where the item has a `value` field,
1085
- // we don't want to treat that as the value but rather the surrounding object
1086
- // This differs from the case where you have a title/value pair setup for a string/number, for instance
1087
- if (typeDef.jsonType === 'object' && hasValueField(typeDef))
1088
- return option;
1089
- return option.value === undefined
1090
- ? option
1091
- : option.value;
1092
- }
1093
- /**
1094
- * Takes in `SchemaValidationValue` and returns an array of `Rule` instances.
1095
- */
1096
- function normalizeValidationRules(typeDef) {
1097
- if (!typeDef) {
1098
- return [];
1099
- }
1100
- const validation = typeDef.validation;
1101
- if (Array.isArray(validation)) {
1102
- return validation.flatMap((i) => normalizeValidationRules({
1103
- ...typeDef,
1104
- validation: i,
1105
- }));
1106
- }
1107
- if (validation instanceof Rule) {
1108
- return [validation];
1109
- }
1110
- const baseRule =
1111
- // using an object + Object.values to de-dupe the type chain by type name
1112
- Object.values(getTypeChain(typeDef, new Set()).reduce((acc, type) => {
1113
- acc[type.name] = type;
1114
- return acc;
1115
- }, {})).reduce(baseRuleReducer, new Rule(typeDef));
1116
- if (!validation) {
1117
- return [baseRule];
1118
- }
1119
- return normalizeValidationRules({
1120
- ...typeDef,
1121
- validation: validation(baseRule),
1122
- });
991
+ function warnOnArraySlug(serializedPath) {
992
+ console.warn(["Slug field at path ".concat(serializedPath, " is within an array and cannot be automatically checked for uniqueness"), "If you need to check for uniqueness, provide your own \"isUnique\" method", "To disable this message, set `disableArrayWarning: true` on the slug `options` field"].join("\n"));
1123
993
  }
1124
-
1125
- const isRecord = (maybeRecord) => typeof maybeRecord === 'object' && maybeRecord !== null && !Array.isArray(maybeRecord);
1126
- const isNonNullable = (value) => value !== null && value !== undefined;
1127
- /**
1128
- * @internal
1129
- */
1130
- function resolveTypeForArrayItem(item, candidates) {
1131
- // if there is only one type available, assume that it's the correct one
1132
- if (candidates.length === 1)
1133
- return candidates[0];
1134
- const itemType = isTypedObject(item) && item._type;
1135
- const primitive = item === undefined || item === null || (!itemType && typeString(item).toLowerCase());
1136
- if (primitive && primitive !== 'object') {
1137
- return candidates.find((candidate) => candidate.jsonType === primitive);
1138
- }
1139
- return (candidates.find((candidate) => candidate.type?.name === itemType) ||
1140
- candidates.find((candidate) => candidate.name === itemType) ||
1141
- candidates.find((candidate) => candidate.name === 'object' && primitive === 'object'));
1142
- }
1143
- async function validateDocument(getClient, doc, schema, context) {
1144
- const documentType = schema.get(doc._type);
1145
- if (!documentType) {
1146
- console.warn('Schema type for object type "%s" not found, skipping validation', doc._type);
1147
- return [];
1148
- }
1149
- const client = getClient({ apiVersion: '2021-06-07' });
1150
- const validationOptions = {
1151
- client,
1152
- getClient,
1153
- schema,
1154
- parent: undefined,
1155
- value: doc,
1156
- path: [],
1157
- document: doc,
1158
- type: documentType,
1159
- getDocumentExists: context?.getDocumentExists,
1160
- };
1161
- // <TEMPORARY UGLY HACK TO PRINT DEPRECATION WARNINGS ON USE>
1162
- /* eslint-disable no-proto */
1163
- const wrappedClient = client;
1164
- validationOptions.client = [
1165
- ...Object.keys(client),
1166
- ...Object.keys(wrappedClient.__proto__),
1167
- ].reduce((acc, key) => {
1168
- const original = Object.hasOwnProperty.call(client, key)
1169
- ? wrappedClient[key]
1170
- : wrappedClient.__proto__[key];
1171
- return Object.defineProperty(acc, key, {
1172
- get() {
1173
- console.warn('`configContext.client` is deprecated and will be removed in the next release! Use `context.getClient({apiVersion: "2021-06-07"})` instead');
1174
- return original;
1175
- },
1176
- });
1177
- }, {});
1178
- /* eslint-enable no-proto */
1179
- // </TEMPORARY UGLY HACK TO PRINT DEPRECATION WARNINGS ON USE>
1180
- try {
1181
- return await validateItem(validationOptions);
1182
- }
1183
- catch (err) {
1184
- console.error(err);
1185
- return [
1186
- {
1187
- level: 'error',
1188
- path: [],
1189
- item: new ValidationError(err?.message),
1190
- },
1191
- ];
1192
- }
1193
- }
1194
- async function validateItem({ value, type, path = [], parent, ...restOfContext }) {
1195
- const rules = normalizeValidationRules(type);
1196
- // run validation for the current value
1197
- const selfChecks = rules.map((rule) => rule.validate(value, {
1198
- ...restOfContext,
1199
- parent,
1200
- path,
1201
- type,
1202
- }));
1203
- // run validation for nested values (conditionally)
1204
- let nestedChecks = [];
1205
- const selfIsRequired = rules.some((rule) => rule.isRequired());
1206
- const shouldRunNestedObjectValidation =
1207
- // run nested validation for objects
1208
- type?.jsonType === 'object' &&
1209
- // if the value is truthy
1210
- (!!value || // or
1211
- // (the value is null or undefined) and the top-level value is required
1212
- ((value === null || value === undefined) && selfIsRequired));
1213
- if (shouldRunNestedObjectValidation) {
1214
- const fieldTypes = type.fields.reduce((acc, field) => {
1215
- acc[field.name] = field.type;
1216
- return acc;
1217
- }, {});
1218
- // Validation for rules set at the object level with `Rule.fields({/* ... */})`
1219
- nestedChecks = nestedChecks.concat(rules
1220
- .map((rule) => rule._fieldRules)
1221
- .filter(isNonNullable)
1222
- .flatMap((fieldResults) => Object.entries(fieldResults))
1223
- .flatMap(([name, validation]) => {
1224
- const fieldType = fieldTypes[name];
1225
- return normalizeValidationRules({ ...fieldType, validation }).map((subRule) => {
1226
- const nestedValue = isRecord(value) ? value[name] : undefined;
1227
- return subRule.validate(nestedValue, {
1228
- ...restOfContext,
1229
- parent: value,
1230
- path: path.concat(name),
1231
- type: fieldType,
1232
- });
1233
- });
1234
- }));
1235
- // Validation from each field's schema `validation: Rule => {/* ... */}` function
1236
- nestedChecks = nestedChecks.concat(type.fields.map((field) => validateItem({
1237
- ...restOfContext,
1238
- parent: value,
1239
- value: isRecord(value) ? value[field.name] : undefined,
1240
- path: path.concat(field.name),
1241
- type: field.type,
1242
- })));
1243
- }
1244
- // note: unlike objects, arrays should not run nested validation for undefined
1245
- // values because we won't have a valid path to put a marker (i.e. missing the
1246
- // key or index in the path) and the downstream form builder won't have a
1247
- // valid target component
1248
- const shouldRunNestedValidationForArrays = type?.jsonType === 'array' && Array.isArray(value);
1249
- if (shouldRunNestedValidationForArrays) {
1250
- nestedChecks = nestedChecks.concat(value.map((item) => validateItem({
1251
- ...restOfContext,
1252
- parent: value,
1253
- value: item,
1254
- path: path.concat(isKeyedObject(item) ? { _key: item._key } : value.indexOf(item)),
1255
- type: resolveTypeForArrayItem(item, type.of),
1256
- })));
1257
- }
1258
- // markDefs also do no run nested validation if the parent object is undefined
1259
- // for a similar reason to arrays
1260
- const shouldRunNestedValidationForMarkDefs = isBlock(value) && value.markDefs.length && isBlockSchemaType(type);
1261
- if (shouldRunNestedValidationForMarkDefs) {
1262
- const [spanChildrenField] = type.fields;
1263
- const spanType = spanChildrenField.type.of.find(isSpanSchemaType);
1264
- const annotations = (spanType?.annotations || []).reduce((map, annotationType) => {
1265
- map.set(annotationType.name, annotationType);
1266
- return map;
1267
- }, new Map());
1268
- nestedChecks = nestedChecks.concat(value.markDefs.map((markDef) => validateItem({
1269
- ...restOfContext,
1270
- parent: value,
1271
- value: markDef,
1272
- path: path.concat(['markDefs', { _key: markDef._key }]),
1273
- type: annotations.get(markDef._type),
1274
- })));
1275
- }
1276
- const results = (await Promise.all([...selfChecks, ...nestedChecks])).flat();
1277
- // run `uniqBy` if `_fieldRules` are present because they can
1278
- // cause repeat markers
1279
- if (rules.some((rule) => rule._fieldRules)) {
1280
- return uniqBy(results, (rule) => JSON.stringify(rule));
1281
- }
1282
- return results;
994
+ const slugValidator = async (value, context) => {
995
+ var _a;
996
+ if (!value) {
997
+ return true;
998
+ }
999
+ if (typeof value !== "object") {
1000
+ return "Slug must be an object";
1001
+ }
1002
+ const slugValue = value.current;
1003
+ if (!slugValue) {
1004
+ return "Slug must have a value";
1005
+ }
1006
+ const options = (_a = context == null ? void 0 : context.type) == null ? void 0 : _a.options;
1007
+ const isUnique = (options == null ? void 0 : options.isUnique) || defaultIsUnique;
1008
+ const slugContext = _objectSpread(_objectSpread({}, context), {}, {
1009
+ parent: context.parent,
1010
+ type: context.type,
1011
+ defaultIsUnique
1012
+ });
1013
+ const wasUnique = await isUnique(slugValue, slugContext);
1014
+ if (wasUnique) {
1015
+ return true;
1016
+ }
1017
+ return "Slug is already in use";
1018
+ };
1019
+ const ruleConstraintTypes = {
1020
+ array: true,
1021
+ boolean: true,
1022
+ date: true,
1023
+ number: true,
1024
+ object: true,
1025
+ string: true
1026
+ };
1027
+ const isRuleConstraint = typeString => typeString in ruleConstraintTypes;
1028
+ function getTypeChain(type, visited) {
1029
+ if (!type) return [];
1030
+ if (visited.has(type)) return [];
1031
+ visited.add(type);
1032
+ const next = type.type ? getTypeChain(type.type, visited) : [];
1033
+ return [...next, type];
1283
1034
  }
1284
-
1285
- function traverse(typeDef, visited) {
1286
- if (visited.has(typeDef)) {
1287
- return;
1288
- }
1289
- visited.add(typeDef);
1290
- typeDef.validation = normalizeValidationRules(typeDef);
1291
- if ('fields' in typeDef) {
1292
- for (const field of typeDef.fields) {
1293
- traverse(field.type, visited);
1294
- }
1295
- }
1296
- if ('of' in typeDef) {
1297
- for (const candidate of typeDef.of) {
1298
- traverse(candidate, visited);
1299
- }
1300
- }
1301
- // eslint-disable-next-line no-warning-comments
1302
- // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet
1303
- if (typeDef.annotations) {
1304
- // eslint-disable-next-line no-warning-comments
1305
- // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet
1306
- for (const annotation of typeDef.annotations) {
1307
- traverse(annotation, visited);
1308
- }
1309
- }
1310
- }
1311
- function inferFromSchemaType(typeDef) {
1312
- traverse(typeDef, new Set());
1313
- return typeDef;
1035
+ function baseRuleReducer(inputRule, type) {
1036
+ let baseRule = inputRule;
1037
+ if (isRuleConstraint(type.jsonType)) {
1038
+ baseRule = baseRule.type(type.jsonType);
1039
+ }
1040
+ const typeOptionsList = (type == null ? void 0 : type.options) && typeof type.options === "object" && "list" in type.options && type.options.list;
1041
+ if (Array.isArray(typeOptionsList)) {
1042
+ baseRule = baseRule.valid(typeOptionsList.map(option => extractValueFromListOption(option, type)));
1043
+ }
1044
+ if (type.name === "datetime") return baseRule.type("Date");
1045
+ if (type.name === "date") return baseRule.type("Date");
1046
+ if (type.name === "url") return baseRule.uri();
1047
+ if (type.name === "slug") return baseRule.custom(slugValidator);
1048
+ if (type.name === "reference") return baseRule.reference();
1049
+ if (type.name === "email") return baseRule.email();
1050
+ return baseRule;
1314
1051
  }
1315
-
1316
- // Note: Mutates schema. Refactor when @sanity/schema supports middlewares
1317
- function inferFromSchema(schema) {
1318
- const typeNames = schema.getTypeNames();
1319
- typeNames.forEach((typeName) => {
1320
- const schemaType = schema.get(typeName);
1321
- if (schemaType) {
1322
- inferFromSchemaType(schemaType);
1323
- }
1324
- });
1325
- return schema;
1052
+ function hasValueField(typeDef) {
1053
+ if (!typeDef) return false;
1054
+ if (!("fields" in typeDef) && typeDef.type) return hasValueField(typeDef.type);
1055
+ if (!("fields" in typeDef)) return false;
1056
+ if (!Array.isArray(typeDef.fields)) return false;
1057
+ return typeDef.fields.some(field => field.name === "value");
1326
1058
  }
1327
-
1328
- var index = { Rule: Rule, validateDocument, inferFromSchema, inferFromSchemaType };
1329
-
1330
- export { Rule, index as default, inferFromSchema, inferFromSchemaType, validateDocument };
1059
+ function extractValueFromListOption(option, typeDef) {
1060
+ if (typeDef.jsonType === "object" && hasValueField(typeDef)) return option;
1061
+ return option.value === void 0 ? option : option.value;
1062
+ }
1063
+ function normalizeValidationRules(typeDef) {
1064
+ if (!typeDef) {
1065
+ return [];
1066
+ }
1067
+ const validation = typeDef.validation;
1068
+ if (Array.isArray(validation)) {
1069
+ return validation.flatMap(i => normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
1070
+ validation: i
1071
+ })));
1072
+ }
1073
+ if (validation instanceof Rule) {
1074
+ return [validation];
1075
+ }
1076
+ const baseRule = Object.values(getTypeChain(typeDef, /* @__PURE__ */new Set()).reduce((acc, type) => {
1077
+ acc[type.name] = type;
1078
+ return acc;
1079
+ }, {})).reduce(baseRuleReducer, new Rule(typeDef));
1080
+ if (!validation) {
1081
+ return [baseRule];
1082
+ }
1083
+ return normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
1084
+ validation: validation(baseRule)
1085
+ }));
1086
+ }
1087
+ const isRecord = maybeRecord => typeof maybeRecord === "object" && maybeRecord !== null && !Array.isArray(maybeRecord);
1088
+ const isNonNullable = value => value !== null && value !== void 0;
1089
+ function resolveTypeForArrayItem(item, candidates) {
1090
+ if (candidates.length === 1) return candidates[0];
1091
+ const itemType = types.isTypedObject(item) && item._type;
1092
+ const primitive = item === void 0 || item === null || !itemType && typeString(item).toLowerCase();
1093
+ if (primitive && primitive !== "object") {
1094
+ return candidates.find(candidate => candidate.jsonType === primitive);
1095
+ }
1096
+ return candidates.find(candidate => {
1097
+ var _a;
1098
+ return ((_a = candidate.type) == null ? void 0 : _a.name) === itemType;
1099
+ }) || candidates.find(candidate => candidate.name === itemType) || candidates.find(candidate => candidate.name === "object" && primitive === "object");
1100
+ }
1101
+ const EMPTY_MARKERS = [];
1102
+ async function validateDocument(getClient, doc, schema, context) {
1103
+ return validateDocumentObservable(getClient, doc, schema, context).toPromise();
1104
+ }
1105
+ function validateDocumentObservable(getClient, doc, schema, context) {
1106
+ const documentType = schema.get(doc._type);
1107
+ if (!documentType) {
1108
+ console.warn('Schema type for object type "%s" not found, skipping validation', doc._type);
1109
+ return rxjs.of(EMPTY_MARKERS);
1110
+ }
1111
+ const client = getClient({
1112
+ apiVersion: "2021-06-07"
1113
+ });
1114
+ const validationOptions = {
1115
+ client,
1116
+ getClient,
1117
+ schema,
1118
+ parent: void 0,
1119
+ value: doc,
1120
+ path: [],
1121
+ document: doc,
1122
+ type: documentType,
1123
+ getDocumentExists: context == null ? void 0 : context.getDocumentExists
1124
+ };
1125
+ const wrappedClient = client;
1126
+ validationOptions.client = [...Object.keys(client), ...Object.keys(wrappedClient.__proto__)].reduce((acc, key) => {
1127
+ const original = Object.hasOwnProperty.call(client, key) ? wrappedClient[key] : wrappedClient.__proto__[key];
1128
+ return Object.defineProperty(acc, key, {
1129
+ get() {
1130
+ console.warn('`configContext.client` is deprecated and will be removed in the next release! Use `context.getClient({apiVersion: "2021-06-07"})` instead');
1131
+ return original;
1132
+ }
1133
+ });
1134
+ }, {});
1135
+ return validateItemObservable(validationOptions).pipe(operators.catchError(err => {
1136
+ console.error(err);
1137
+ return rxjs.of([{
1138
+ type: "validation",
1139
+ level: "error",
1140
+ path: [],
1141
+ item: new ValidationError(err == null ? void 0 : err.message)
1142
+ }]);
1143
+ }));
1144
+ }
1145
+ function validateItemObservable(_ref) {
1146
+ let {
1147
+ value,
1148
+ type,
1149
+ path = [],
1150
+ parent
1151
+ } = _ref,
1152
+ restOfContext = _objectWithoutProperties(_ref, _excluded);
1153
+ const rules = normalizeValidationRules(type);
1154
+ const selfChecks = rules.map(rule => rxjs.defer(() => rule.validate(value, _objectSpread(_objectSpread({}, restOfContext), {}, {
1155
+ parent,
1156
+ path,
1157
+ type
1158
+ }))));
1159
+ let nestedChecks = [];
1160
+ const selfIsRequired = rules.some(rule => rule.isRequired());
1161
+ const shouldRunNestedObjectValidation = (type == null ? void 0 : type.jsonType) === "object" && (!!value || (value === null || value === void 0) && selfIsRequired);
1162
+ if (shouldRunNestedObjectValidation) {
1163
+ const fieldTypes = type.fields.reduce((acc, field) => {
1164
+ acc[field.name] = field.type;
1165
+ return acc;
1166
+ }, {});
1167
+ nestedChecks = nestedChecks.concat(rules.map(rule => rule._fieldRules).filter(isNonNullable).flatMap(fieldResults => Object.entries(fieldResults)).flatMap(_ref2 => {
1168
+ let [name, validation] = _ref2;
1169
+ const fieldType = fieldTypes[name];
1170
+ return normalizeValidationRules(_objectSpread(_objectSpread({}, fieldType), {}, {
1171
+ validation
1172
+ })).map(subRule => {
1173
+ const nestedValue = isRecord(value) ? value[name] : void 0;
1174
+ return rxjs.defer(() => subRule.validate(nestedValue, _objectSpread(_objectSpread({}, restOfContext), {}, {
1175
+ parent: value,
1176
+ path: path.concat(name),
1177
+ type: fieldType
1178
+ })));
1179
+ });
1180
+ }));
1181
+ nestedChecks = nestedChecks.concat(type.fields.map(field => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1182
+ parent: value,
1183
+ value: isRecord(value) ? value[field.name] : void 0,
1184
+ path: path.concat(field.name),
1185
+ type: field.type
1186
+ }))));
1187
+ }
1188
+ const shouldRunNestedValidationForArrays = (type == null ? void 0 : type.jsonType) === "array" && Array.isArray(value);
1189
+ if (shouldRunNestedValidationForArrays) {
1190
+ nestedChecks = nestedChecks.concat(value.map((item, index) => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1191
+ parent: value,
1192
+ value: item,
1193
+ path: path.concat(types.isKeyedObject(item) ? {
1194
+ _key: item._key
1195
+ } : index),
1196
+ type: resolveTypeForArrayItem(item, type.of)
1197
+ }))));
1198
+ }
1199
+ const shouldRunNestedValidationForMarkDefs = types.isBlock(value) && value.markDefs.length && types.isBlockSchemaType(type);
1200
+ if (shouldRunNestedValidationForMarkDefs) {
1201
+ const [spanChildrenField] = type.fields;
1202
+ const spanType = spanChildrenField.type.of.find(types.isSpanSchemaType);
1203
+ const annotations = ((spanType == null ? void 0 : spanType.annotations) || []).reduce((acc, annotationType) => {
1204
+ acc.set(annotationType.name, annotationType);
1205
+ return acc;
1206
+ }, /* @__PURE__ */new Map());
1207
+ nestedChecks = nestedChecks.concat(value.markDefs.map(markDef => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1208
+ parent: value,
1209
+ value: markDef,
1210
+ path: path.concat(["markDefs", {
1211
+ _key: markDef._key
1212
+ }]),
1213
+ type: annotations.get(markDef._type)
1214
+ }))));
1215
+ }
1216
+ return rxjs.defer(() => rxjs.merge([...selfChecks, ...nestedChecks])).pipe(operators.mergeMap(validateNode => rxjs.concat(idle(), validateNode), 40), operators.mergeAll(), operators.toArray(), operators.map(lodash.flatten), operators.map(results => {
1217
+ if (rules.some(rule => rule._fieldRules)) {
1218
+ return lodash.uniqBy(results, rule => JSON.stringify(rule));
1219
+ }
1220
+ return results;
1221
+ }));
1222
+ }
1223
+ function idle(timeout) {
1224
+ return new rxjs.Observable(observer => {
1225
+ const handle = requestIdleCallback(() => {
1226
+ observer.complete();
1227
+ }, timeout ? {
1228
+ timeout
1229
+ } : void 0);
1230
+ return () => cancelIdleCallback(handle);
1231
+ });
1232
+ }
1233
+ function traverse(typeDef, visited) {
1234
+ if (visited.has(typeDef)) {
1235
+ return;
1236
+ }
1237
+ visited.add(typeDef);
1238
+ typeDef.validation = normalizeValidationRules(typeDef);
1239
+ if ("fields" in typeDef) {
1240
+ for (const field of typeDef.fields) {
1241
+ traverse(field.type, visited);
1242
+ }
1243
+ }
1244
+ if ("of" in typeDef) {
1245
+ for (const candidate of typeDef.of) {
1246
+ traverse(candidate, visited);
1247
+ }
1248
+ }
1249
+ if (typeDef.annotations) {
1250
+ for (const annotation of typeDef.annotations) {
1251
+ traverse(annotation, visited);
1252
+ }
1253
+ }
1254
+ }
1255
+ function inferFromSchemaType(typeDef) {
1256
+ traverse(typeDef, /* @__PURE__ */new Set());
1257
+ return typeDef;
1258
+ }
1259
+ function inferFromSchema(schema) {
1260
+ const typeNames = schema.getTypeNames();
1261
+ typeNames.forEach(typeName => {
1262
+ const schemaType = schema.get(typeName);
1263
+ if (schemaType) {
1264
+ inferFromSchemaType(schemaType);
1265
+ }
1266
+ });
1267
+ return schema;
1268
+ }
1269
+ exports.Rule = Rule;
1270
+ exports.inferFromSchema = inferFromSchema;
1271
+ exports.inferFromSchemaType = inferFromSchemaType;
1272
+ exports.validateDocument = validateDocument;
1273
+ exports.validateDocumentObservable = validateDocumentObservable;
1331
1274
  //# sourceMappingURL=index.js.map