@sanity/validation 3.0.0-v3-pkg-utils.59 → 3.0.0-v3-pkg-utils.79

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.
@@ -1,3 +1,4 @@
1
+ import {Observable} from 'rxjs'
1
2
  import {RuleClass} from '@sanity/types'
2
3
  import type {SanityClient} from '@sanity/client'
3
4
  import {SanityDocument} from '@sanity/types'
@@ -19,10 +20,17 @@ export declare function inferFromSchemaType(typeDef: SchemaType): SchemaType
19
20
  export declare const Rule: RuleClass
20
21
 
21
22
  export declare function validateDocument(
22
- client: SanityClient,
23
+ getClient: (options: {apiVersion: string}) => SanityClient,
23
24
  doc: SanityDocument,
24
25
  schema: Schema,
25
26
  context?: Pick<ValidationContext, 'getDocumentExists'>
26
27
  ): Promise<ValidationMarker[]>
27
28
 
29
+ export declare function validateDocumentObservable(
30
+ getClient: (options: {apiVersion: string}) => SanityClient,
31
+ doc: SanityDocument,
32
+ schema: Schema,
33
+ context?: Pick<ValidationContext, 'getDocumentExists'>
34
+ ): Observable<ValidationMarker[]>
35
+
28
36
  export {}
package/lib/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ 'use strict';
2
+
1
3
  const _excluded = ["value", "type", "path", "parent"];
2
4
 
3
5
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
@@ -10,9 +12,28 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va
10
12
 
11
13
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
14
 
