@sanity/validation 2.34.1-canary.0 → 2.34.2-empty-template-cli.0

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.
@@ -4,82 +4,108 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
+
7
8
  var _deepEquals = _interopRequireDefault(require("../util/deepEquals"));
9
+
8
10
  var _ValidationError = _interopRequireDefault(require("../ValidationError"));
11
+
9
12
  var _genericValidator = _interopRequireDefault(require("./genericValidator"));
13
+
10
14
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
+
11
16
  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; }
17
+
12
18
  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; }
19
+
13
20
  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; }
21
+
14
22
  var arrayValidators = _objectSpread(_objectSpread({}, _genericValidator.default), {}, {
15
23
  min: (minLength, value, message) => {
16
24
  if (!value || value.length >= minLength) {
17
25
  return true;
18
26
  }
27
+
19
28
  return message || "Must have at least ".concat(minLength, " items");
20
29
  },
21
30
  max: (maxLength, value, message) => {
22
31
  if (!value || value.length <= maxLength) {
23
32
  return true;
24
33
  }
34
+
25
35
  return message || "Must have at most ".concat(maxLength, " items");
26
36
  },
27
37
  length: (wantedLength, value, message) => {
28
38
  if (!value || value.length === wantedLength) {
29
39
  return true;
30
40
  }
41
+
31
42
  return message || "Must have exactly ".concat(wantedLength, " items");
32
43
  },
33
44
  presence: (flag, value, message) => {
34
45
  if (flag === 'required' && !value) {
35
46
  return message || 'Required';
36
47
  }
48
+
37
49
  return true;
38
50
  },
39
51
  valid: (allowedValues, values, message) => {
40
52
  var valueType = typeof values;
53
+
41
54
  if (valueType === 'undefined') {
42
55
  return true;
43
56
  }
57
+
44
58
  var paths = [];
59
+
45
60
  var _loop = function _loop(i) {
46
61
  var value = values[i];
62
+
47
63
  if (allowedValues.some(expected => (0, _deepEquals.default)(expected, value))) {
48
64
  return "continue";
49
65
  }
66
+
50
67
  var pathSegment = value && value._key ? {
51
68
  _key: value._key
52
69
  } : i;
53
70
  paths.push([pathSegment]);
54
71
  };
72
+
55
73
  for (var i = 0; i < values.length; i++) {
56
74
  var _ret = _loop(i);
75
+
57
76
  if (_ret === "continue") continue;
58
77
  }
78
+
59
79
  return paths.length === 0 ? true : new _ValidationError.default(message || 'Value did not match any allowed values', {
60
80
  paths
61
81
  });
62
82
  },
63
83
  unique: (_unused, value, message) => {
64
84
  var dupeIndices = [];
85
+
65
86
  if (!value) {
66
87
  return true;
67
88
  }
89
+
68
90
  for (var x = 0; x < value.length; x++) {
69
91
  for (var y = x + 1; y < value.length; y++) {
70
92
  var itemA = value[x];
71
93
  var itemB = value[y];
94
+
72
95
  if (!(0, _deepEquals.default)(itemA, itemB)) {
73
96
  continue;
74
97
  }
98
+
75
99
  if (dupeIndices.indexOf(x) === -1) {
76
100
  dupeIndices.push(x);
77
101
  }
102
+
78
103
  if (dupeIndices.indexOf(y) === -1) {
79
104
  dupeIndices.push(y);
80
105
  }
81
106
  }
82
107
  }
108
+
83
109
  var paths = dupeIndices.map(idx => {
84
110
  var item = value[idx];
85
111
  var pathSegment = item && item._key ? {
@@ -92,5 +118,6 @@ var arrayValidators = _objectSpread(_objectSpread({}, _genericValidator.default)
92
118
  }) : true;
93
119
  }
94
120
  });
121
+
95
122
  var _default = arrayValidators;
96
123
  exports.default = _default;
@@ -4,18 +4,26 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
+
7
8
  var _genericValidator = _interopRequireDefault(require("./genericValidator"));
9
+
8
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+
9
12
  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; }
13
+
10
14
  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; }
