@sanity/validation 2.33.3-performance-opts.9 → 2.33.3-performance-opts.14

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.
@@ -10,4 +10,5 @@ declare const _default: {
10
10
  };
11
11
  export default _default;
12
12
  export { RuleClass as Rule, validateDocument, inferFromSchema, inferFromSchemaType };
13
+ export { validateDocumentObservable } from './validateDocument';
13
14
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,QAAQ,CAAA;AAC9B,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AACjD,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,mBAAmB,MAAM,uBAAuB,CAAA;;;;;;;AAEvD,wBAAwF;AACxF,OAAO,EAAC,SAAS,IAAI,IAAI,EAAE,gBAAgB,EAAE,eAAe,EAAE,mBAAmB,EAAC,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,QAAQ,CAAA;AAC9B,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AACjD,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,mBAAmB,MAAM,uBAAuB,CAAA;;;;;;;AAEvD,wBAAwF;AACxF,OAAO,EAAC,SAAS,IAAI,IAAI,EAAE,gBAAgB,EAAE,eAAe,EAAE,mBAAmB,EAAC,CAAA;AAElF,OAAO,EAAC,0BAA0B,EAAC,MAAM,oBAAoB,CAAA"}
@@ -0,0 +1,9 @@
1
+ export declare const requestIdleCallback: {
2
+ (callback: IdleRequestCallback, options?: IdleRequestOptions | undefined): number;
3
+ (callback: (deadline: IdleDeadline) => void, options?: IdleRequestOptions | undefined): number;
4
+ } & typeof globalThis.requestIdleCallback;
5
+ export declare const cancelIdleCallback: {
6
+ (handle: number): void;
7
+ (handle: number): void;
8
+ } & typeof globalThis.cancelIdleCallback;
9
+ //# sourceMappingURL=requestIdleCallback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestIdleCallback.d.ts","sourceRoot":"","sources":["../../../src/util/requestIdleCallback.ts"],"names":[],"mappings":"AA2BA,eAAO,MAAM,mBAAmB;;;yCAAwD,CAAA;AACxF,eAAO,MAAM,kBAAkB;;;wCAAsD,CAAA"}
@@ -4,7 +4,8 @@ import { Observable } from 'rxjs';
4
4
  * @internal
5
5
  */
6
6
  export declare function resolveTypeForArrayItem(item: unknown, candidates: SchemaType[]): SchemaType | undefined;
