@sanity/validation 2.34.0 → 3.0.0-canary.186

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.
Files changed (90) hide show
  1. package/lib/dts/src/index.d.ts +36 -0
  2. package/lib/index.js +1543 -36
  3. package/lib/index.js.map +1 -0
  4. package/lib/index.mjs +1542 -0
  5. package/lib/index.mjs.map +1 -0
  6. package/package.json +26 -11
  7. package/src/Rule.ts +6 -2
  8. package/src/index.ts +1 -1
  9. package/src/inferFromSchema.ts +7 -1
  10. package/src/util/convertToValidationMarker.ts +5 -3
  11. package/src/util/requestIdleCallback.ts +4 -2
  12. package/src/validateDocument.test.ts +35 -24
  13. package/src/validateDocument.ts +48 -16
  14. package/src/validators/dateValidator.ts +4 -4
  15. package/src/validators/slugValidator.ts +19 -5
  16. package/src/validators/stringValidator.ts +2 -1
  17. package/dist/dts/Rule.d.ts +0 -4
  18. package/dist/dts/Rule.d.ts.map +0 -1
  19. package/dist/dts/ValidationError.d.ts +0 -4
  20. package/dist/dts/ValidationError.d.ts.map +0 -1
  21. package/dist/dts/getClient.d.ts +0 -3
  22. package/dist/dts/getClient.d.ts.map +0 -1
  23. package/dist/dts/index.d.ts +0 -14
  24. package/dist/dts/index.d.ts.map +0 -1
  25. package/dist/dts/inferFromSchema.d.ts +0 -4
  26. package/dist/dts/inferFromSchema.d.ts.map +0 -1
  27. package/dist/dts/inferFromSchemaType.d.ts +0 -5
  28. package/dist/dts/inferFromSchemaType.d.ts.map +0 -1
  29. package/dist/dts/util/convertToValidationMarker.d.ts +0 -6
  30. package/dist/dts/util/convertToValidationMarker.d.ts.map +0 -1
  31. package/dist/dts/util/deepEquals.d.ts +0 -6
  32. package/dist/dts/util/deepEquals.d.ts.map +0 -1
  33. package/dist/dts/util/escapeRegex.d.ts +0 -3
  34. package/dist/dts/util/escapeRegex.d.ts.map +0 -1
  35. package/dist/dts/util/normalizeValidationRules.d.ts +0 -6
  36. package/dist/dts/util/normalizeValidationRules.d.ts.map +0 -1
  37. package/dist/dts/util/normalizeValidationRules.test.d.ts +0 -2
  38. package/dist/dts/util/normalizeValidationRules.test.d.ts.map +0 -1
  39. package/dist/dts/util/pathToString.d.ts +0 -3
  40. package/dist/dts/util/pathToString.d.ts.map +0 -1
  41. package/dist/dts/util/requestIdleCallback.d.ts +0 -3
  42. package/dist/dts/util/requestIdleCallback.d.ts.map +0 -1
  43. package/dist/dts/util/typeString.d.ts +0 -2
  44. package/dist/dts/util/typeString.d.ts.map +0 -1
  45. package/dist/dts/util/typeString.test.d.ts +0 -2
  46. package/dist/dts/util/typeString.test.d.ts.map +0 -1
  47. package/dist/dts/validateDocument.d.ts +0 -24
  48. package/dist/dts/validateDocument.d.ts.map +0 -1
  49. package/dist/dts/validateDocument.test.d.ts +0 -2
  50. package/dist/dts/validateDocument.test.d.ts.map +0 -1
  51. package/dist/dts/validators/arrayValidator.d.ts +0 -4
  52. package/dist/dts/validators/arrayValidator.d.ts.map +0 -1
  53. package/dist/dts/validators/booleanValidator.d.ts +0 -4
  54. package/dist/dts/validators/booleanValidator.d.ts.map +0 -1
  55. package/dist/dts/validators/dateValidator.d.ts +0 -5
  56. package/dist/dts/validators/dateValidator.d.ts.map +0 -1
  57. package/dist/dts/validators/genericValidator.d.ts +0 -4
  58. package/dist/dts/validators/genericValidator.d.ts.map +0 -1
  59. package/dist/dts/validators/numberValidator.d.ts +0 -4
  60. package/dist/dts/validators/numberValidator.d.ts.map +0 -1
  61. package/dist/dts/validators/objectValidator.d.ts +0 -4
  62. package/dist/dts/validators/objectValidator.d.ts.map +0 -1
  63. package/dist/dts/validators/slugValidator.d.ts +0 -9
  64. package/dist/dts/validators/slugValidator.d.ts.map +0 -1
  65. package/dist/dts/validators/stringValidator.d.ts +0 -4
  66. package/dist/dts/validators/stringValidator.d.ts.map +0 -1
  67. package/jest.config.js +0 -5
  68. package/lib/Rule.js +0 -491
  69. package/lib/ValidationError.js +0 -39
  70. package/lib/getClient.js +0 -20
  71. package/lib/inferFromSchema.js +0 -22
  72. package/lib/inferFromSchemaType.js +0 -86
  73. package/lib/util/convertToValidationMarker.js +0 -65
  74. package/lib/util/deepEquals.js +0 -87
  75. package/lib/util/escapeRegex.js +0 -14
  76. package/lib/util/normalizeValidationRules.js +0 -115
  77. package/lib/util/pathToString.js +0 -30
  78. package/lib/util/requestIdleCallback.js +0 -35
  79. package/lib/util/typeString.js +0 -29
  80. package/lib/validateDocument.js +0 -242
  81. package/lib/validators/arrayValidator.js +0 -123
  82. package/lib/validators/booleanValidator.js +0 -29
  83. package/lib/validators/dateValidator.js +0 -120
  84. package/lib/validators/genericValidator.js +0 -135
  85. package/lib/validators/numberValidator.js +0 -70
  86. package/lib/validators/objectValidator.js +0 -93
  87. package/lib/validators/slugValidator.js +0 -133
  88. package/lib/validators/stringValidator.js +0 -131
  89. package/src/getClient.ts +0 -13
  90. package/tsconfig.json +0 -10
