@sanity/validation 3.0.0-dev-preview.21 → 3.0.0-findability.122

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.
@@ -1,15 +1,9 @@
1
1
  const _excluded = ["value", "type", "path", "parent"];
2
-
3
2
  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; }
4
-
5
3
  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
-
7
4
  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; }
8
-
9
5
  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; }
10
-
11
6
  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; }
12
-
13
7
  import { cloneDeep, get, memoize, flatten, uniqBy } from 'lodash';
14
8
  import { isKeyedObject, isReference, isBlock, isBlockSchemaType, isSpanSchemaType, isTypedObject } from '@sanity/types';
15
9
  import formatDate from 'date-fns/format';
@@ -23,7 +17,6 @@ const ValidationError = class ValidationError2 {
23
17
  this.children = options.children;
24
18
  this.operation = options.operation;
25
19
  }
26
-
27
20
  cloneWithMessage(msg) {
28
21
  return new ValidationError2(msg, {
29
22
  paths: this.paths,
@@ -31,66 +24,49 @@ const ValidationError = class ValidationError2 {
31
24
  operation: this.operation
32
25
  });
33
26
  }
34
-
35
27
  };
36
-
37
28
  var escapeRegex = string => {
38
29
  return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, "\\$&");
39
30
  };
40
-
41
31
  function pathToString() {
42
32
  let path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
43
33
  return path.reduce((target, segment, i) => {
44
34
  const segmentType = typeof segment;
45
-
46
35
  if (segmentType === "number") {
47
36
  return "".concat(target, "[").concat(segment, "]");
48
37
  }
49
-
50
38
  if (segmentType === "string") {
51
39
  const separator = i === 0 ? "" : ".";
52
40
  return "".concat(target).concat(separator).concat(segment);
53
41
  }
54
-
55
42
  if (isKeyedObject(segment)) {
56
43
  return "".concat(target, "[_key==\"").concat(segment._key, "\"]");
57
44
  }
58
-
59
45
  throw new Error("Unsupported path segment \"".concat(segment, "\""));
60
46
  }, "");
61
47
  }
62
-
63
48
  function isNonNullable$1(t) {
64
49
  return t !== null || t !== void 0;
65
50
  }
66
-
67
51
  function convertToValidationMarker(validatorResult, level, context) {
68
52
  var _a;
69
-
70
53
  if (!context) {
71
54
  throw new Error("missing context");
72
55
  }
73
-
74
56
  if (validatorResult === true) return [];
75
-
76
57
  if (Array.isArray(validatorResult)) {
77
58
  return validatorResult.flatMap(child => convertToValidationMarker(child, level, context)).filter(isNonNullable$1);
78
59
  }
79
-
80
60
  if (typeof validatorResult === "string") {
81
61
  return convertToValidationMarker(new ValidationError(validatorResult), level, context);
82
62
  }
83
-
84
63
  if (!(validatorResult instanceof ValidationError)) {
85
64
  if (typeof (validatorResult == null ? void 0 : validatorResult.message) !== "string") {
86
65
  throw new Error("".concat(pathToString(context.path), ": Validator must return 'true' if valid or an error message as a string on errors"));
87
66
  }
88
-
89
67
  return convertToValidationMarker(new ValidationError(validatorResult.message, validatorResult), level, context);
90
68
  }
91
-
92
69
  const results = [];
93
-
94
70
  if (!((_a = validatorResult.paths) == null ? void 0 : _a.length)) {
95
71
  return [{
96
72
  level: level || "error",
@@ -98,113 +74,85 @@ function convertToValidationMarker(validatorResult, level, context) {
98
74
  path: context.path || []
99
75
  }];
100
76
  }
101
-
102
77
  return results.concat(validatorResult.paths.map(path => ({
103
78
  path: (context.path || []).concat(path),
104
79
  level: level || "error",
105
80
  item: validatorResult
106
81
  })));
107
82
  }
108
-
109
83
  const _toString = {}.toString;
110
84
  const builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error];
111
-
112
85
  function isBuiltIn(_constructor) {
113
86
  for (let i = 0; i < builtIns.length; i++) {
114
87
  if (builtIns[i] === _constructor) return true;
115
88
  }
116
-
117
89
  return false;
118
90
  }
119
-
120
91
  function typeString(obj) {
121
92
  const stringType = _toString.call(obj).slice(8, -1);
122
-
123
93
  if (obj === null || obj === void 0) return stringType.toLowerCase();
124
94
  const constructorType = obj.constructor;
125
95
  if (constructorType && !isBuiltIn(constructorType)) return constructorType.name;
126
96
  return stringType;
127
97
  }
128
-
129
98
  function deepEquals(a, b) {
130
99
  if (a === b) {
131
100
  return true;
132
101
  }
133
-
134
102
  if (Array.isArray(a) && Array.isArray(b)) {
135
103
  if (a.length != b.length) return false;
136
-
137
104
  for (let i = 0; i < a.length; i++) {
138
105
  if (!deepEquals(a[i], b[i])) {
139
106
  return false;
140
107
  }
141
108
  }
142
-
143
109
  return true;
144
110
  }
145
-
146
111
  if (Array.isArray(a) != Array.isArray(b)) {
147
112
  return false;
148
113
  }
149
-
150
114
  if (a && b && typeof a === "object" && typeof b === "object") {
151
115
  const keys = Object.keys(a);
152
-
153
116
  if (keys.length !== Object.keys(b).length) {
154
117
  return false;
155
118
  }
156
-
157
119
  if (a instanceof Date && b instanceof Date) {
158
120
  return a.getTime() === b.getTime();
159
121
  }
160
-
161
122
  if (a instanceof Date != b instanceof Date) {
162
123
  return false;
163
124
  }
164
-
165
125
  if (a instanceof RegExp && b instanceof RegExp) {
166
126
  return a.toString() == b.toString();
167
127
  }
168
-
169
128
  if (a instanceof RegExp != b instanceof RegExp) {
170
129
  return false;
171
130
  }
172
-
173
131
  for (let i = 0; i < keys.length; i++) {
174
132
  if (keys[i] === "_key") {
175
133
  continue;
176
134
  }
177
-
178
135
  if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
179
136
  return false;
180
137
  }
181
138
  }
182
-
183
139
  for (let i = 0; i < keys.length; i++) {
184
140
  const key = keys[i];
185
-
186
141
  if (key === "_key") {
187
142
  continue;
188
143
  }
189
-
190
144
  if (!deepEquals(a[key], b[key])) {
191
145
  return false;
192
146
  }
193
147
  }
194
-
195
148
  return true;
196
149
  }