15
+
11
16
  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; }
17
+
12
18
  var booleanValidators = _objectSpread(_objectSpread({}, _genericValidator.default), {}, {
13
19
  presence: (flag, value, message) => {
14
20
  if (flag === 'required' && typeof value !== 'boolean') {
15
21
  return message || 'Required';
16
22
  }
23
+
17
24
  return true;
18
25
  }
19
26
  });
27
+
20
28
  var _default = booleanValidators;
21
29
  exports.default = _default;
@@ -5,20 +5,25 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  exports.isRecord = isRecord;
8
+
8
9
  var _format = _interopRequireDefault(require("date-fns/format"));
10
+
9
11
  var _genericValidator = _interopRequireDefault(require("./genericValidator"));
12
+
10
13
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
+
11
15
  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; }
16
+
12
17
  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; }
18
+
13
19
  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; }
20
+
14
21
  function isRecord(obj) {
15
22
  return typeof obj === 'object' && obj !== null && !Array.isArray(obj);
16
- }
23
+ } // eslint-disable-next-line no-useless-escape
17
24
 
18
- // eslint-disable-next-line no-useless-escape
19
- var 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)?)?)?)?$/;
20
25
 
21
- // eslint-disable-next-line no-warning-comments
26
+ var 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)?)?)?)?$/; // eslint-disable-next-line no-warning-comments
22
27
  // TODO (eventually): move these to schema type package
23
28
 
24
29
  var getFormattedDate = function getFormattedDate() {
@@ -26,45 +31,54 @@ var getFormattedDate = function getFormattedDate() {
26
31
  var value = arguments.length > 1 ? arguments[1] : undefined;
27
32
  var options = arguments.length > 2 ? arguments[2] : undefined;
28
33
  var format = 'yyyy-MM-dd';
34
+
29
35
  if (options && options.dateFormat) {
30
36
  format = options.dateFormat;
31
37
  }
38
+
32
39
  if (type === 'date') {
33
40
  // If the type is date only
34
41
  return (0, _format.default)(new Date(value), format);
35
- }
42
+ } // If the type is datetime
43
+
36
44
 
37
- // If the type is datetime
38
45
  if (options && options.timeFormat) {
39
46
  format += " ".concat(options.timeFormat);
40
47
  } else {
41
48
  format += ' HH:mm';
42
49
  }
50
+
43
51
  return (0, _format.default)(new Date(value), format);
44
52
  };
53
+
45
54
  function parseDate(date) {
46
55
  var throwOnError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
47
56
  if (!date) return null;
48
- if (date === 'now') return new Date();
57
+ if (date === 'now') return new Date(); // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
58
 
50
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
51
59
  var parsed = new Date(date);
52
60
  var isInvalid = isNaN(parsed.getTime());
61
+
53
62
  if (isInvalid && throwOnError) {
54
63
  throw new Error("Unable to parse \"".concat(date, "\" to a date"));
55
64
  }
65
+
56
66
  return isInvalid ? null : parsed;
57
67
  }
