@sanity/validation 3.0.0-dev-preview.22 → 3.0.0-findability.53

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