197
-
198
150
  return false;
199
151
  }
200
-
201
152
  const SLOW_VALIDATOR_TIMEOUT = 5e3;
202
-
203
153
  const formatValidationErrors = options => {
204
154
  var _a;
205
-
206
155
  let message;
207
-
208
156
  if (options.message) {
209
157
  message = options.message;
210
158
  } else if (options.results.length === 1) {
@@ -212,28 +160,23 @@ const formatValidationErrors = options => {
212
160
  } else {
213
161
  message = "[".concat(options.results.map(err => err.item.message).join(" - ".concat(options.operation, " - ")), "]");
214
162
  }
215
-
216
163
  return new ValidationError(message, {
217
164
  children: options.results.length > 1 ? options.results : void 0,
218
165
  operation: options.operation
219
166
  });
220
167
  };
221
-
222
168
  const genericValidators = {
223
169
  type: (expected, value, message) => {
224
170
  const actualType = typeString(value);
225
-
226
171
  if (actualType !== expected && actualType !== "undefined") {
227
172
  return message || "Expected type \"".concat(expected, "\", got \"").concat(actualType, "\"");
228
173
  }
229
-
230
174
  return true;
231
175
  },
232
176
  presence: (expected, value, message) => {
233
177
  if (value === void 0 && expected === "required") {
234
178
  return message || "Value is required";
235
179
  }
236
-
237
180
  return true;
238
181
  },
239
182
  all: async (children, value, message, context) => {
@@ -258,11 +201,9 @@ const genericValidators = {
258
201
  },
259
202
  valid: (allowedValues, actual, message) => {
260
203
  const valueType = typeof actual;
261
-
262
204
  if (valueType === "undefined") {
263
205
  return true;
264
206
  }
265
-
266
207
  const value = (valueType === "number" || valueType === "string") && "".concat(actual);
267
208
  const strValue = value && value.length > 30 ? "".concat(value.slice(0, 30), "\u2026") : value;
268
209
  const defaultMessage = value ? "Value \"".concat(strValue, "\" did not match any allowed values") : "Value did not match any allowed values";
@@ -273,106 +214,86 @@ const genericValidators = {
273
214
  console.warn("Custom validator at ".concat(pathToString(context.path), " has taken more than ").concat(SLOW_VALIDATOR_TIMEOUT, "ms to respond"));
274
215
  }, SLOW_VALIDATOR_TIMEOUT);
275
216
  let result;
276
-
277
217
  try {
278
218
  result = await fn(value, context);
279
219
  } finally {
280
220
  clearTimeout(slowTimer);
281
221
  }
282
-
283
222
  if (typeof result === "string") return message || result;
284
223
  return result;
285
224
  }
286
225
  };
287
-
288
226
  const booleanValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
289
227
  presence: (flag, value, message) => {
290
228
  if (flag === "required" && typeof value !== "boolean") {
291
229
  return message || "Required";
292
230
  }
293
-
294
231
  return true;
295
232
  }
296
233
  });
297
-
298
234
  const precisionRx = /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
299
-
300
235
  const numberValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
301
236
  integer: (_unused, value, message) => {
302
237
  if (!Number.isInteger(value)) {
303
238
  return message || "Must be an integer";
304
239
  }
305
-
306
240
  return true;
307
241
  },
308
242
  precision: (limit, value, message) => {
309
243
  if (value === void 0) return true;
310
244
  const places = value.toString().match(precisionRx);
311
245
  const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0);
312
-
313
246
  if (decimals > limit) {
314
247
  return message || "Max precision is ".concat(limit);
315
248
  }
316
-
317
249
  return true;
318
250
  },
319
251
  min: (minNum, value, message) => {
320
252
  if (value >= minNum) {
321
253
  return true;
322
254
  }
323
-
324
255
  return message || "Must be greater than or equal ".concat(minNum);
325
256
  },
326
257
  max: (maxNum, value, message) => {
327
258
  if (value <= maxNum) {
328
259
  return true;
329
260
  }
330
-
331
261
  return message || "Must be less than or equal ".concat(maxNum);
332
262
  },
333
263
  greaterThan: (num, value, message) => {
334
264
  if (value > num) {
335
265
  return true;
336
266
  }
337
-
338
267
  return message || "Must be greater than ".concat(num);
339
268
  },
340
269
  lessThan: (maxNum, value, message) => {
341
270
  if (value < maxNum) {
342
271
  return true;
343
272
  }
344
-
345
273
  return message || "Must be less than ".concat(maxNum);
346
274
  }
347
275
  });
348
-
349
276
  const DUMMY_ORIGIN = "http://sanity";
350
277
  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,}))$/;
351
-
352
278
  const isRelativeUrl = url => /^\.*\//.test(url);
353
-
354
279
  const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
355
280
  min: (minLength, value, message) => {
356
281
  if (!value || value.length >= minLength) {
357
282
  return true;
358
283
  }
359
-
360
284
  return message || "Must be at least ".concat(minLength, " characters long");
361
285
  },
362
286
  max: (maxLength, value, message) => {
363
287
  if (!value || value.length <= maxLength) {
364
288
  return true;
365
289
  }
366
-
367
290
  return message || "Must be at most ".concat(maxLength, " characters long");
368
291
  },
369
292
  length: (wantedLength, value, message) => {
370
293
  const strValue = value || "";
371
-
372
294
  if (strValue.length === wantedLength) {
373
295
  return true;
374
296
  }
375
-
376
297
  return message || "Must be exactly ".concat(wantedLength, " characters long");
377
298
  },
378
299
  uri: (constraints, value, message) => {
@@ -386,52 +307,41 @@ const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {},
386
307
  } = options;
387
308
  const allowRelative = options.allowRelative || relativeOnly;
388
309
  let url;
389
-
390
310
  try {
391
311
  url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue);
392
312
  } catch (err) {
393
313
  return message || "Not a valid URL";
394
314
  }
395
-
396
315
  if (relativeOnly && url.origin !== DUMMY_ORIGIN) {
397
316
  return message || "Only relative URLs are allowed";
398
317
  }
399
-
400
318
  if (!allowRelative && url.origin === DUMMY_ORIGIN && isRelativeUrl(strValue)) {
401
319
  return message || "Relative URLs are not allowed";
402
320
  }
403
-
404
321
  if (!allowCredentials && (url.username || url.password)) {
405
322
  return message || "Username/password not allowed";
406
323
  }
407
-
408
324
  const urlScheme = url.protocol.replace(/:$/, "");
409
325
  const matchesAllowedScheme = options.scheme.some(scheme => scheme.test(urlScheme));