@@ -1,65 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = convertToValidationMarker;
7
- exports.isNonNullable = isNonNullable;
8
-
9
- var _ValidationError = _interopRequireDefault(require("../ValidationError"));
10
-
11
- var _pathToString = _interopRequireDefault(require("../util/pathToString"));
12
-
13
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
-
15
- function isNonNullable(t) {
16
- return t !== null || t !== undefined;
17
- }
18
-
19
- function convertToValidationMarker(validatorResult, level, context) {
20
- var _validatorResult$path;
21
-
22
- if (validatorResult === true) return [];
23
-
24
- if (Array.isArray(validatorResult)) {
25
- return validatorResult.flatMap(child => convertToValidationMarker(child, level, context)).filter(isNonNullable);
26
- }
27
-
28
- if (typeof validatorResult === 'string') {
29
- return convertToValidationMarker(new _ValidationError.default(validatorResult), level, context);
30
- }
31
-
32
- if (!(validatorResult instanceof _ValidationError.default)) {
33
- // in order to accept the `ValidationErrorLike`, it at least needs to have
34
- // a `message` in the object
35
- if (typeof (validatorResult === null || validatorResult === void 0 ? void 0 : validatorResult.message) !== 'string') {
36
- throw new Error("".concat((0, _pathToString.default)(context.path), ": Validator must return 'true' if valid or an error message as a string on errors"));
37
- } // this is the occurs when an object is returned that wasn't created with the
38
- // `ValidationErrorClass`. in this case, we want to convert it to a class
39
-
40
-
41
- return convertToValidationMarker(new _ValidationError.default(validatorResult.message, validatorResult), level, context);
42
- }
43
-
44
- var results = []; // the validator result does not include any item-level relative paths,
45
- // then just return the top-level path with the validation result
46
-
47
- if (!((_validatorResult$path = validatorResult.paths) !== null && _validatorResult$path !== void 0 && _validatorResult$path.length)) {
48
- return [{
49
- type: 'validation',
50
- level: level || 'error',
51
- item: validatorResult,
52
- path: context.path || []
53
- }];
54
- } // if the validator result did include item-level relative paths, then for
55
- // each item-level relative path, create a validation marker that concatenates
56
- // the relative path with the path from the validation context
57
-
58
-
59
- return results.concat(validatorResult.paths.map(path => ({
60
- type: 'validation',
61
- path: (context.path || []).concat(path),
62
- level: level || 'error',
63
- item: validatorResult
64
- })));
65
- }
@@ -1,87 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = deepEquals;
7
-
8
- /**
9
- * Modified version of fast-deep-equal (https://github.com/epoberezkin/fast-deep-equal)
10
- * MIT-licensed, copyright (c) 2017 Evgeny Poberezkin
11
- **/
12
- // NOTE: when converting to typescript, some of the checks were inlined (vs
13
- // having them in a variable) because the type predicate type narrowing only
14
- // works when type predicate is called inline in the condition that starts the
15
- // control flow branch.
16
- // see here: https://www.typescriptlang.org/docs/handbook/2/narrowing.html
17
- function deepEquals(a, b) {
18
- if (a === b) {
19
- return true;
20
- }
21
-
22
- if (Array.isArray(a) && Array.isArray(b)) {
23
- if (a.length != b.length) return false;
24
-
25
- for (var i = 0; i < a.length; i++) {
26
- if (!deepEquals(a[i], b[i])) {
27
- return false;
28
- }
29
- }
30
-
31
- return true;
32
- }
33
-
34
- if (Array.isArray(a) != Array.isArray(b)) {
35
- return false;
36
- }
37
-
38
- if (a && b && typeof a === 'object' && typeof b === 'object') {
39
- var keys = Object.keys(a);
40
-
41
- if (keys.length !== Object.keys(b).length) {
42
- return false;
43
- }
44
-
45
- if (a instanceof Date && b instanceof Date) {
46
- return a.getTime() === b.getTime();
47
- }
48
-
49
- if (a instanceof Date != b instanceof Date) {
50
- return false;
51
- }
52
-
53
- if (a instanceof RegExp && b instanceof RegExp) {
54
- return a.toString() == b.toString();
55
- }
56
-
57
- if (a instanceof RegExp != b instanceof RegExp) {
58
- return false;
59
- }
60
-
61
- for (var _i = 0; _i < keys.length; _i++) {
62
- if (keys[_i] === '_key') {
63
- continue;
64
- }
65
-
66
- if (!Object.prototype.hasOwnProperty.call(b, keys[_i])) {
67
- return false;
68
- }
69
- }
70
-
71
- for (var _i2 = 0; _i2 < keys.length; _i2++) {
72
- var key = keys[_i2];
73
-
74
- if (key === '_key') {
75
- continue;
76
- }
77
-
78
- if (!deepEquals(a[key], b[key])) {
79
- return false;
80
- }
81
- }
82
-
83
- return true;
84
- }
85
-
86
- return false;
87
- }
@@ -1,14 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
-
8
- /* eslint-disable no-useless-escape */
9
- var _default = string => {
10
- // Escape ^$.*+-?=!:|\/()[]{},
11
- return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
12
- };
13
-
14
- exports.default = _default;
@@ -1,115 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = normalizeValidationRules;
7
-
8
- var _Rule = _interopRequireDefault(require("../Rule"));
9
-
10
- var _slugValidator = require("../validators/slugValidator");
11
-
12
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
-
14
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
15
-
16
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
17
-
18
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
19
-
20
- var ruleConstraintTypes = {
21
- array: true,
22
- boolean: true,
23
- date: true,
24
- number: true,
25
- object: true,
26
- string: true
27
- };
28
-
29
- var isRuleConstraint = typeString => typeString in ruleConstraintTypes;
30
-
31
- function getTypeChain(type, visited) {
32
- if (!type) return [];
33
- if (visited.has(type)) return [];
34
- visited.add(type);
35
- var next = type.type ? getTypeChain(type.type, visited) : [];
36
- return [...next, type];
37
- }
38
-
39
- function baseRuleReducer(inputRule, type) {
40
- var baseRule = inputRule;
41
-
42
- if (isRuleConstraint(type.jsonType)) {
43
- baseRule = baseRule.type(type.jsonType);
44
- }
45
-
46
- var typeOptionsList = // if type.options is truthy
47
- (type === null || type === void 0 ? void 0 : type.options) && // and type.options is an object (non-null from the previous)
48
- typeof type.options === 'object' && // and if `list` is in options
49
- 'list' in type.options && // then finally access the list
50
- type.options.list;
51
-
52
- if (Array.isArray(typeOptionsList)) {
53
- baseRule = baseRule.valid(typeOptionsList.map(option => extractValueFromListOption(option, type)));
54
- }
55
-
56
- if (type.name === 'datetime') return baseRule.type('Date');
57
- if (type.name === 'date') return baseRule.type('Date');
58
- if (type.name === 'url') return baseRule.uri();
59
- if (type.name === 'slug') return baseRule.custom(_slugValidator.slugValidator);
60
- if (type.name === 'reference') return baseRule.reference();
61
- if (type.name === 'email') return baseRule.email();
62
- return baseRule;
63
- }
64
-
65
- function hasValueField(typeDef) {
66
- if (!typeDef) return false;
67
- if (!('fields' in typeDef) && typeDef.type) return hasValueField(typeDef.type);
68
- if (!('fields' in typeDef)) return false;
69
- if (!Array.isArray(typeDef.fields)) return false;
70
- return typeDef.fields.some(field => field.name === 'value');
71
- }
72
-
73
- function extractValueFromListOption(option, typeDef) {
74
- // If you define a `list` option with object items, where the item has a `value` field,
75
- // we don't want to treat that as the value but rather the surrounding object
76
- // This differs from the case where you have a title/value pair setup for a string/number, for instance
77
- if (typeDef.jsonType === 'object' && hasValueField(typeDef)) return option;
78
- return option.value === undefined ? option : option.value;
79
- }
80
- /**
81
- * Takes in `SchemaValidationValue` and returns an array of `Rule` instances.
82
- */
83
-
84
-
85
- function normalizeValidationRules(typeDef) {
86
- if (!typeDef) {
87
- return [];
88
- }
89
-
90
- var validation = typeDef.validation;
91
-
92
- if (Array.isArray(validation)) {
93
- return validation.flatMap(i => normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
94
- validation: i
95
- })));
96
- }
97
-
98
- if (validation instanceof _Rule.default) {
99
- return [validation];
100
- }
101
-
102
- var baseRule = // using an object + Object.values to de-dupe the type chain by type name
103
- Object.values(getTypeChain(typeDef, new Set()).reduce((acc, type) => {
104
- acc[type.name] = type;
105
- return acc;
106
- }, {})).reduce(baseRuleReducer, new _Rule.default(typeDef));
107
-
108
- if (!validation) {
109
- return [baseRule];
110
- }
111
-
112
- return normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
113
- validation: validation(baseRule)
114
- }));
115
- }
@@ -1,30 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = pathToString;
7
-
8
- var _types = require("@sanity/types");
9
-
10
- function pathToString() {
11
- var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
12
- return path.reduce((target, segment, i) => {
13
- var segmentType = typeof segment;
14
-
15
- if (segmentType === 'number') {
16
- return "".concat(target, "[").concat(segment, "]");
17
- }
18
-
19
- if (segmentType === 'string') {
20
- var separator = i === 0 ? '' : '.';
21
- return "".concat(target).concat(separator).concat(segment);
22
- }
23
-
24
- if ((0, _types.isKeyedObject)(segment)) {
25
- return "".concat(target, "[_key==\"").concat(segment._key, "\"]");
26
- }
27
-
28
- throw new Error("Unsupported path segment \"".concat(segment, "\""));
29
- }, '');
30
- }
@@ -1,35 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.requestIdleCallback = exports.cancelIdleCallback = void 0;
7
-
8
- /**
9
- * Simple requestIdleCallback polyfill
10
- * Can be removed when all browsers support requestIdleCallback: https://caniuse.com/requestidlecallback
11
- * @param callback
12
- * @param options
13
- */
14
- var requestIdleCallbackShim = function requestIdleCallbackShim(callback, options) {
15
- var start = Date.now();
16
- return window.setTimeout(() => {
17
- callback({
18
- didTimeout: false,
19
-
20
- timeRemaining() {
21
- return Math.max(0, Date.now() - start);
22
- }
23
-
24
- });
25
- }, 0);
26
- };
27
-
28
- var cancelIdleCallbackShim = function cancelIdleCallbackShim(handle) {
29
- return window.clearTimeout(handle);
30
- };
31
-
32
- var requestIdleCallback = window.requestIdleCallback || requestIdleCallbackShim;
33
- exports.requestIdleCallback = requestIdleCallback;
34
- var cancelIdleCallback = window.cancelIdleCallback || cancelIdleCallbackShim;
35
- exports.cancelIdleCallback = cancelIdleCallback;
@@ -1,29 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = typeString;
7
- // this file was adapted from a previous dependency `type-of-is`
8
- // https://github.com/stephenhandley/type-of-is/blob/7138a7e79f5af7c286bf8123f60843a91aaebf38/index.js
9
- var _toString = {}.toString;
10
- var builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error];
11
-
12
- function isBuiltIn(_constructor) {
13
- for (var i = 0; i < builtIns.length; i++) {
14
- if (builtIns[i] === _constructor) return true;
15
- }
16
-
17
- return false;
18
- }
19
-
20
- function typeString(obj) {
21
- // [object Blah] -> Blah
22
- var stringType = _toString.call(obj).slice(8, -1);
23
-
24
- if (obj === null || obj === undefined) return stringType.toLowerCase(); // eslint-disable-next-line @typescript-eslint/ban-types
25
-
26
- var constructorType = obj.constructor;
27
- if (constructorType && !isBuiltIn(constructorType)) return constructorType.name;
28
- return stringType;
29
- }
@@ -1,242 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = validateDocument;
7
- exports.resolveTypeForArrayItem = resolveTypeForArrayItem;
8
- exports.validateDocumentObservable = validateDocumentObservable;
9
- exports.validateItem = validateItem;
10
-
11
- var _uniqBy2 = _interopRequireDefault(require("lodash/uniqBy"));
12
-
13
- var _flatten2 = _interopRequireDefault(require("lodash/flatten"));
14
-
15
- var _types = require("@sanity/types");
16
-
17
- var _rxjs = require("rxjs");
18
-
19
- var _operators = require("rxjs/operators");
20
-
21
- var _typeString = _interopRequireDefault(require("./util/typeString"));
22
-
23
- var _requestIdleCallback = require("./util/requestIdleCallback");
24
-
25
- var _ValidationError = _interopRequireDefault(require("./ValidationError"));
26
-
27
- var _normalizeValidationRules = _interopRequireDefault(require("./util/normalizeValidationRules"));
28
-
29
- var _excluded = ["value", "type", "path", "parent"];
30
-
31
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
32
-
33
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
34
-
35
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
36
-
37
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
38
-
39
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
40
-
41
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
42
-
43
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
44
-
45
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
46
-
47
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
48
-
49
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
50
-
51
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
52
-
53
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
54
-
55
- var isRecord = maybeRecord => typeof maybeRecord === 'object' && maybeRecord !== null && !Array.isArray(maybeRecord);
56
-
57
- var isNonNullable = value => value !== null && value !== undefined;
58
- /**
59
- * @internal
60
- */
61
-
62
-
63
- function resolveTypeForArrayItem(item, candidates) {
64
- // if there is only one type available, assume that it's the correct one
65
- if (candidates.length === 1) return candidates[0];
66
-
67
- var itemType = (0, _types.isTypedObject)(item) && item._type;
68
-
69
- var primitive = item === undefined || item === null || !itemType && (0, _typeString.default)(item).toLowerCase();
70
-
71
- if (primitive && primitive !== 'object') {
72
- return candidates.find(candidate => candidate.jsonType === primitive);
73
- }
74
-
75
- return candidates.find(candidate => {
76
- var _candidate$type;
77
-
78
- return ((_candidate$type = candidate.type) === null || _candidate$type === void 0 ? void 0 : _candidate$type.name) === itemType;
79
- }) || candidates.find(candidate => candidate.name === itemType) || candidates.find(candidate => candidate.name === 'object' && primitive === 'object');
80
- }
81
-
82
- var EMPTY_MARKERS = [];
83
-
84
- function validateDocument(doc, schema, context) {
85
- return validateDocumentObservable(doc, schema, context).toPromise();
86
- }
87
-
88
- function validateDocumentObservable(doc, schema, context) {
89
- var documentType = schema.get(doc._type);
90
-
91
- if (!documentType) {
92
- console.warn('Schema type for object type "%s" not found, skipping validation', doc._type);
93
- return (0, _rxjs.of)(EMPTY_MARKERS);
94
- }
95
-
96
- return validateItemObservable({
97
- parent: undefined,
98
- value: doc,
99
- path: [],
100
- document: doc,
101
- type: documentType,
102
- getDocumentExists: context === null || context === void 0 ? void 0 : context.getDocumentExists
103
- }).pipe((0, _operators.catchError)(err => {
104
- console.error(err);
105
- return (0, _rxjs.of)([{
106
- type: 'validation',
107
- level: 'error',
108
- path: [],
109
- item: new _ValidationError.default(err === null || err === void 0 ? void 0 : err.message)
110
- }]);
111
- }));
112
- }
113
- /**
114
- * this is used make optional properties required by replacing optionals with
115
- * `T[P] | undefined`. this is used to prevent errors in `validateItem` where
116
- * an option from a previous invocation would be incorrectly passed down.
117
- *
118
- * https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585
119
- */
120
-
121
-
122
- function validateItem(opts) {
123
- return validateItemObservable(opts).toPromise();
124
- }
125
-
126
- function validateItemObservable(_ref) {
127
- var value = _ref.value,
128
- type = _ref.type,
129
- _ref$path = _ref.path,
130
- path = _ref$path === void 0 ? [] : _ref$path,
131
- parent = _ref.parent,
132
- restOfContext = _objectWithoutProperties(_ref, _excluded);
133
-
134
- var rules = (0, _normalizeValidationRules.default)(type); // run validation for the current value
135
-
136
- var selfChecks = rules.map(rule => (0, _rxjs.defer)(() => rule.validate(value, _objectSpread(_objectSpread({}, restOfContext), {}, {
137
- parent,
138
- path,
139
- type
140
- })))); // run validation for nested values (conditionally)
141
-
142
- var fieldChecks = [];
143
- var selfIsRequired = rules.some(rule => rule.isRequired());
144
- var shouldRunNestedObjectValidation = // run nested validation for objects
145
- (type === null || type === void 0 ? void 0 : type.jsonType) === 'object' && ( // if the value is truthy
146
- !!value || // or
147
- // (the value is null or undefined) and the top-level value is required
148
- (value === null || value === undefined) && selfIsRequired);
149
-
150
- if (shouldRunNestedObjectValidation) {
151
- var fieldTypes = type.fields.reduce((acc, field) => {
152
- acc[field.name] = field.type;
153
- return acc;
154
- }, {}); // Validation for rules set at the object level with `Rule.fields({/* ... */})`
155
-
156
- fieldChecks = fieldChecks.concat(rules.map(rule => rule._fieldRules).filter(isNonNullable).flatMap(fieldResults => Object.entries(fieldResults)).flatMap(_ref2 => {
157
- var _ref3 = _slicedToArray(_ref2, 2),
158
- name = _ref3[0],
159
- validation = _ref3[1];
160
-
161
- var fieldType = fieldTypes[name];
162
- return (0, _normalizeValidationRules.default)(_objectSpread(_objectSpread({}, fieldType), {}, {
163
- validation
164
- })).map(subRule => {
165
- var nestedValue = isRecord(value) ? value[name] : undefined;
166
- return (0, _rxjs.defer)(() => subRule.validate(nestedValue, _objectSpread(_objectSpread({}, restOfContext), {}, {
167
- parent: value,
168
- path: path.concat(name),
169
- type: fieldType
170
- })));
171
- });
172
- })); // Validation from each field's schema `validation: Rule => {/* ... */}` function
173
-
174
- fieldChecks = fieldChecks.concat(type.fields.map(field => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
175
- parent: value,
176
- value: isRecord(value) ? value[field.name] : undefined,
177
- path: path.concat(field.name),
178
- type: field.type
179
- }))));
180
- } // note: unlike objects, arrays should not run nested validation for undefined
181
- // values because we won't have a valid path to put a marker (i.e. missing the
182
- // key or index in the path) and the downstream form builder won't have a
183
- // valid target component
184
-
185
-
186
- var shouldRunNestedValidationForArrays = (type === null || type === void 0 ? void 0 : type.jsonType) === 'array' && Array.isArray(value);
187
-
188
- if (shouldRunNestedValidationForArrays) {
189
- fieldChecks = fieldChecks.concat(value.map(item => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
190
- parent: value,
191
- value: item,
192
- path: path.concat((0, _types.isKeyedObject)(item) ? {
193
- _key: item._key
194
- } : value.indexOf(item)),
195
- type: resolveTypeForArrayItem(item, type.of)
196
- }))));
197
- } // markDefs also do no run nested validation if the parent object is undefined
198
- // for a similar reason to arrays
199
-
200
-
201
- var shouldRunNestedValidationForMarkDefs = (0, _types.isBlock)(value) && value.markDefs.length && (0, _types.isBlockSchemaType)(type);
202
-
203
- if (shouldRunNestedValidationForMarkDefs) {
204
- var _type$fields = _slicedToArray(type.fields, 1),
205
- spanChildrenField = _type$fields[0];
206
-
207
- var spanType = spanChildrenField.type.of.find(_types.isSpanSchemaType);
208
- var annotations = ((spanType === null || spanType === void 0 ? void 0 : spanType.annotations) || []).reduce((acc, annotationType) => {
209
- acc.set(annotationType.name, annotationType);
210
- return acc;
211
- }, new Map());
212
- fieldChecks = fieldChecks.concat(value.markDefs.map(markDef => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
213
- parent: value,
214
- value: markDef,
215
- path: path.concat(['markDefs', {
216
- _key: markDef._key
217
- }]),
218
- type: annotations.get(markDef._type)
219
- }))));
220
- }
221
-
222
- return (0, _rxjs.defer)(() => (0, _rxjs.merge)([...selfChecks, ...fieldChecks])).pipe((0, _operators.mergeMap)(validateNode => (0, _rxjs.concat)(idle(), validateNode), 40), (0, _operators.mergeAll)(), (0, _operators.toArray)(), (0, _operators.map)(_flatten2.default), (0, _operators.map)(results => {
223
- // run `uniqBy` if `_fieldRules` are present because they can
224
- // cause repeat markers
225
- if (rules.some(rule => rule._fieldRules)) {
226
- return (0, _uniqBy2.default)(results, rule => JSON.stringify(rule));
227
- }
228
-
229
- return results;
230
- }));
231
- }
232
-
233
- function idle(timeout) {
234
- return new _rxjs.Observable(observer => {
235
- var handle = (0, _requestIdleCallback.requestIdleCallback)(() => {
236
- observer.complete();
237
- }, timeout ? {
238
- timeout
239
- } : undefined);
240
- return () => (0, _requestIdleCallback.cancelIdleCallback)(handle);
241
- });
242
- }