68
+
58
69
  var dateValidators = _objectSpread(_objectSpread({}, _genericValidator.default), {}, {
59
70
  type: (_unused, value, message) => {
60
71
  var strVal = "".concat(value);
72
+
61
73
  if (!strVal || isoDate.test(value)) {
62
74
  return true;
63
75
  }
76
+
64
77
  return message || 'Must be a valid ISO-8601 formatted date string';
65
78
  },
66
79
  min: (minDate, value, message, context) => {
67
80
  var dateVal = parseDate(value);
81
+
68
82
  if (!dateVal) {
69
83
  return true; // `type()` should catch parse errors
70
84
  }
@@ -72,15 +86,18 @@ var dateValidators = _objectSpread(_objectSpread({}, _genericValidator.default),
72
86
  if (!value || dateVal >= parseDate(minDate, true)) {
73
87
  return true;
74
88
  }
89
+
75
90
  if (!context.type) {
76
91
  throw new Error("`type` was not provided in validation context.");
77
92
  }
93
+
78
94
  var dateTimeOptions = isRecord(context.type.options) ? context.type.options : {};
79
95
  var date = getFormattedDate(context.type.name, minDate, dateTimeOptions);
80
96
  return message || "Must be at or after ".concat(date);
81
97
  },
82
98
  max: (maxDate, value, message, context) => {
83
99
  var dateVal = parseDate(value);
100
+
84
101
  if (!dateVal) {
85
102
  return true; // `type()` should catch parse errors
86
103
  }
@@ -88,13 +105,16 @@ var dateValidators = _objectSpread(_objectSpread({}, _genericValidator.default),
88
105
  if (!value || dateVal <= parseDate(maxDate, true)) {
89
106
  return true;
90
107
  }
108
+
91
109
  if (!context.type) {
92
110
  throw new Error("`type` was not provided in validation context.");
93
111
  }
112
+
94
113
  var dateTimeOptions = isRecord(context.type.options) ? context.type.options : {};
95
114
  var date = getFormattedDate(context.type.name, maxDate, dateTimeOptions);
96
115
  return message || "Must be at or before ".concat(date);
97
116
  }
98
117
  });
118
+
99
119
  var _default = dateValidators;
100
120
  exports.default = _default;
@@ -4,41 +4,57 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
+
7
8
  var _typeString = _interopRequireDefault(require("../util/typeString"));
9
+
8
10
  var _deepEquals = _interopRequireDefault(require("../util/deepEquals"));
11
+
9
12
  var _pathToString = _interopRequireDefault(require("../util/pathToString"));
13
+
10
14
  var _ValidationError = _interopRequireDefault(require("../ValidationError"));
15
+
11
16
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+
12
18
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
19
+
13
20
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
21
+
14
22
  var SLOW_VALIDATOR_TIMEOUT = 5000;
23
+
15
24
  var formatValidationErrors = options => {
16
25
  var message;
26
+
17
27
  if (options.message) {
18
28
  message = options.message;
19
29
  } else if (options.results.length === 1) {
20
30
  var _options$results$;
31
+
21
32
  message = (_options$results$ = options.results[0]) === null || _options$results$ === void 0 ? void 0 : _options$results$.item.message;
22
33
  } else {
23
34
  message = "[".concat(options.results.map(err => err.item.message).join(" - ".concat(options.operation, " - ")), "]");
24
35
  }
36
+
25
37
  return new _ValidationError.default(message, {
26
38
  children: options.results.length > 1 ? options.results : undefined,
27
39
  operation: options.operation
28
40
  });
29
41
  };
42
+
30
43
  var genericValidators = {
31
44
  type: (expected, value, message) => {
32
45
  var actualType = (0, _typeString.default)(value);
46
+
33
47
  if (actualType !== expected && actualType !== 'undefined') {
34
48
  return message || "Expected type \"".concat(expected, "\", got \"").concat(actualType, "\"");
35
49
  }
50
+
36
51
  return true;
37
52
  },
38
53
  presence: (expected, value, message) => {
39
54
  if (value === undefined && expected === 'required') {
40
55
  return message || 'Value is required';
41
56
  }
57
+
42
58
  return true;
43
59
  },
44
60
  all: function () {
@@ -52,17 +68,18 @@ var genericValidators = {
52
68
  operation: 'AND'
53
69
  });
54
70
  });
71
+
55
72
  function all(_x, _x2, _x3, _x4) {
56
73
  return _all.apply(this, arguments);
57
74
  }
75
+
58
76
  return all;
59
77
  }(),