410
-
411
326
  if (!matchesAllowedScheme) {
412
327
  return message || "Does not match allowed protocols/schemes";
413
328
  }
414
-
415
329
  return true;
416
330
  },
417
331
  stringCasing: (casing, value, message) => {
418
332
  const strValue = value || "";
419
-
420
333
  if (casing === "uppercase" && strValue !== strValue.toLocaleUpperCase()) {
421
334
  return message || "Must be all uppercase letters";
422
335
  }
423
-
424
336
  if (casing === "lowercase" && strValue !== strValue.toLocaleLowerCase()) {
425
337
  return message || "Must be all lowercase letters";
426
338
  }
427
-
428
339
  return true;
429
340
  },
430
341
  presence: (flag, value, message) => {
431
342
  if (flag === "required" && !value) {
432
343
  return message || "Required";
433
344
  }
434
-
435
345
  return true;
436
346
  },
437
347
  regex: (options, value, message) => {
@@ -443,106 +353,85 @@ const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {},
443
353
  const regName = name || "\"".concat(pattern.toString(), "\"");
444
354
  const strValue = value || "";
445
355
  const matches = pattern.test(strValue);
446
-
447
356
  if (!invert && !matches || invert && matches) {
448
357
  const defaultMessage = invert ? "Should not match ".concat(regName, "-pattern") : "Does not match ".concat(regName, "-pattern");
449
358
  return message || defaultMessage;
450
359
  }
451
-
452
360
  return true;
453
361
  },
454
362
  email: (_unused, value, message) => {
455
363
  const strValue = "".concat(value || "").trim();
456
-
457
364
  if (!strValue || emailRegex.test(strValue)) {
458
365
  return true;
459
366
  }
460
-
461
367
  return message || "Must be a valid email address";
462
368
  }
463
369
  });
464
-
465
370
  const arrayValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
466
371
  min: (minLength, value, message) => {
467
372
  if (!value || value.length >= minLength) {
468
373
  return true;
469
374
  }
470
-
471
375
  return message || "Must have at least ".concat(minLength, " items");
472
376
  },
473
377
  max: (maxLength, value, message) => {
474
378
  if (!value || value.length <= maxLength) {
475
379
  return true;
476
380
  }
477
-
478
381
  return message || "Must have at most ".concat(maxLength, " items");
479
382
  },
480
383
  length: (wantedLength, value, message) => {
481
384
  if (!value || value.length === wantedLength) {
482
385
  return true;
483
386
  }
484
-
485
387
  return message || "Must have exactly ".concat(wantedLength, " items");
486
388
  },
487
389
  presence: (flag, value, message) => {
488
390
  if (flag === "required" && !value) {
489
391
  return message || "Required";
490
392
  }
491
-
492
393
  return true;
493
394
  },
494
395
  valid: (allowedValues, values, message) => {
495
396
  const valueType = typeof values;
496
-
497
397
  if (valueType === "undefined") {
498
398
  return true;
499
399
  }
500
-
501
400
  const paths = [];
502
-
503
401
  for (let i = 0; i < values.length; i++) {
504
402
  const value = values[i];
505
-
506
403
  if (allowedValues.some(expected => deepEquals(expected, value))) {
507
404
  continue;
508
405
  }
509
-
510
406
  const pathSegment = value && value._key ? {
511
407
  _key: value._key
512
408
  } : i;
513
409
  paths.push([pathSegment]);
514
410
  }
515
-
516
411
  return paths.length === 0 ? true : new ValidationError(message || "Value did not match any allowed values", {
517
412
  paths
518
413
  });
519
414
  },
520
415
  unique: (_unused, value, message) => {
521
416
  const dupeIndices = [];
522
-
523
417
  if (!value) {
524
418
  return true;
525
419
  }
526
-
527
420
  for (let x = 0; x < value.length; x++) {
528
421
  for (let y = x + 1; y < value.length; y++) {
529
422
  const itemA = value[x];
530
423
  const itemB = value[y];
531
-
532
424
  if (!deepEquals(itemA, itemB)) {
533
425
  continue;
534
426
  }
535
-
536
427
  if (dupeIndices.indexOf(x) === -1) {
537
428
  dupeIndices.push(x);
538
429
  }
539
-
540
430
  if (dupeIndices.indexOf(y) === -1) {
541
431
  dupeIndices.push(y);
542
432
  }
543
433
  }
544
434
  }
545
-
546
435
  const paths = dupeIndices.map(idx => {
547
436
  const item = value[idx];
548
437
  const pathSegment = item && item._key ? {
@@ -555,57 +444,44 @@ const arrayValidators = _objectSpread(_objectSpread({}, genericValidators), {},
555
444
  }) : true;
556
445
  }
557
446
  });
558
-
559
447
  const metaKeys = ["_key", "_type", "_weak"];
560
-
561
448
  const objectValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
562
449
  presence: (expected, value, message) => {
563
450
  if (expected !== "required") {
564
451
  return true;
565
452
  }
566
-
567
453
  const keys = value && Object.keys(value).filter(key => !metaKeys.includes(key));
568
-
569
454
  if (value === void 0 || keys && keys.length === 0) {
570
455
  return message || "Required";
571
456
  }
572
-
573
457
  return true;
574
458
  },
575
459
  reference: async (_unused, value, message, context) => {
576
460
  if (!value) {
577
461
  return true;
578
462
  }
579
-
580
463
  if (!isReference(value)) {
581
464
  return message || true;
582
465
  }
583
-
584
466
  const {
585
467
  type,
586
468
  getDocumentExists
587
469
  } = context;
588
-
589
470
  if (!type) {
590
471
  throw new Error("`type` was not provided in validation context");
591
472
  }
592
-
593
473
  if ("weak" in type && type.weak) {
594
474
  return true;
595
475
  }
596
-
597
476
  if (!getDocumentExists) {
598
477
  throw new Error("`getDocumentExists` was not provided in validation context");
599
478
  }
600
-
601
479
  const exists = await getDocumentExists({
602
480
  id: value._ref
603
481
  });
604
-
605
482
  if (!exists) {
606
483
  return "This reference must be published";
607
484
  }
608
-
609
485
  return true;
610
486
  },
611
487
  assetRequired: (flag, value, message) => {
@@ -613,106 +489,82 @@ const objectValidators = _objectSpread(_objectSpread({}, genericValidators), {},
613
489
  const assetType = flag.assetType || "Asset";
614
490
  return message || "".concat(assetType, " required");
615
491
  }
616
-
617
492
  return true;
618
493
  }
619
494
  });