13
- import { cloneDeep, get, memoize, uniqBy } from 'lodash';
14
- import { isKeyedObject, isReference, isBlock, isBlockSchemaType, isSpanSchemaType, isTypedObject } from '@sanity/types';
15
- import formatDate from 'date-fns/format';
15
+ Object.defineProperty(exports, '__esModule', {
16
+ value: true
17
+ });
18
+
19
+ var lodash = require('lodash');
20
+
21
+ var types = require('@sanity/types');
22
+
23
+ var formatDate = require('date-fns/format');
24
+
25
+ var rxjs = require('rxjs');
26
+
27
+ var operators = require('rxjs/operators');
28
+
29
+ function _interopDefaultLegacy(e) {
30
+ return e && typeof e === 'object' && 'default' in e ? e : {
31
+ 'default': e
32
+ };
33
+ }
34
+
35
+ var formatDate__default = /*#__PURE__*/_interopDefaultLegacy(formatDate);
36
+
16
37
  const ValidationError = class ValidationError2 {
17
38
  constructor(message) {
18
39
  let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -50,7 +71,7 @@ function pathToString() {
50
71
  return "".concat(target).concat(separator).concat(segment);
51
72
  }
52
73
 
53
- if (isKeyedObject(segment)) {
74
+ if (types.isKeyedObject(segment)) {
54
75
  return "".concat(target, "[_key==\"").concat(segment._key, "\"]");
55
76
  }
56
77
 
@@ -575,7 +596,7 @@ const objectValidators = _objectSpread(_objectSpread({}, genericValidators), {},
575
596
  return true;
576
597
  }
577
598
 
578
- if (!isReference(value)) {
599
+ if (!types.isReference(value)) {
579
600
  return message || true;
580
601
  }
581
602
 
@@ -633,7 +654,7 @@ const getFormattedDate = function () {
633
654
  }
634
655
 
635
656
  if (type === "date") {
636
- return formatDate(new Date(value), format);
657
+ return formatDate__default["default"](new Date(value), format);
637
658
  }
638
659
 
639
660
  if (options && options.timeFormat) {
@@ -642,7 +663,7 @@ const getFormattedDate = function () {
642
663
  format += " HH:mm";
643
664
  }
644
665
 
645
- return formatDate(new Date(value), format);
666
+ return formatDate__default["default"](new Date(value), format);
646
667
  };
647
668
 
648
669
  function parseDate(date) {
@@ -792,7 +813,7 @@ const Rule = (_a = class {
792
813
  rule._type = this._type;
793
814
  rule._message = this._message;
794
815
  rule._required = this._required;
795
- rule._rules = cloneDeep(this._rules);
816
+ rule._rules = lodash.cloneDeep(this._rules);
796
817
  rule._level = this._level;
797
818
  rule._fieldRules = this._fieldRules;
798
819
  rule._typeDef = this._typeDef;
@@ -1093,7 +1114,7 @@ const Rule = (_a = class {
1093
1114
  let specConstraint = "constraint" in curr ? curr.constraint : null;
1094
1115
 
1095
1116
  if (isFieldRef(specConstraint)) {
1096
- specConstraint = get(context.parent, specConstraint.path);
1117
+ specConstraint = lodash.get(context.parent, specConstraint.path);
1097
1118
  }
1098
1119
 
1099
1120
  let result;
@@ -1114,7 +1135,29 @@ const Rule = (_a = class {
1114
1135
  type: FIELD_REF,
1115
1136
  path
1116
1137
  }), _a);
1117
- const memoizedWarnOnArraySlug = memoize(warnOnArraySlug);
1138
+
1139
+ const requestIdleCallbackShim = function requestIdleCallbackShim2(callback, options) {
1140
+ const start = Date.now();
1141
+ return window.setTimeout(() => {
1142
+ callback({
1143
+ didTimeout: false,
1144
+
1145
+ timeRemaining() {
1146
+ return Math.max(0, Date.now() - start);
1147
+ }
1148
+
1149
+ });
1150
+ }, 0);
1151
+ };
1152
+
1153
+ const cancelIdleCallbackShim = function cancelIdleCallbackShim2(handle) {
1154
+ return window.clearTimeout(handle);
1155
+ };
1156
+
1157
+ const win = typeof window === "undefined" ? void 0 : window;
1158
+ const requestIdleCallback = (win == null ? void 0 : win.requestIdleCallback) || requestIdleCallbackShim;
1159
+ const cancelIdleCallback = (win == null ? void 0 : win.cancelIdleCallback) || cancelIdleCallbackShim;
1160
+ const memoizedWarnOnArraySlug = lodash.memoize(warnOnArraySlug);
1118
1161
 
1119
1162
  function getDocumentIds(id) {
1120
1163
  const isDraft = id.indexOf("drafts.") === 0;
@@ -1127,7 +1170,7 @@ function getDocumentIds(id) {
1127
1170
  function serializePath(path) {
1128
1171
  return path.reduce((target, part, i) => {
1129
1172
  const isIndex = typeof part === "number";
1130
- const isKey = isKeyedObject(part);
1173
+ const isKey = types.isKeyedObject(part);
1131
1174
  const separator = i === 0 ? "" : ".";
1132
1175
  const add = isIndex || isKey ? "[]" : "".concat(separator).concat(part);
1133
1176
  return "".concat(target).concat(add);
@@ -1136,7 +1179,7 @@ function serializePath(path) {
1136
1179
 
1137
1180
  const defaultIsUnique = (slug, context) => {
1138
1181
  const {
1139
- client,
1182
+ getClient,
1140
1183
  document,
1141
1184
  path,
1142
1185
  type
@@ -1164,7 +1207,9 @@ const defaultIsUnique = (slug, context) => {
1164
1207
  }
1165
1208
 
1166
1209
  const constraints = ["_type == $docType", "!(_id in [$draft, $published])", "".concat(atPath, " == $slug")].join(" && ");
1167
- return client.fetch("!defined(*[".concat(constraints, "][0]._id)"), {
1210
+ return getClient({
1211
+ apiVersion: "2022-09-09"
1212
+ }).fetch("!defined(*[".concat(constraints, "][0]._id)"), {
1168
1213
  docType,
1169
1214
  draft,
1170
1215
  published,
@@ -1300,7 +1345,7 @@ const isNonNullable = value => value !== null && value !== void 0;
1300
1345
  function resolveTypeForArrayItem(item, candidates) {
1301
1346
  if (candidates.length === 1) return candidates[0];
1302
1347
 
1303
- const itemType = isTypedObject(item) && item._type;
1348
+ const itemType = types.isTypedObject(item) && item._type;
1304
1349
 
1305
1350
  const primitive = item === void 0 || item === null || !itemType && typeString(item).toLowerCase();
1306
1351
 
@@ -1315,36 +1360,57 @@ function resolveTypeForArrayItem(item, candidates) {
1315
1360
  }) || candidates.find(candidate => candidate.name === itemType) || candidates.find(candidate => candidate.name === "object" && primitive === "object");
1316
1361
  }
1317
1362
 
1318
- async function validateDocument(client, doc, schema, context) {
1363
+ const EMPTY_MARKERS = [];
1364
+
1365
+ async function validateDocument(getClient, doc, schema, context) {
1366
+ return validateDocumentObservable(getClient, doc, schema, context).toPromise();
1367
+ }
1368
+
1369
+ function validateDocumentObservable(getClient, doc, schema, context) {
1319
1370
  const documentType = schema.get(doc._type);
1320
1371
 
1321
1372
  if (!documentType) {
1322
1373
  console.warn('Schema type for object type "%s" not found, skipping validation', doc._type);
1323
- return [];
1374
+ return rxjs.of(EMPTY_MARKERS);
1324
1375
  }
1325
1376
 
1326
- try {
1327
- return await validateItem({
1328
- client,
1329
- schema,
1330
- parent: void 0,
1331
- value: doc,
1332
- path: [],
1333
- document: doc,
1334
- type: documentType,
1335
- getDocumentExists: context == null ? void 0 : context.getDocumentExists
1377
+ const client = getClient({
1378
+ apiVersion: "2021-06-07"
1379
+ });
1380
+ const validationOptions = {
1381
+ client,
1382
+ getClient,
1383
+ schema,
1384
+ parent: void 0,
1385
+ value: doc,
1386
+ path: [],
1387
+ document: doc,
1388
+ type: documentType,
1389
+ getDocumentExists: context == null ? void 0 : context.getDocumentExists
1390
+ };
1391
+ const wrappedClient = client;
1392
+ validationOptions.client = [...Object.keys(client), ...Object.keys(wrappedClient.__proto__)].reduce((acc, key) => {
1393
+ const original = Object.hasOwnProperty.call(client, key) ? wrappedClient[key] : wrappedClient.__proto__[key];
1394
+ return Object.defineProperty(acc, key, {
1395
+ get() {
1396
+ console.warn('`configContext.client` is deprecated and will be removed in the next release! Use `context.getClient({apiVersion: "2021-06-07"})` instead');
1397
+ return original;
1398
+ }
1399
+
1336
1400
  });
1337
- } catch (err) {
1401
+ }, {});
1402
+ return validateItemObservable(validationOptions).pipe(operators.catchError(err => {
1338
1403
  console.error(err);
1339
- return [{
1404
+ return rxjs.of([{
1405
+ type: "validation",
1340
1406
  level: "error",
1341
1407
  path: [],
1342
1408
  item: new ValidationError(err == null ? void 0 : err.message)
1343
- }];
1344
- }
1409
+ }]);
1410
+ }));
1345
1411
  }
1346
1412
 
1347
- async function validateItem(_ref) {
1413
+ function validateItemObservable(_ref) {
1348
1414
  let {
1349
1415
  value,
1350
1416
  type,
@@ -1354,11 +1420,11 @@ async function validateItem(_ref) {
1354
1420
  restOfContext = _objectWithoutProperties(_ref, _excluded);
1355
1421
 
1356
1422
  const rules = normalizeValidationRules(type);
1357
- const selfChecks = rules.map(rule => rule.validate(value, _objectSpread(_objectSpread({}, restOfContext), {}, {
1423
+ const selfChecks = rules.map(rule => rxjs.defer(() => rule.validate(value, _objectSpread(_objectSpread({}, restOfContext), {}, {
1358
1424
  parent,
1359
1425
  path,
1360
1426
  type
1361
- })));
1427
+ }))));
1362
1428
  let nestedChecks = [];
1363
1429
  const selfIsRequired = rules.some(rule => rule.isRequired());
1364
1430
  const shouldRunNestedObjectValidation = (type == null ? void 0 : type.jsonType) === "object" && (!!value || (value === null || value === void 0) && selfIsRequired);
@@ -1375,14 +1441,14 @@ async function validateItem(_ref) {
1375
1441
  validation
1376
1442
  })).map(subRule => {
1377
1443
  const nestedValue = isRecord(value) ? value[name] : void 0;
1378
- return subRule.validate(nestedValue, _objectSpread(_objectSpread({}, restOfContext), {}, {
1444
+ return rxjs.defer(() => subRule.validate(nestedValue, _objectSpread(_objectSpread({}, restOfContext), {}, {
1379
1445
  parent: value,
1380
1446
  path: path.concat(name),
1381
1447
  type: fieldType
1382
- }));
1448
+ })));
1383
1449
  });
1384
1450
  }));
1385
- nestedChecks = nestedChecks.concat(type.fields.map(field => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
1451
+ nestedChecks = nestedChecks.concat(type.fields.map(field => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1386
1452
  parent: value,
1387
1453
  value: isRecord(value) ? value[field.name] : void 0,
1388
1454
  path: path.concat(field.name),
@@ -1393,26 +1459,26 @@ async function validateItem(_ref) {
1393
1459
  const shouldRunNestedValidationForArrays = (type == null ? void 0 : type.jsonType) === "array" && Array.isArray(value);
1394
1460
 
1395
1461
  if (shouldRunNestedValidationForArrays) {
1396
- nestedChecks = nestedChecks.concat(value.map(item => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
1462
+ nestedChecks = nestedChecks.concat(value.map(item => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1397
1463
  parent: value,
1398
1464
  value: item,
1399
- path: path.concat(isKeyedObject(item) ? {
1465
+ path: path.concat(types.isKeyedObject(item) ? {
1400
1466
  _key: item._key
1401
1467
  } : value.indexOf(item)),
1402
1468
  type: resolveTypeForArrayItem(item, type.of)
1403
1469
  }))));
1404
1470
  }
1405
1471
 
1406
- const shouldRunNestedValidationForMarkDefs = isBlock(value) && value.markDefs.length && isBlockSchemaType(type);
1472
+ const shouldRunNestedValidationForMarkDefs = types.isBlock(value) && value.markDefs.length && types.isBlockSchemaType(type);
1407
1473
 
1408
1474
  if (shouldRunNestedValidationForMarkDefs) {
1409
1475
  const [spanChildrenField] = type.fields;
1410
- const spanType = spanChildrenField.type.of.find(isSpanSchemaType);
1411
- const annotations = ((spanType == null ? void 0 : spanType.annotations) || []).reduce((map, annotationType) => {
1412
- map.set(annotationType.name, annotationType);
1413
- return map;
1476
+ const spanType = spanChildrenField.type.of.find(types.isSpanSchemaType);
1477
+ const annotations = ((spanType == null ? void 0 : spanType.annotations) || []).reduce((acc, annotationType) => {
1478
+ acc.set(annotationType.name, annotationType);
1479
+ return acc;
1414
1480
  }, /* @__PURE__ */new Map());
1415
- nestedChecks = nestedChecks.concat(value.markDefs.map(markDef => validateItem(_objectSpread(_objectSpread({}, restOfContext), {}, {
1481
+ nestedChecks = nestedChecks.concat(value.markDefs.map(markDef => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1416
1482
  parent: value,
1417
1483
  value: markDef,
1418
1484
  path: path.concat(["markDefs", {
@@ -1422,13 +1488,24 @@ async function validateItem(_ref) {
1422
1488
  }))));
1423
1489
  }
1424
1490
 
1425
- const results = (await Promise.all([...selfChecks, ...nestedChecks])).flat();
1491
+ return rxjs.defer(() => rxjs.merge([...selfChecks, ...nestedChecks])).pipe(operators.mergeMap(validateNode => rxjs.concat(idle(), validateNode), 40), operators.mergeAll(), operators.toArray(), operators.map(lodash.flatten), operators.map(results => {
1492
+ if (rules.some(rule => rule._fieldRules)) {
1493
+ return lodash.uniqBy(results, rule => JSON.stringify(rule));
1494
+ }
1426
1495
 
1427
- if (rules.some(rule => rule._fieldRules)) {
1428
- return uniqBy(results, rule => JSON.stringify(rule));
1429
- }
1496
+ return results;
1497
+ }));
1498
+ }
1430
1499
 
1431
- return results;
1500
+ function idle(timeout) {
1501
+ return new rxjs.Observable(observer => {
1502
+ const handle = requestIdleCallback(() => {
1503
+ observer.complete();
1504
+ }, timeout ? {
1505
+ timeout
1506
+ } : void 0);
1507
+ return () => cancelIdleCallback(handle);
1508
+ });
1432
1509
  }
1433
1510
 
1434
1511
  function traverse(typeDef, visited) {
@@ -1475,5 +1552,9 @@ function inferFromSchema(schema) {
1475
1552
  return schema;
1476
1553
  }
1477
1554
 
1478
- export { Rule, inferFromSchema, inferFromSchemaType, validateDocument };
1555
+ exports.Rule = Rule;
1556
+ exports.inferFromSchema = inferFromSchema;
1557
+ exports.inferFromSchemaType = inferFromSchemaType;
1558
+ exports.validateDocument = validateDocument;
1559
+ exports.validateDocumentObservable = validateDocumentObservable;
1479
1560
  //# sourceMappingURL=index.js.map