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