60
78
  either: function () {
61
79
  var _either = _asyncToGenerator(function* (children, value, message, context) {
62
80
  var resolved = yield Promise.all(children.map(child => child.validate(value, context)));
63
- var results = resolved.flat();
81
+ var results = resolved.flat(); // Read: There is at least one rule that matched
64
82
 
65
- // Read: There is at least one rule that matched
66
83
  if (results.length < children.length) return true;
67
84
  return formatValidationErrors({
68
85
  message,
@@ -70,16 +87,20 @@ var genericValidators = {
70
87
  operation: 'OR'
71
88
  });
72
89
  });
90
+
73
91
  function either(_x5, _x6, _x7, _x8) {
74
92
  return _either.apply(this, arguments);
75
93
  }
94
+
76
95
  return either;
77
96
  }(),
78
97
  valid: (allowedValues, actual, message) => {
79
98
  var valueType = typeof actual;
99
+
80
100
  if (valueType === 'undefined') {
81
101
  return true;
82
102
  }
103
+
83
104
  var value = (valueType === 'number' || valueType === 'string') && "".concat(actual);
84
105
  var strValue = value && value.length > 30 ? "".concat(value.slice(0, 30), "\u2026") : value;
85
106
  var defaultMessage = value ? "Value \"".concat(strValue, "\" did not match any allowed values") : 'Value did not match any allowed values';
@@ -92,17 +113,21 @@ var genericValidators = {
92
113
  console.warn("Custom validator at ".concat((0, _pathToString.default)(context.path), " has taken more than ").concat(SLOW_VALIDATOR_TIMEOUT, "ms to respond"));
93
114
  }, SLOW_VALIDATOR_TIMEOUT);
94
115
  var result;
116
+
95
117
  try {
96
118
  result = yield fn(value, context);
97
119
  } finally {
98
120
  clearTimeout(slowTimer);
99
121
  }
122
+
100
123
  if (typeof result === 'string') return message || result;
101
124
  return result;
102
125
  });
126
+
103
127
  function custom(_x9, _x10, _x11, _x12) {
104
128
  return _custom.apply(this, arguments);
105
129
  }
130
+
106
131
  return custom;
107
132
  }()
108
133
  };
@@ -4,52 +4,67 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
+
7
8
  var _genericValidator = _interopRequireDefault(require("./genericValidator"));
9
+
8
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+
9
12
  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; }
13
+
10
14
  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; }
15
+
11
16
  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; }
17
+
12
18
  var precisionRx = /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
19
+
13
20
  var numberValidators = _objectSpread(_objectSpread({}, _genericValidator.default), {}, {
14
21
  integer: (_unused, value, message) => {
15
22
  if (!Number.isInteger(value)) {
16
23
  return message || 'Must be an integer';
17
24
  }
25
+
18
26
  return true;
19
27
  },
20
28
  precision: (limit, value, message) => {
21
29
  if (value === undefined) return true;
22
30
  var places = value.toString().match(precisionRx);
23
31
  var decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0);
32
+
24
33
  if (decimals > limit) {
25
34
  return message || "Max precision is ".concat(limit);
26
35
  }
36
+
27
37
  return true;
28
38
  },
29
39
  min: (minNum, value, message) => {
30
40
  if (value >= minNum) {
31
41
  return true;
32
42
  }
43
+
33
44
  return message || "Must be greater than or equal ".concat(minNum);
34
45
  },
35
46
  max: (maxNum, value, message) => {
36
47
  if (value <= maxNum) {
37
48
  return true;
38
49
  }
50
+
39
51
  return message || "Must be less than or equal ".concat(maxNum);
40
52
  },
41
53
  greaterThan: (num, value, message) => {
42
54
  if (value > num) {
43
55
  return true;
44
56
  }
57
+
45
58
  return message || "Must be greater than ".concat(num);
46
59
  },
47
60
  lessThan: (maxNum, value, message) => {
48
61
  if (value < maxNum) {
49
62
  return true;
50
63
  }
64
+
51
65
  return message || "Must be less than ".concat(maxNum);
52
66
  }
53
67
  });