7
- export default function validateDocument(doc: SanityDocument, schema: Schema, context?: Pick<ValidationContext, 'getDocumentExists'>): Observable<ValidationMarker[]>;
7
+ export default function validateDocument(doc: SanityDocument, schema: Schema, context?: Pick<ValidationContext, 'getDocumentExists'>): Promise<ValidationMarker[]>;
8
+ export declare function validateDocumentObservable(doc: SanityDocument, schema: Schema, context?: Pick<ValidationContext, 'getDocumentExists'>): Observable<ValidationMarker[]>;
8
9
  /**
9
10
  * this is used make optional properties required by replacing optionals with
10
11
  * `T[P] | undefined`. this is used to prevent errors in `validateItem` where
@@ -18,6 +19,6 @@ declare type ExplicitUndefined<T> = {
18
19
  declare type ValidateItemOptions = {
19
20
  value: unknown;
20
21
  } & ExplicitUndefined<ValidationContext>;
21
- export declare function validateItem({ value, type, path, parent, ...restOfContext }: ValidateItemOptions): Observable<ValidationMarker[]>;
22
+ export declare function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]>;
22
23
  export {};
23
24
  //# sourceMappingURL=validateDocument.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validateDocument.d.ts","sourceRoot":"","sources":["../../src/validateDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,cAAc,EACd,MAAM,EACN,UAAU,EACV,iBAAiB,EACjB,gBAAgB,EACjB,MAAM,eAAe,CAAA;AACtB,OAAO,EAAuB,UAAU,EAAK,MAAM,MAAM,CAAA;AAuBzD;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,OAAO,EACb,UAAU,EAAE,UAAU,EAAE,GACvB,UAAU,GAAG,SAAS,CAiBxB;AAGD,MAAM,CAAC,OAAO,UAAU,gBAAgB,CACtC,GAAG,EAAE,cAAc,EACnB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,mBAAmB,CAAC,GACrD,UAAU,CAAC,gBAAgB,EAAE,CAAC,CA2BhC;AAED;;;;;;GAMG;AACH,aAAK,iBAAiB,CAAC,CAAC,IAAI;KACzB,CAAC,IAAI,MAAM,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,SAAS,QAAQ,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS;CAC5F,CAAA;AAED,aAAK,mBAAmB,GAAG;IACzB,KAAK,EAAE,OAAO,CAAA;CACf,GAAG,iBAAiB,CAAC,iBAAiB,CAAC,CAAA;AAExC,wBAAgB,YAAY,CAAC,EAC3B,KAAK,EACL,IAAI,EACJ,IAAS,EACT,MAAM,EACN,GAAG,aAAa,EACjB,EAAE,mBAAmB,GAAG,UAAU,CAAC,gBAAgB,EAAE,CAAC,CAsItD"}
1
+ {"version":3,"file":"validateDocument.d.ts","sourceRoot":"","sources":["../../src/validateDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,cAAc,EACd,MAAM,EACN,UAAU,EACV,iBAAiB,EACjB,gBAAgB,EACjB,MAAM,eAAe,CAAA;AACtB,OAAO,EAAuB,UAAU,EAAK,MAAM,MAAM,CAAA;AAczD;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,OAAO,EACb,UAAU,EAAE,UAAU,EAAE,GACvB,UAAU,GAAG,SAAS,CAiBxB;AAGD,MAAM,CAAC,OAAO,UAAU,gBAAgB,CACtC,GAAG,EAAE,cAAc,EACnB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,mBAAmB,CAAC,GACrD,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAE7B;AAED,wBAAgB,0BAA0B,CACxC,GAAG,EAAE,cAAc,EACnB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,mBAAmB,CAAC,GACrD,UAAU,CAAC,gBAAgB,EAAE,CAAC,CA2BhC;AAED;;;;;;GAMG;AACH,aAAK,iBAAiB,CAAC,CAAC,IAAI;KACzB,CAAC,IAAI,MAAM,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,SAAS,QAAQ,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS;CAC5F,CAAA;AAED,aAAK,mBAAmB,GAAG;IACzB,KAAK,EAAE,OAAO,CAAA;CACf,GAAG,iBAAiB,CAAC,iBAAiB,CAAC,CAAA;AAExC,wBAAgB,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAEnF"}
package/lib/index.js CHANGED
@@ -28,15 +28,25 @@ Object.defineProperty(exports, "validateDocument", {
28
28
  return _validateDocument.default;
29
29
  }
30
30
  });
31
+ Object.defineProperty(exports, "validateDocumentObservable", {
32
+ enumerable: true,
33
+ get: function get() {
34
+ return _validateDocument.validateDocumentObservable;
35
+ }
36
+ });
31
37
 
32
38
  var _Rule = _interopRequireDefault(require("./Rule"));
33
39
 
34
- var _validateDocument = _interopRequireDefault(require("./validateDocument"));
40
+ var _validateDocument = _interopRequireWildcard(require("./validateDocument"));
35
41
 
36
42
  var _inferFromSchema = _interopRequireDefault(require("./inferFromSchema"));
37
43
 
38
44
  var _inferFromSchemaType = _interopRequireDefault(require("./inferFromSchemaType"));
39
45
 
46
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
47
+
48
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
49
+
40
50
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
41
51
 
42
52
  var _default = {
@@ -0,0 +1,35 @@
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;
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = validateDocument;
7
7
  exports.resolveTypeForArrayItem = resolveTypeForArrayItem;
8
+ exports.validateDocumentObservable = validateDocumentObservable;
8
9
  exports.validateItem = validateItem;
9
10
 
10
11
  var _uniqBy2 = _interopRequireDefault(require("lodash/uniqBy"));
@@ -19,6 +20,8 @@ var _operators = require("rxjs/operators");
19
20
 
20
21
  var _typeString = _interopRequireDefault(require("./util/typeString"));
21
22
 
23
+ var _requestIdleCallback = require("./util/requestIdleCallback");
24
+
22
25
  var _ValidationError = _interopRequireDefault(require("./ValidationError"));
23
26
 
24
27
  var _normalizeValidationRules = _interopRequireDefault(require("./util/normalizeValidationRules"));
@@ -79,6 +82,10 @@ function resolveTypeForArrayItem(item, candidates) {
79
82
  var EMPTY_MARKERS = [];
80
83
 
81
84
  function validateDocument(doc, schema, context) {
85
+ return validateDocumentObservable(doc, schema, context).toPromise();
86
+ }
87
+
88
+ function validateDocumentObservable(doc, schema, context) {
82
89
  var documentType = schema.get(doc._type);
83
90
 
84
91
  if (!documentType) {
@@ -86,7 +93,7 @@ function validateDocument(doc, schema, context) {
86
93
  return (0, _rxjs.of)(EMPTY_MARKERS);
87
94
  }
88
95
 
89
- return validateItem({
96
+ return validateItemObservable({
90
97
  parent: undefined,
91
98
  value: doc,
92
99
  path: [],
@@ -112,7 +119,11 @@ function validateDocument(doc, schema, context) {
112
119
  */
