@sanity/validation 3.1.5-next.43 → 3.1.5-next.44

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