620
-
621
495
  function isRecord$1(obj) {
622
496
  return typeof obj === "object" && obj !== null && !Array.isArray(obj);
623
497
  }
624
-
625
498
  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)?)?)?)?$/;
626
-
627
499
  const getFormattedDate = function () {
628
500
  let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
629
501
  let value = arguments.length > 1 ? arguments[1] : undefined;
630
502
  let options = arguments.length > 2 ? arguments[2] : undefined;
631
503
  let format = "yyyy-MM-dd";
632
-
633
504
  if (options && options.dateFormat) {
634
505
  format = options.dateFormat;
635
506
  }
636
-
637
507
  if (type === "date") {
638
508
  return formatDate(new Date(value), format);
639
509
  }
640
-
641
510
  if (options && options.timeFormat) {
642
511
  format += " ".concat(options.timeFormat);
643
512
  } else {
644
513
  format += " HH:mm";
645
514
  }
646
-
647
515
  return formatDate(new Date(value), format);
648
516
  };
649
-
650
517
  function parseDate(date) {
651
518
  let throwOnError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
652
519
  if (!date) return null;
653
520
  if (date === "now") return new Date();
654
521
  const parsed = new Date(date);
655
522
  const isInvalid = isNaN(parsed.getTime());
656
-
657
523
  if (isInvalid && throwOnError) {
658
524
  throw new Error("Unable to parse \"".concat(date, "\" to a date"));
659
525
  }
660
-
661
526
  return isInvalid ? null : parsed;
662
527
  }
663
-
664
528
  const dateValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
665
529
  type: (_unused, value, message) => {
666
530
  const strVal = "".concat(value);
667
-
668
531
  if (!strVal || isoDate.test(value)) {
669
532
  return true;
670
533
  }
671
-
672
534
  return message || "Must be a valid ISO-8601 formatted date string";
673
535
  },
674
536
  min: (minDate, value, message, context) => {
675
537
  const dateVal = parseDate(value);
676
-
677
538
  if (!dateVal) {
678
539
  return true;
679
540
  }
680
-
681
541
  if (!value || dateVal >= parseDate(minDate, true)) {
682
542
  return true;
683
543
  }
684
-
685
544
  if (!context.type) {
686
545
  throw new Error("`type` was not provided in validation context.");
687
546
  }
688
-
689
547
  const dateTimeOptions = isRecord$1(context.type.options) ? context.type.options : {};
690
548
  const date = getFormattedDate(context.type.name, minDate, dateTimeOptions);
691
549
  return message || "Must be at or after ".concat(date);
692
550
  },
693
551
  max: (maxDate, value, message, context) => {
694
552
  const dateVal = parseDate(value);
695
-
696
553
  if (!dateVal) {
697
554
  return true;
698
555
  }
699
-
700
556
  if (!value || dateVal <= parseDate(maxDate, true)) {
701
557
  return true;
702
558
  }
703
-
704
559
  if (!context.type) {
705
560
  throw new Error("`type` was not provided in validation context.");
706
561
  }
707
-
708
562
  const dateTimeOptions = isRecord$1(context.type.options) ? context.type.options : {};
709
563
  const date = getFormattedDate(context.type.name, maxDate, dateTimeOptions);
710
564
  return message || "Must be at or before ".concat(date);
711
565
  }
712
566
  });
713
-
714
567
  var _a;