113
120
 
114
121
 
115
- function validateItem(_ref) {
122
+ function validateItem(opts) {
123
+ return validateItemObservable(opts).toPromise();
124
+ }
125
+
126
+ function validateItemObservable(_ref) {
116
127
  var value = _ref.value,
117
128
  type = _ref.type,
118
129
  _ref$path = _ref.path,
@@ -160,7 +171,7 @@ function validateItem(_ref) {
160
171
  });
161
172
  })); // Validation from each field's schema `validation: Rule => {/* ... */}` function
162
173
 
163
- fieldChecks = fieldChecks.concat(type.fields.map(field => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
174
+ fieldChecks = fieldChecks.concat(type.fields.map(field => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
164
175
  parent: value,
165
176
  value: isRecord(value) ? value[field.name] : undefined,
166
177
  path: path.concat(field.name),
@@ -175,7 +186,7 @@ function validateItem(_ref) {
175
186
  var shouldRunNestedValidationForArrays = (type === null || type === void 0 ? void 0 : type.jsonType) === 'array' && Array.isArray(value);
176
187
 
177
188
  if (shouldRunNestedValidationForArrays) {
178
- fieldChecks = fieldChecks.concat(value.map(item => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
189
+ fieldChecks = fieldChecks.concat(value.map(item => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
179
190
  parent: value,
180
191
  value: item,
181
192
  path: path.concat((0, _types.isKeyedObject)(item) ? {
@@ -194,11 +205,11 @@ function validateItem(_ref) {
194
205
  spanChildrenField = _type$fields[0];
195
206
 
196
207
  var spanType = spanChildrenField.type.of.find(_types.isSpanSchemaType);
197
- var annotations = ((spanType === null || spanType === void 0 ? void 0 : spanType.annotations) || []).reduce((map, annotationType) => {
198
- map.set(annotationType.name, annotationType);
199
- return map;
208
+ var annotations = ((spanType === null || spanType === void 0 ? void 0 : spanType.annotations) || []).reduce((acc, annotationType) => {
209
+ acc.set(annotationType.name, annotationType);
210
+ return acc;
200
211
  }, new Map());
201
- fieldChecks = fieldChecks.concat(value.markDefs.map(markDef => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
212
+ fieldChecks = fieldChecks.concat(value.markDefs.map(markDef => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
202
213
  parent: value,
203
214
  value: markDef,
204
215
  path: path.concat(['markDefs', {
@@ -208,7 +219,7 @@ function validateItem(_ref) {
208
219
  }))));
209
220
  }
210
221
 
211
- 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.filter)(arr => arr.length > 0), (0, _operators.map)(_flatten2.default), (0, _operators.map)(results => {
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 => {
212
223
  // run `uniqBy` if `_fieldRules` are present because they can
213
224
  // cause repeat markers
214
225
  if (rules.some(rule => rule._fieldRules)) {
@@ -216,16 +227,16 @@ function validateItem(_ref) {
216
227
  }
217
228
 
218
229
  return results;
219
- }), (0, _operators.filter)(arr => arr.length > 0));
230
+ }));
220
231
  }
221
232
 
222
233
  function idle(timeout) {
223
234
  return new _rxjs.Observable(observer => {
224
- var handle = requestIdleCallback(() => {
235
+ var handle = (0, _requestIdleCallback.requestIdleCallback)(() => {
225
236
  observer.complete();
226
237
  }, timeout ? {
227
238
  timeout
228
239
  } : undefined);
229
- return () => cancelIdleCallback(handle);
240
+ return () => (0, _requestIdleCallback.cancelIdleCallback)(handle);
230
241
  });
231
242
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/validation",
3
- "version": "2.33.3-performance-opts.9+6ea72536ea",
3
+ "version": "2.33.3-performance-opts.14+691c5016e3",
4
4
  "description": "Validation and warning infrastructure for Sanity projects",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./dist/dts",
@@ -33,13 +33,13 @@
33
33
  },
34
34
  "devDependencies": {
35
35
  "@sanity/client": "^3.3.3",
36
- "@sanity/schema": "2.33.3-performance-opts.9+6ea72536ea"
36
+ "@sanity/schema": "2.33.3-performance-opts.14+691c5016e3"
37
37
  },
38
38
  "dependencies": {
39
- "@sanity/types": "2.33.3-performance-opts.9+6ea72536ea",
39
+ "@sanity/types": "2.33.3-performance-opts.14+691c5016e3",
40
40
  "date-fns": "^2.16.1",
41
41
  "lodash": "^4.17.15",
42
42
  "rxjs": "^6.5.3"
43
43
  },
44
- "gitHead": "6ea72536ea8c9aaebb1c57b304fc23f1e6705a67"
44
+ "gitHead": "691c5016e3cc91918d378614efb574125504ffc5"
45
45
  }
package/src/index.ts CHANGED
@@ -5,3 +5,5 @@ import inferFromSchemaType from './inferFromSchemaType'
5
5
 
6
6
  export default {Rule: RuleClass, validateDocument, inferFromSchema, inferFromSchemaType}
7
7
  export {RuleClass as Rule, validateDocument, inferFromSchema, inferFromSchemaType}
8
+
9
+ export {validateDocumentObservable} from './validateDocument'
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Simple requestIdleCallback polyfill
3
+ * Can be removed when all browsers support requestIdleCallback: https://caniuse.com/requestidlecallback
4
+ * @param callback
5
+ * @param options
6
+ */
7
+ const requestIdleCallbackShim: typeof window.requestIdleCallback = function requestIdleCallbackShim(
8
+ callback,
9
+ options?
10
+ ): number {
11
+ const start = Date.now()
12
+ return window.setTimeout(() => {
13
+ callback({
14
+ didTimeout: false,
15
+ timeRemaining() {
16
+ return Math.max(0, Date.now() - start)
17
+ },
18
+ })
19
+ }, 0)
20
+ }
21
+
22
+ const cancelIdleCallbackShim: typeof window.cancelIdleCallback = function cancelIdleCallbackShim(
23
+ handle: number
24
+ ): void {
25
+ return window.clearTimeout(handle)
26
+ }
27
+
28
+ export const requestIdleCallback = window.requestIdleCallback || requestIdleCallbackShim
29
+ export const cancelIdleCallback = window.cancelIdleCallback || cancelIdleCallbackShim
@@ -687,81 +687,4 @@ describe('validateItem', () => {
687
687
  },
688
688
  ])
689
689
  })
690
-
691
- it('runs all nested validation checks concurrently', async () => {
692
- type Resolver = (value: true) => void
693
- const resolvers = new Set<Resolver>()
694
- const customValidationFn = () => new Promise<true>((resolve) => resolvers.add(resolve))
695
-
696
- const schema: Schema = createSchema({
697
- types: [
698
- {
699
- name: 'root',
700
- type: 'object',
701
- fields: [
702
- {
703
- name: 'level1Object',
704
- type: 'object',
705
- validation: (rule: Rule) => [
706
- rule.custom(customValidationFn),
707
- rule.fields({
708
- level2String: (r) => r.custom(customValidationFn),
709
- }),
710
- ],
711
- fields: [
712
- {
713
- name: 'level2String',
714
- type: 'string',
715
- validation: (rule: Rule) => rule.custom(customValidationFn),
716
- },
717
- ],
718
- },
719
- {
720
- name: 'level1Array',
721
- type: 'array',
722
- validation: (rule: Rule) => rule.custom(customValidationFn),
723
- of: [
724
- {
725
- type: 'object',
726
- fields: [
727
- {
728
- name: 'level2Number',
729
- type: 'number',
730
- validation: (rule: Rule) => rule.custom(customValidationFn),
731
- },
732
- ],
733
- },
734
- ],
735
- },
736
- ],
737
- validation: (rule: Rule) => rule.custom(customValidationFn),
738
- },
739
- ],
740
- })
741
-
742
- const value = {
743
- level1Object: {level3String: 'a string'},
744
- level1Array: [{level2Number: 5}],
745
- }
746
-
747
- const resultPromise = validateItem({
748
- value,
749
- document: undefined,
750
- parent: undefined,
751
- path: undefined,
752
- type: schema.get('root'),
753
- getDocumentExists: undefined,
754
- })
755
-
756
- // after `validateItem(...)` has been initiated, all of the custom
757
- // validation calls should have fired so the resolver size should equal the
758
- // amount of total fields
759
- expect(resolvers.size).toBe(6)
760
-
761
- for (const resolver of resolvers) {
762
- resolver(true)
763
- }
764
-
765
- await resultPromise
766
- })
767
690
  })
@@ -11,19 +11,10 @@ import {
11
11
  ValidationMarker,
12
12
  } from '@sanity/types'
13
13
  import {concat, defer, merge, Observable, of} from 'rxjs'
14
- import {
15
- catchError,
16
- combineAll,
17
- concatMap,
18
- filter,
19
- map,
20
- mergeAll,
21
- mergeMap,
22
- tap,
23
- toArray,
24
- } from 'rxjs/operators'
14
+ import {catchError, map, mergeAll, mergeMap, toArray} from 'rxjs/operators'
25
15
  import {flatten, uniqBy} from 'lodash'
26
16
  import typeString from './util/typeString'
17
+ import {requestIdleCallback, cancelIdleCallback} from './util/requestIdleCallback'
27
18
  import ValidationErrorClass from './ValidationError'
28
19
  import normalizeValidationRules from './util/normalizeValidationRules'
29
20
 
@@ -63,6 +54,14 @@ export default function validateDocument(
63
54
  doc: SanityDocument,
64
55
  schema: Schema,
65
56
  context?: Pick<ValidationContext, 'getDocumentExists'>
57
+ ): Promise<ValidationMarker[]> {
58
+ return validateDocumentObservable(doc, schema, context).toPromise()
59
+ }
60
+
61
+ export function validateDocumentObservable(
62
+ doc: SanityDocument,
63
+ schema: Schema,
64
+ context?: Pick<ValidationContext, 'getDocumentExists'>
66
65
  ): Observable<ValidationMarker[]> {
67
66
  const documentType = schema.get(doc._type)
68
67
  if (!documentType) {
@@ -70,7 +69,7 @@ export default function validateDocument(
70
69
  return of(EMPTY_MARKERS)
71
70
  }
72
71
 
73
- return validateItem({
72
+ return validateItemObservable({
74
73
  parent: undefined,
75
74
  value: doc,
76
75
  path: [],
@@ -107,7 +106,11 @@ type ValidateItemOptions = {
107
106
  value: unknown
108
107
  } & ExplicitUndefined<ValidationContext>
109
108
 
110
- export function validateItem({
109
+ export function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]> {
110
+ return validateItemObservable(opts).toPromise()
111
+ }
112
+
113
+ function validateItemObservable({
111
114
  value,
112
115
  type,
113
116
  path = [],
@@ -170,7 +173,7 @@ export function validateItem({
170
173
  // Validation from each field's schema `validation: Rule => {/* ... */}` function
171
174
  fieldChecks = fieldChecks.concat(
172
175
  type.fields.map((field) =>
173
- validateItem({
176
+ validateItemObservable({
174
177
  ...restOfContext,
175
178
  parent: value,
176
179
  value: isRecord(value) ? value[field.name] : undefined,
@@ -190,7 +193,7 @@ export function validateItem({
190
193
  if (shouldRunNestedValidationForArrays) {
191
194
  fieldChecks = fieldChecks.concat(
192
195
  value.map((item) =>
193
- validateItem({
196
+ validateItemObservable({
194
197
  ...restOfContext,
195
198
  parent: value,
196
199
  value: item,
@@ -211,16 +214,16 @@ export function validateItem({
211
214
  const spanType = spanChildrenField.type.of.find(isSpanSchemaType)
212
215
 
213
216
  const annotations = (spanType?.annotations || []).reduce<Map<string, SchemaType>>(
214
- (map, annotationType) => {
215
- map.set(annotationType.name, annotationType)
216
- return map
217
+ (acc, annotationType) => {
218
+ acc.set(annotationType.name, annotationType)
219
+ return acc
217
220
  },
218
221
  new Map()
219
222
  )
220
223
 
221
224
  fieldChecks = fieldChecks.concat(
222
225
  value.markDefs.map((markDef) =>
223
- validateItem({
226
+ validateItemObservable({
224
227
  ...restOfContext,
225
228
  parent: value,
226
229
  value: markDef,
@@ -235,7 +238,6 @@ export function validateItem({
235
238
  mergeMap((validateNode) => concat(idle(), validateNode), 40),
236
239
  mergeAll(),
237
240
  toArray(),
238
- filter((arr) => arr.length > 0),
239
241
  map(flatten),
240
242
  map((results) => {
241
243
  // run `uniqBy` if `_fieldRules` are present because they can
@@ -244,8 +246,7 @@ export function validateItem({
244
246
  return uniqBy(results, (rule) => JSON.stringify(rule))
245
247
  }
246
248
  return results
247
- }),
248
- filter((arr) => arr.length > 0)
249
+ })
249
250
  )
250
251
  }
251
252