68
+
54
69
  var _default = numberValidators;
55
70
  exports.default = _default;
@@ -4,24 +4,37 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
+
7
8
  var _types = require("@sanity/types");
9
+
8
10
  var _genericValidator = _interopRequireDefault(require("./genericValidator"));
11
+
9
12
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+
10
14
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
15
+
11
16
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
17
+
12
18
  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; }
19
+
13
20
  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; }
21
+
14
22
  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; }
23
+
15
24
  var metaKeys = ['_key', '_type', '_weak'];
25
+
16
26
  var objectValidators = _objectSpread(_objectSpread({}, _genericValidator.default), {}, {
17
27
  presence: (expected, value, message) => {
18
28
  if (expected !== 'required') {
19
29
  return true;
20
30
  }
31
+
21
32
  var keys = value && Object.keys(value).filter(key => !metaKeys.includes(key));
33
+
22
34
  if (value === undefined || keys && keys.length === 0) {
23
35
  return message || 'Required';
24
36
  }
37
+
25
38
  return true;
26
39
  },
27
40
  reference: function () {
@@ -29,31 +42,41 @@ var objectValidators = _objectSpread(_objectSpread({}, _genericValidator.default
29
42
  if (!value) {
30
43
  return true;
31
44
  }
45
+
32
46
  if (!(0, _types.isReference)(value)) {
33
47
  return message || true;
34
48
  }
49
+
35
50
  var type = context.type,
36
- getDocumentExists = context.getDocumentExists;
51
+ getDocumentExists = context.getDocumentExists;
52
+
37
53
  if (!type) {
38
54
  throw new Error("`type` was not provided in validation context");
39
55
  }
56
+
40
57
  if ('weak' in type && type.weak) {
41
58
  return true;
42
59
  }
60
+
43
61
  if (!getDocumentExists) {
44
62
  throw new Error("`getDocumentExists` was not provided in validation context");
45
63
  }
64
+
46
65
  var exists = yield getDocumentExists({
47
66
  id: value._ref
48
67
  });
68
+
49
69
  if (!exists) {
50
70
  return 'This reference must be published';
51
71
  }
72
+
52
73
  return true;
53
74
  });
75
+
54
76
  function reference(_x, _x2, _x3, _x4) {
55
77
  return _reference.apply(this, arguments);
56
78
  }
79
+
57
80
  return reference;
58
81
  }(),
59
82
  assetRequired: (flag, value, message) => {
@@ -61,8 +84,10 @@ var objectValidators = _objectSpread(_objectSpread({}, _genericValidator.default
61
84
  var assetType = flag.assetType || 'Asset';
62
85
  return message || "".concat(assetType, " required");
63
86
  }
87
+
64
88
  return true;
65
89
  }
66
90
  });
91
+
67
92
  var _default = objectValidators;
68
93
  exports.default = _default;
@@ -4,16 +4,27 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.slugValidator = void 0;
7
+
7
8
  var _memoize2 = _interopRequireDefault(require("lodash/memoize"));
9
+
8
10
  var _types = require("@sanity/types");
11
+
9
12
  var _getClient = _interopRequireDefault(require("../getClient"));
13
+
10
14
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
+
11
16
  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; }
17
+
12
18
  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; }
19
+
13
20
  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; }
21
+
14
22
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
23
+
15
24
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
25
+
16
26
  var memoizedWarnOnArraySlug = (0, _memoize2.default)(warnOnArraySlug);