715
-
716
568
  const typeValidators = {
717
569
  Boolean: booleanValidators,
718
570
  Number: numberValidators,
@@ -721,16 +573,13 @@ const typeValidators = {
721
573
  Object: objectValidators,
722
574
  Date: dateValidators
723
575
  };
724
-
725
576
  const getBaseType = type => {
726
577
  return type && type.type ? getBaseType(type.type) : type;
727
578
  };
728
-
729
579
  const isFieldRef = constraint => {
730
580
  if (typeof constraint !== "object" || !constraint) return false;
731
581
  return constraint.type === Rule.FIELD_REF;
732
582
  };
733
-
734
583
  const EMPTY_ARRAY = [];
735
584
  const FIELD_REF = Symbol("FIELD_REF");
736
585
  const ruleConstraintTypes$1 = ["Array", "Boolean", "Date", "Number", "Object", "String"];
@@ -747,34 +596,29 @@ const Rule = (_a = class {
747
596
  this._typeDef = typeDef;
748
597
  this.reset();
749
598
  }
750
-
751
599
  _mergeRequired(next) {
752
600
  if (this._required === "required" || next._required === "required") return "required";
753
601
  if (this._required === "optional" || next._required === "optional") return "optional";
754
602
  return void 0;
755
603
  }
756
-
757
604
  error(message) {
758
605
  const rule = this.clone();
759
606
  rule._level = "error";
760
607
  rule._message = message || void 0;
761
608
  return rule;
762
609
  }
763
-
764
610
  warning(message) {
765
611
  const rule = this.clone();
766
612
  rule._level = "warning";
767
613
  rule._message = message || void 0;
768
614
  return rule;
769
615
  }
770
-
771
616
  info(message) {
772
617
  const rule = this.clone();
773
618
  rule._level = "info";
774
619
  rule._message = message || void 0;
775
620
  return rule;
776
621
  }
777
-
778
622
  reset() {
779
623
  this._type = this._type || void 0;
780
624
  this._rules = (this._rules || []).filter(rule => rule.flag === "type");
@@ -784,11 +628,9 @@ const Rule = (_a = class {
784
628
  this._fieldRules = void 0;
785
629
  return this;
786
630
  }
787
-
788
631
  isRequired() {
789
632
  return this._required === "required";
790
633
  }
791
-
792
634
  clone() {
793
635
  const rule = new _a();
794
636
  rule._type = this._type;
@@ -800,7 +642,6 @@ const Rule = (_a = class {
800
642
  rule._typeDef = this._typeDef;
801
643
  return rule;
802
644
  }
803
-
804
645
  cloneWithRules(rules) {
805
646
  const rule = this.clone();
806
647
  const newRules = /* @__PURE__ */new Set();
@@ -808,7 +649,6 @@ const Rule = (_a = class {
808
649
  if (curr.flag === "type") {
809
650
  rule._type = curr.constraint;
810
651
  }
811
-
812
652
  newRules.add(curr.flag);
813
653
  });
814
654
  rule._rules = rule._rules.filter(curr => {
@@ -818,12 +658,10 @@ const Rule = (_a = class {
818
658
  }).concat(rules);
819
659
  return rule;
820
660
  }
821
-
822
661
  merge(rule) {
823
662
  if (this._type && rule._type && this._type !== rule._type) {
824
663
  throw new Error("merge() failed: conflicting types");
825
664
  }
826
-
827
665
  const newRule = this.cloneWithRules(rule._rules);
828
666
  newRule._type = this._type || rule._type;
829
667
  newRule._message = this._message || rule._message;
@@ -831,14 +669,11 @@ const Rule = (_a = class {
831
669
  newRule._level = this._level === "error" ? rule._level : this._level;
832
670
  return newRule;
833
671
  }
834
-
835
672
  type(targetType) {
836
673
  const type = "".concat(targetType.slice(0, 1).toUpperCase()).concat(targetType.slice(1));
837
-
838
674
  if (!ruleConstraintTypes$1.includes(type)) {
839
675
  throw new Error("Unknown type \"".concat(targetType, "\""));
840
676
  }
841
-
842
677
  const rule = this.cloneWithRules([{
843
678
  flag: "type",
844
679
  constraint: type
@@ -846,21 +681,18 @@ const Rule = (_a = class {
846
681
  rule._type = type;
847
682
  return rule;
848
683
  }
849
-
850
684
  all(children) {
851
685
  return this.cloneWithRules([{
852
686
  flag: "all",
853
687
  constraint: children
854
688
  }]);
855
689
  }
856
-
857
690
  either(children) {
858
691
  return this.cloneWithRules([{
859
692
  flag: "either",
860
693
  constraint: children
861
694
  }]);
862
695
  }
863
-
864
696
  optional() {
865
697
  const rule = this.cloneWithRules([{
866
698
  flag: "presence",
@@ -869,7 +701,6 @@ const Rule = (_a = class {
869
701
  rule._required = "optional";
870
702
  return rule;
871
703
  }
872
-
873
704
  required() {
874
705
  const rule = this.cloneWithRules([{
875
706
  flag: "presence",
@@ -878,42 +709,36 @@ const Rule = (_a = class {
878
709
  rule._required = "required";
879
710
  return rule;
880
711
  }
881
-
882
712
  custom(fn) {
883
713
  return this.cloneWithRules([{
884
714
  flag: "custom",
885
715
  constraint: fn
886
716
  }]);
887
717
  }
888
-
889
718
  block(fn) {
890
719
  return this.cloneWithRules([{
891
720
  flag: "custom",
892
721
  constraint: fn
893
722
  }]);
894
723
  }
895
-
896
724
  min(len) {
897
725
  return this.cloneWithRules([{
898
726
  flag: "min",
899
727
  constraint: len
900
728
  }]);
901
729
  }
902
-
903
730
  max(len) {
904
731
  return this.cloneWithRules([{
905
732
  flag: "max",
906
733
  constraint: len
907
734
  }]);
908
735
  }
909
-
910
736
  length(len) {
911
737
  return this.cloneWithRules([{
912
738
  flag: "length",
913
739
  constraint: len
914
740
  }]);
915
741
  }
916
-
917
742
  valid(value) {
918
743
  const values = Array.isArray(value) ? value : [value];
919
744
  return this.cloneWithRules([{
@@ -921,65 +746,55 @@ const Rule = (_a = class {
921
746
  constraint: values
922
747
  }]);
923
748
  }
924
-
925
749
  integer() {
926
750
  return this.cloneWithRules([{
927
751
  flag: "integer"
928
752
  }]);
929
753
  }
930
-
931
754
  precision(limit) {
932
755
  return this.cloneWithRules([{
933
756
  flag: "precision",
934
757
  constraint: limit
935
758
  }]);
936
759
  }
937
-
938
760
  positive() {
939
761
  return this.cloneWithRules([{
940
762
  flag: "min",
941
763
  constraint: 0
942
764
  }]);
943
765
  }
944
-
945
766
  negative() {
946
767
  return this.cloneWithRules([{
947
768
  flag: "lessThan",
948
769
  constraint: 0
949
770
  }]);
950
771
  }
951
-
952
772
  greaterThan(num) {
953
773
  return this.cloneWithRules([{
954
774
  flag: "greaterThan",
955
775
  constraint: num
956
776
  }]);
957
777
  }
958
-
959
778
  lessThan(num) {
960
779
  return this.cloneWithRules([{
961
780
  flag: "lessThan",
962
781
  constraint: num
963
782
  }]);
964
783
  }
965
-
966
784
  uppercase() {
967
785
  return this.cloneWithRules([{
968
786
  flag: "stringCasing",
969
787
  constraint: "uppercase"
970
788
  }]);
971
789
  }
972
-
973
790
  lowercase() {
974
791
  return this.cloneWithRules([{
975
792
  flag: "stringCasing",
976
793
  constraint: "lowercase"
977
794
  }]);
978
795
  }
979
-
980
796
  regex(pattern, a, b) {
981
797
  var _a2, _b;
982
-
983
798
  const name = typeof a === "string" ? a : (_a2 = a == null ? void 0 : a.name) != null ? _a2 : b == null ? void 0 : b.name;
984
799
  const invert = typeof a === "string" ? false : (_b = a == null ? void 0 : a.invert) != null ? _b : b == null ? void 0 : b.invert;
985
800
  const constraint = {
@@ -992,28 +807,23 @@ const Rule = (_a = class {
992
807
  constraint
993
808
  }]);
994
809
  }
995
-
996
810
  email() {
997
811
  return this.cloneWithRules([{
998
812
  flag: "email"
999
813
  }]);
1000
814
  }
1001
-
1002
815
  uri(opts) {
1003
816
  const optsScheme = (opts == null ? void 0 : opts.scheme) || ["http", "https"];
1004
817
  const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme];
1005
-
1006
818
  if (!schemes.length) {
1007
819
  throw new Error("scheme must have at least 1 scheme specified");
1008
820
  }
1009
-
1010
821
  const constraint = {
1011
822
  options: {
1012
823
  scheme: schemes.map(scheme => {
1013
824
  if (!(scheme instanceof RegExp) && typeof scheme !== "string") {
1014
825
  throw new Error("scheme must be a RegExp or a String");
1015
826
  }
1016
-
1017
827
  return typeof scheme === "string" ? new RegExp("^".concat(escapeRegex(scheme), "$")) : scheme;
1018
828
  }),
1019
829
  allowRelative: (opts == null ? void 0 : opts.allowRelative) || false,
@@ -1026,39 +836,32 @@ const Rule = (_a = class {
1026
836
  constraint
1027
837
  }]);
1028
838
  }
1029
-
1030
839
  unique() {
1031
840
  return this.cloneWithRules([{
1032
841
  flag: "unique"
1033
842
  }]);
1034
843
  }
1035
-
1036
844
  reference() {
1037
845
  return this.cloneWithRules([{
1038
846
  flag: "reference"
1039
847
  }]);
1040
848
  }
1041
-
1042
849
  fields(rules) {
1043
850
  if (this._type !== "Object") {
1044
851
  throw new Error("fields() can only be called on an object type");
1045
852
  }
1046
-
1047
853
  const rule = this.cloneWithRules([]);
1048
854
  rule._fieldRules = rules;
1049
855
  return rule;
1050
856
  }
1051
-
1052
857
  assetRequired() {
1053
858
  const base = getBaseType(this._typeDef);
1054
859
  let assetType;
1055
-
1056
860
  if (base && ["image", "file"].includes(base.name)) {
1057
861
  assetType = base.name === "image" ? "Image" : "File";
1058
862
  } else {
1059
863
  assetType = "Asset";
1060
864
  }
1061
-
1062
865
  return this.cloneWithRules([{
1063
866
  flag: "assetRequired",
1064
867
  constraint: {
@@ -1066,80 +869,62 @@ const Rule = (_a = class {
1066
869
  }
1067
870
  }]);
1068
871
  }
1069
-
1070
872
  async validate(value, context) {
1071
873
  if (!context) {
1072
874
  throw new Error("missing context");
1073
875
  }
1074
-
1075
876
  const valueIsEmpty = value === null || value === void 0;
1076
-
1077
877
  if (valueIsEmpty && this._required === "optional") {
1078
878
  return EMPTY_ARRAY;
1079
879
  }
1080
-
1081
880
  const rules = this._required === void 0 && valueIsEmpty ? this._rules.filter(curr => curr.flag === "custom") : this._rules;
1082
881
  const validators = this._type && typeValidators[this._type] || genericValidators;
1083
882
  const results = await Promise.all(rules.map(async curr => {
1084
883
  if (curr.flag === void 0) {
1085
884
  throw new Error('Invalid rule, did not contain "flag"-property');
1086
885
  }
1087
-
1088
886
  const validator = validators[curr.flag];
1089
-
1090
887
  if (!validator) {
1091
888
  const forType = this._type ? "type \"".concat(this._type, "\"") : "rule without declared type";
1092
889
  throw new Error("Validator for flag \"".concat(curr.flag, "\" not found for ").concat(forType));
1093
890
  }
1094
-
1095
891
  let specConstraint = "constraint" in curr ? curr.constraint : null;
1096
-
1097
892
  if (isFieldRef(specConstraint)) {
1098
893
  specConstraint = get(context.parent, specConstraint.path);
1099
894
  }
1100
-
1101
895
  let result;
1102
-
1103
896
  try {
1104
897
  result = await validator(specConstraint, value, this._message, context);
1105
898
  } catch (err) {
1106
899
  const errorFromException = new ValidationError("".concat(pathToString(context.path), ": Exception occurred while validating value: ").concat(err.message));
1107
900
  return convertToValidationMarker(errorFromException, "error", context);
1108
901
  }
1109
-
1110
902
  return convertToValidationMarker(result, this._level, context);
1111
903
  }));
1112
904
  return results.flat();
1113
905
  }
1114
-
1115
906
  }, _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 => ({
1116
907
  type: FIELD_REF,
1117
908
  path
1118
909
  }), _a);
1119
-
1120
910
  const requestIdleCallbackShim = function requestIdleCallbackShim2(callback, options) {
1121
911
  const start = Date.now();
1122
912
  return window.setTimeout(() => {
1123
913
  callback({
1124
914
  didTimeout: false,
1125
-
1126
915
  timeRemaining() {
1127
916
  return Math.max(0, Date.now() - start);
1128
917
  }
1129
-
1130
918
  });
1131
919
  }, 0);
1132
920
  };
1133
-
1134
921
  const cancelIdleCallbackShim = function cancelIdleCallbackShim2(handle) {
1135
922
  return window.clearTimeout(handle);
1136
923
  };
1137
-
1138
924
  const win = typeof window === "undefined" ? void 0 : window;
1139
925
  const requestIdleCallback = (win == null ? void 0 : win.requestIdleCallback) || requestIdleCallbackShim;
1140
926
  const cancelIdleCallback = (win == null ? void 0 : win.cancelIdleCallback) || cancelIdleCallbackShim;
1141
927
  const memoizedWarnOnArraySlug = memoize(warnOnArraySlug);
1142
-
1143
928
  function getDocumentIds(id) {
1144
929
  const isDraft = id.indexOf("drafts.") === 0;
1145
930
  return {
@@ -1147,7 +932,6 @@ function getDocumentIds(id) {
1147
932
  draft: isDraft ? id : "drafts.".concat(id)
1148
933
  };
1149
934
  }
1150
-
1151
935
  function serializePath(path) {
1152
936
  return path.reduce((target, part, i) => {
1153
937
  const isIndex = typeof part === "number";
@@ -1157,7 +941,6 @@ function serializePath(path) {
1157
941
  return "".concat(target).concat(add);
1158
942
  }, "");
1159
943
  }
1160
-
1161
944
  const defaultIsUnique = (slug, context) => {
1162
945
  const {
1163
946
  getClient,
@@ -1166,15 +949,12 @@ const defaultIsUnique = (slug, context) => {
1166
949
  type
1167
950
  } = context;
1168
951
  const schemaOptions = type == null ? void 0 : type.options;
1169
-
1170
952
  if (!document) {
1171
953
  throw new Error("`document` was not provided in validation context.");
1172
954
  }
1173
-
1174
955
  if (!path) {
1175
956
  throw new Error("`path` was not provided in validation context.");
1176
957
  }
1177
-
1178
958
  const disableArrayWarning = (schemaOptions == null ? void 0 : schemaOptions.disableArrayWarning) || false;
1179
959
  const {
1180
960
  published,
@@ -1182,11 +962,9 @@ const defaultIsUnique = (slug, context) => {
1182
962
  } = getDocumentIds(document._id);
1183
963
  const docType = document._type;
1184
964
  const atPath = serializePath(path.concat("current"));
1185
-
1186
965
  if (!disableArrayWarning && atPath.includes("[]")) {
1187
966
  memoizedWarnOnArraySlug(serializePath(path));
1188
967
  }
1189
-
1190
968
  const constraints = ["_type == $docType", "!(_id in [$draft, $published])", "".concat(atPath, " == $slug")].join(" && ");
1191
969
  return getClient({
1192
970
  apiVersion: "2022-09-09"
@@ -1199,46 +977,34 @@ const defaultIsUnique = (slug, context) => {
1199
977
  tag: "validation.slug-is-unique"
1200
978
  });
1201
979
  };
1202
-
1203
980
  function warnOnArraySlug(serializedPath) {
1204
981
  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"));
1205
982
  }
1206
-
1207
983
  const slugValidator = async (value, context) => {
1208
984
  var _a;
1209
-
1210
985
  if (!value) {
1211
986
  return true;
1212
987
  }
1213
-
1214
988
  if (typeof value !== "object") {
1215
989
  return "Slug must be an object";
1216
990
  }
1217
-
1218
991
  const slugValue = value.current;
1219
-
1220
992
  if (!slugValue) {
1221
993
  return "Slug must have a value";
1222
994
  }
1223
-
1224
995
  const options = (_a = context == null ? void 0 : context.type) == null ? void 0 : _a.options;
1225
996
  const isUnique = (options == null ? void 0 : options.isUnique) || defaultIsUnique;
1226
-
1227
997
  const slugContext = _objectSpread(_objectSpread({}, context), {}, {
1228
998
  parent: context.parent,
1229
999
  type: context.type,
1230
1000
  defaultIsUnique
1231
1001
  });
1232
-
1233
1002
  const wasUnique = await isUnique(slugValue, slugContext);
1234
-
1235
1003
  if (wasUnique) {
1236
1004
  return true;
1237
1005
  }
1238
-
1239
1006
  return "Slug is already in use";
1240
1007
  };
1241
-
1242
1008
  const ruleConstraintTypes = {
1243
1009
  array: true,
1244
1010
  boolean: true,
@@ -1247,9 +1013,7 @@ const ruleConstraintTypes = {
1247
1013
  object: true,
1248
1014
  string: true
1249
1015
  };
1250
-
1251
1016
  const isRuleConstraint = typeString => typeString in ruleConstraintTypes;
1252
-
1253
1017
  function getTypeChain(type, visited) {
1254
1018
  if (!type) return [];
1255
1019
  if (visited.has(type)) return [];
@@ -1257,20 +1021,15 @@ function getTypeChain(type, visited) {
1257
1021
  const next = type.type ? getTypeChain(type.type, visited) : [];
1258
1022
  return [...next, type];
1259
1023
  }
1260
-
1261
1024
  function baseRuleReducer(inputRule, type) {
1262
1025
  let baseRule = inputRule;
1263
-
1264
1026
  if (isRuleConstraint(type.jsonType)) {
1265
1027
  baseRule = baseRule.type(type.jsonType);
1266
1028
  }
1267
-
1268
1029
  const typeOptionsList = (type == null ? void 0 : type.options) && typeof type.options === "object" && "list" in type.options && type.options.list;
1269
-
1270
1030
  if (Array.isArray(typeOptionsList)) {
1271
1031
  baseRule = baseRule.valid(typeOptionsList.map(option => extractValueFromListOption(option, type)));
1272
1032
  }
1273
-
1274
1033
  if (type.name === "datetime") return baseRule.type("Date");
1275
1034
  if (type.name === "date") return baseRule.type("Date");
1276
1035
  if (type.name === "url") return baseRule.uri();
@@ -1279,7 +1038,6 @@ function baseRuleReducer(inputRule, type) {
1279
1038
  if (type.name === "email") return baseRule.email();
1280
1039
  return baseRule;
1281
1040
  }
1282
-
1283
1041
  function hasValueField(typeDef) {
1284
1042
  if (!typeDef) return false;
1285
1043
  if (!("fields" in typeDef) && typeDef.type) return hasValueField(typeDef.type);
@@ -1287,79 +1045,58 @@ function hasValueField(typeDef) {
1287
1045
  if (!Array.isArray(typeDef.fields)) return false;
1288
1046
  return typeDef.fields.some(field => field.name === "value");
1289
1047
  }
1290
-
1291
1048
  function extractValueFromListOption(option, typeDef) {
1292
1049
  if (typeDef.jsonType === "object" && hasValueField(typeDef)) return option;
1293
1050
  return option.value === void 0 ? option : option.value;
1294
1051
  }
1295
-
1296
1052
  function normalizeValidationRules(typeDef) {
1297
1053
  if (!typeDef) {
1298
1054
  return [];
1299
1055
  }
1300
-
1301
1056
  const validation = typeDef.validation;
1302
-
1303
1057
  if (Array.isArray(validation)) {
1304
1058
  return validation.flatMap(i => normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
1305
1059
  validation: i
1306
1060
  })));
1307
1061
  }
1308
-
1309
1062
  if (validation instanceof Rule) {
1310
1063
  return [validation];
1311
1064
  }
1312
-
1313
1065
  const baseRule = Object.values(getTypeChain(typeDef, /* @__PURE__ */new Set()).reduce((acc, type) => {
1314
1066
  acc[type.name] = type;
1315
1067
  return acc;
1316
1068
  }, {})).reduce(baseRuleReducer, new Rule(typeDef));
1317
-
1318
1069
  if (!validation) {
1319
1070
  return [baseRule];
1320
1071
  }
1321
-
1322
1072
  return normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
1323
1073
  validation: validation(baseRule)
1324
1074
  }));
1325
1075
  }
1326
-
1327
1076
  const isRecord = maybeRecord => typeof maybeRecord === "object" && maybeRecord !== null && !Array.isArray(maybeRecord);
1328
-
1329
1077
  const isNonNullable = value => value !== null && value !== void 0;
1330
-
1331
1078
  function resolveTypeForArrayItem(item, candidates) {
1332
1079
  if (candidates.length === 1) return candidates[0];
1333
-
1334
1080
  const itemType = isTypedObject(item) && item._type;
1335
-
1336
1081
  const primitive = item === void 0 || item === null || !itemType && typeString(item).toLowerCase();
1337
-
1338
1082
  if (primitive && primitive !== "object") {
1339
1083
  return candidates.find(candidate => candidate.jsonType === primitive);
1340
1084
  }
1341
-
1342
1085
  return candidates.find(candidate => {
1343
1086
  var _a;
1344
-
1345
1087
  return ((_a = candidate.type) == null ? void 0 : _a.name) === itemType;
1346
1088
  }) || candidates.find(candidate => candidate.name === itemType) || candidates.find(candidate => candidate.name === "object" && primitive === "object");
1347
1089
  }
1348
-
1349
1090
  const EMPTY_MARKERS = [];
1350
-
1351
1091
  async function validateDocument(getClient, doc, schema, context) {
1352
1092
  return validateDocumentObservable(getClient, doc, schema, context).toPromise();
1353
1093
  }
1354
-
1355
1094
  function validateDocumentObservable(getClient, doc, schema, context) {
1356
1095
  const documentType = schema.get(doc._type);
1357
-
1358
1096
  if (!documentType) {
1359
1097
  console.warn('Schema type for object type "%s" not found, skipping validation', doc._type);
1360
1098
  return of(EMPTY_MARKERS);
1361
1099
  }
1362
-
1363
1100
  const client = getClient({
1364
1101
  apiVersion: "2021-06-07"
1365
1102
  });
@@ -1382,7 +1119,6 @@ function validateDocumentObservable(getClient, doc, schema, context) {
1382
1119
  console.warn('`configContext.client` is deprecated and will be removed in the next release! Use `context.getClient({apiVersion: "2021-06-07"})` instead');
1383
1120
  return original;
1384
1121
  }
1385
-
1386
1122
  });
1387
1123
  }, {});
1388
1124
  return validateItemObservable(validationOptions).pipe(catchError(err => {
@@ -1395,16 +1131,14 @@ function validateDocumentObservable(getClient, doc, schema, context) {
1395
1131
  }]);
1396
1132
  }));
1397
1133
  }
1398
-
1399
1134
  function validateItemObservable(_ref) {
1400
1135
  let {
1401
- value,
1402
- type,
1403
- path = [],
1404
- parent
1405
- } = _ref,
1406
- restOfContext = _objectWithoutProperties(_ref, _excluded);
1407
-
1136
+ value,
1137
+ type,
1138
+ path = [],
1139
+ parent
1140
+ } = _ref,
1141
+ restOfContext = _objectWithoutProperties(_ref, _excluded);
1408
1142
  const rules = normalizeValidationRules(type);
1409
1143
  const selfChecks = rules.map(rule => defer(() => rule.validate(value, _objectSpread(_objectSpread({}, restOfContext), {}, {
1410
1144
  parent,
@@ -1414,7 +1148,6 @@ function validateItemObservable(_ref) {
1414
1148
  let nestedChecks = [];
1415
1149
  const selfIsRequired = rules.some(rule => rule.isRequired());
1416
1150
  const shouldRunNestedObjectValidation = (type == null ? void 0 : type.jsonType) === "object" && (!!value || (value === null || value === void 0) && selfIsRequired);
1417
-
1418
1151
  if (shouldRunNestedObjectValidation) {
1419
1152
  const fieldTypes = type.fields.reduce((acc, field) => {
1420
1153
  acc[field.name] = field.type;
@@ -1441,22 +1174,18 @@ function validateItemObservable(_ref) {
1441
1174
  type: field.type
1442
1175
  }))));
1443
1176
  }
1444
-
1445
1177
  const shouldRunNestedValidationForArrays = (type == null ? void 0 : type.jsonType) === "array" && Array.isArray(value);
1446
-
1447
1178
  if (shouldRunNestedValidationForArrays) {
1448
- nestedChecks = nestedChecks.concat(value.map(item => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1179
+ nestedChecks = nestedChecks.concat(value.map((item, index) => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1449
1180
  parent: value,
1450
1181
  value: item,
1451
1182
  path: path.concat(isKeyedObject(item) ? {
1452
1183
  _key: item._key
1453
- } : value.indexOf(item)),
1184
+ } : index),
1454
1185
  type: resolveTypeForArrayItem(item, type.of)
1455
1186
  }))));
1456
1187
  }
1457
-
1458
1188
  const shouldRunNestedValidationForMarkDefs = isBlock(value) && value.markDefs.length && isBlockSchemaType(type);
1459
-
1460
1189
  if (shouldRunNestedValidationForMarkDefs) {
1461
1190
  const [spanChildrenField] = type.fields;
1462
1191
  const spanType = spanChildrenField.type.of.find(isSpanSchemaType);
@@ -1473,16 +1202,13 @@ function validateItemObservable(_ref) {
1473
1202
  type: annotations.get(markDef._type)
1474
1203
  }))));
1475
1204
  }
1476
-
1477
1205
  return defer(() => merge([...selfChecks, ...nestedChecks])).pipe(mergeMap(validateNode => concat(idle(), validateNode), 40), mergeAll(), toArray(), map(flatten), map(results => {
1478
1206
  if (rules.some(rule => rule._fieldRules)) {
1479
1207
  return uniqBy(results, rule => JSON.stringify(rule));
1480
1208
  }
1481
-
1482
1209
  return results;
1483
1210
  }));
1484
1211
  }
1485
-
1486
1212
  function idle(timeout) {
1487
1213
  return new Observable(observer => {
1488
1214
  const handle = requestIdleCallback(() => {
@@ -1493,50 +1219,41 @@ function idle(timeout) {
1493
1219
  return () => cancelIdleCallback(handle);
1494
1220
  });
1495
1221
  }
1496
-
1497
1222
  function traverse(typeDef, visited) {
1498
1223
  if (visited.has(typeDef)) {
1499
1224
  return;
1500
1225
  }
1501
-
1502
1226
  visited.add(typeDef);
1503
1227
  typeDef.validation = normalizeValidationRules(typeDef);
1504
-
1505
1228
  if ("fields" in typeDef) {
1506
1229
  for (const field of typeDef.fields) {
1507
1230
  traverse(field.type, visited);
1508
1231
  }
1509
1232
  }
1510
-
1511
1233
  if ("of" in typeDef) {
1512
1234
  for (const candidate of typeDef.of) {
1513
1235
  traverse(candidate, visited);
1514
1236
  }
1515
1237
  }
1516
-
1517
1238
  if (typeDef.annotations) {
1518
1239
  for (const annotation of typeDef.annotations) {
1519
1240
  traverse(annotation, visited);
1520
1241
  }
1521
1242
  }
1522
1243
  }
1523
-
1524
1244
  function inferFromSchemaType(typeDef) {
1525
1245
  traverse(typeDef, /* @__PURE__ */new Set());
1526
1246
  return typeDef;
1527
1247
  }
1528
-
1529
1248
  function inferFromSchema(schema) {
1530
1249
  const typeNames = schema.getTypeNames();
1531
1250
  typeNames.forEach(typeName => {
1532
1251
  const schemaType = schema.get(typeName);
1533
-
1534
1252
  if (schemaType) {
1535
1253
  inferFromSchemaType(schemaType);
1536
1254
  }
1537
1255
  });
1538
1256
  return schema;
1539
1257
  }
1540
-
1541
1258
  export { Rule, inferFromSchema, inferFromSchemaType, validateDocument, validateDocumentObservable };
1542
- //# sourceMappingURL=index.mjs.map
1259
+ //# sourceMappingURL=index.esm.js.map