27
+
17
28
  function getDocumentIds(id) {
18
29
  var isDraft = id.indexOf('drafts.') === 0;
19
30
  return {
@@ -21,6 +32,7 @@ function getDocumentIds(id) {
21
32
  draft: isDraft ? id : "drafts.".concat(id)
22
33
  };
23
34
  }
35
+
24
36
  function serializePath(path) {
25
37
  return path.reduce((target, part, i) => {
26
38
  var isIndex = typeof part === 'number';
@@ -30,26 +42,34 @@ function serializePath(path) {
30
42
  return "".concat(target).concat(add);
31
43
  }, '');
32
44
  }
45
+
33
46
  var defaultIsUnique = (slug, context) => {
34
47
  var document = context.document,
35
- path = context.path,
36
- type = context.type;
48
+ path = context.path,
49
+ type = context.type;
37
50
  var schemaOptions = type === null || type === void 0 ? void 0 : type.options;
51
+
38
52
  if (!document) {
39
53
  throw new Error("`document` was not provided in validation context.");
40
54
  }
55
+
41
56
  if (!path) {
42
57
  throw new Error("`path` was not provided in validation context.");
43
58
  }
59
+
44
60
  var disableArrayWarning = (schemaOptions === null || schemaOptions === void 0 ? void 0 : schemaOptions.disableArrayWarning) || false;
61
+
45
62
  var _getDocumentIds = getDocumentIds(document._id),
46
- published = _getDocumentIds.published,
47
- draft = _getDocumentIds.draft;
63
+ published = _getDocumentIds.published,
64
+ draft = _getDocumentIds.draft;
65
+
48
66
  var docType = document._type;
49
67
  var atPath = serializePath(path.concat('current'));
68
+
50
69
  if (!disableArrayWarning && atPath.includes('[]')) {
51
70
  memoizedWarnOnArraySlug(serializePath(path));
52
71
  }
72
+
53
73
  var constraints = ['_type == $docType', "!(_id in [$draft, $published])", "".concat(atPath, " == $slug")].join(' && ');
54
74
  return (0, _getClient.default)().fetch("!defined(*[".concat(constraints, "][0]._id)"), {
55
75
  docType,
@@ -60,43 +80,54 @@ var defaultIsUnique = (slug, context) => {
60
80
  tag: 'validation.slug-is-unique'
61
81
  });
62
82
  };
83
+
63
84
  function warnOnArraySlug(serializedPath) {
64
85
  /* eslint-disable no-console */
65
86
  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'));
66
87
  /* eslint-enable no-console */
67
88
  }
68
-
69
89
  /**
70
90
  * Validates slugs values by querying for uniqueness from the client.
71
91
  *
72
92
  * This is a custom rule implementation (e.g. `Rule.custom(slugValidator)`)
73
93
  * that's populated in `inferFromSchemaType` when the type name is `slug`
74
94
  */
95
+
96
+
75
97
  var slugValidator = /*#__PURE__*/function () {
76
98
  var _ref = _asyncToGenerator(function* (value, context) {
77
99
  var _context$type;
100
+
78
101
  if (!value) {
79
102
  return true;
80
103
  }
104
+
81
105
  if (typeof value !== 'object') {
82
106
  return 'Slug must be an object';
83
107
  }
108
+
84
109
  var slugValue = value.current;
110
+
85
111
  if (!slugValue) {
86
112
  return 'Slug must have a value';
87
113
  }
114
+
88
115
  var options = context === null || context === void 0 ? void 0 : (_context$type = context.type) === null || _context$type === void 0 ? void 0 : _context$type.options;
89
116
  var isUnique = (options === null || options === void 0 ? void 0 : options.isUnique) || defaultIsUnique;
90
117
  var wasUnique = yield isUnique(slugValue, _objectSpread(_objectSpread({}, context), {}, {
91
118
  defaultIsUnique
92
119
  }));
120
+
93
121
  if (wasUnique) {
94
122
  return true;
95
123
  }
124
+
96
125
  return 'Slug is already in use';
97
126
  });
127
+
98
128
  return function slugValidator(_x, _x2) {
99
129
  return _ref.apply(this, arguments);
100
130
  };
101
131
  }();
132
+
102
133
  exports.slugValidator = slugValidator;