@sanity/validation 3.0.0-dev-preview.12 → 3.0.0-v3-pte.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -10,10 +10,6 @@ var formatDate__default = /*#__PURE__*/_interopDefaultLegacy(formatDate);
10
10
 
11
11
  // Follows the same pattern as Rule and RuleClass. @see Rule
12
12
  const ValidationError = class ValidationError {
13
- message;
14
- paths;
15
- children;
16
- operation;
17
13
  constructor(message, options = {}) {
18
14
  this.message = message;
19
15
  this.paths = options.paths || [];
@@ -624,6 +620,7 @@ const dateValidators = {
624
620
  },
625
621
  };
626
622
 
623
+ var _a;
627
624
  const typeValidators = {
628
625
  Boolean: booleanValidators,
629
626
  Number: numberValidators,
@@ -665,285 +662,286 @@ const ruleConstraintTypes$1 = [
665
662
  // This package exports the RuleClass as a value without implicitly exporting
666
663
  // an instance definition. This should help reminder downstream users to import
667
664
  // from the `@sanity/types` package.
668
- const Rule = class Rule {
669
- static FIELD_REF = FIELD_REF;
670
- static array = (def) => new Rule(def).type('Array');
671
- static object = (def) => new Rule(def).type('Object');
672
- static string = (def) => new Rule(def).type('String');
673
- static number = (def) => new Rule(def).type('Number');
674
- static boolean = (def) => new Rule(def).type('Boolean');
675
- static dateTime = (def) => new Rule(def).type('Date');
676
- static valueOfField = (path) => ({
677
- type: FIELD_REF,
678
- path,
679
- });
680
- _type = undefined;
681
- _level = undefined;
682
- _required = undefined;
683
- _typeDef = undefined;
684
- _message = undefined;
685
- _rules = [];
686
- _fieldRules = undefined;
687
- constructor(typeDef) {
688
- this._typeDef = typeDef;
689
- this.reset();
690
- }
691
- _mergeRequired(next) {
692
- if (this._required === 'required' || next._required === 'required')
693
- return 'required';
694
- if (this._required === 'optional' || next._required === 'optional')
695
- return 'optional';
696
- return undefined;
697
- }
698
- // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class
699
- valueOfField = Rule.valueOfField.bind(Rule);
700
- error(message) {
701
- const rule = this.clone();
702
- rule._level = 'error';
703
- rule._message = message || undefined;
704
- return rule;
705
- }
706
- warning(message) {
707
- const rule = this.clone();
708
- rule._level = 'warning';
709
- rule._message = message || undefined;
710
- return rule;
711
- }
712
- info(message) {
713
- const rule = this.clone();
714
- rule._level = 'info';
715
- rule._message = message || undefined;
716
- return rule;
717
- }
718
- reset() {
719
- this._type = this._type || undefined;
720
- this._rules = (this._rules || []).filter((rule) => rule.flag === 'type');
721
- this._message = undefined;
722
- this._required = undefined;
723
- this._level = 'error';
724
- this._fieldRules = undefined;
725
- return this;
726
- }
727
- isRequired() {
728
- return this._required === 'required';
729
- }
730
- clone() {
731
- const rule = new Rule();
732
- rule._type = this._type;
733
- rule._message = this._message;
734
- rule._required = this._required;
735
- rule._rules = lodash.cloneDeep(this._rules);
736
- rule._level = this._level;
737
- rule._fieldRules = this._fieldRules;
738
- rule._typeDef = this._typeDef;
739
- return rule;
740
- }
741
- cloneWithRules(rules) {
742
- const rule = this.clone();
743
- const newRules = new Set();
744
- rules.forEach((curr) => {
745
- if (curr.flag === 'type') {
746
- rule._type = curr.constraint;
665
+ const Rule = (_a = class Rule {
666
+ constructor(typeDef) {
667
+ this._type = undefined;
668
+ this._level = undefined;
669
+ this._required = undefined;
670
+ this._typeDef = undefined;
671
+ this._message = undefined;
672
+ this._rules = [];
673
+ this._fieldRules = undefined;
674
+ // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class
675
+ this.valueOfField = Rule.valueOfField.bind(Rule);
676
+ this._typeDef = typeDef;
677
+ this.reset();
678
+ }
679
+ _mergeRequired(next) {
680
+ if (this._required === 'required' || next._required === 'required')
681
+ return 'required';
682
+ if (this._required === 'optional' || next._required === 'optional')
683
+ return 'optional';
684
+ return undefined;
685
+ }
686
+ error(message) {
687
+ const rule = this.clone();
688
+ rule._level = 'error';
689
+ rule._message = message || undefined;
690
+ return rule;
691
+ }
692
+ warning(message) {
693
+ const rule = this.clone();
694
+ rule._level = 'warning';
695
+ rule._message = message || undefined;
696
+ return rule;
697
+ }
698
+ info(message) {
699
+ const rule = this.clone();
700
+ rule._level = 'info';
701
+ rule._message = message || undefined;
702
+ return rule;
703
+ }
704
+ reset() {
705
+ this._type = this._type || undefined;
706
+ this._rules = (this._rules || []).filter((rule) => rule.flag === 'type');
707
+ this._message = undefined;
708
+ this._required = undefined;
709
+ this._level = 'error';
710
+ this._fieldRules = undefined;
711
+ return this;
712
+ }
713
+ isRequired() {
714
+ return this._required === 'required';
715
+ }
716
+ clone() {
717
+ const rule = new Rule();
718
+ rule._type = this._type;
719
+ rule._message = this._message;
720
+ rule._required = this._required;
721
+ rule._rules = lodash.cloneDeep(this._rules);
722
+ rule._level = this._level;
723
+ rule._fieldRules = this._fieldRules;
724
+ rule._typeDef = this._typeDef;
725
+ return rule;
726
+ }
727
+ cloneWithRules(rules) {
728
+ const rule = this.clone();
729
+ const newRules = new Set();
730
+ rules.forEach((curr) => {
731
+ if (curr.flag === 'type') {
732
+ rule._type = curr.constraint;
733
+ }
734
+ newRules.add(curr.flag);
735
+ });
736
+ rule._rules = rule._rules
737
+ .filter((curr) => {
738
+ const disallowDuplicate = ['type', 'uri', 'email'].includes(curr.flag);
739
+ const isDuplicate = newRules.has(curr.flag);
740
+ return !(disallowDuplicate && isDuplicate);
741
+ })
742
+ .concat(rules);
743
+ return rule;
744
+ }
745
+ merge(rule) {
746
+ if (this._type && rule._type && this._type !== rule._type) {
747
+ throw new Error('merge() failed: conflicting types');
747
748
  }
748
- newRules.add(curr.flag);
749
- });
750
- rule._rules = rule._rules
751
- .filter((curr) => {
752
- const disallowDuplicate = ['type', 'uri', 'email'].includes(curr.flag);
753
- const isDuplicate = newRules.has(curr.flag);
754
- return !(disallowDuplicate && isDuplicate);
755
- })
756
- .concat(rules);
757
- return rule;
758
- }
759
- merge(rule) {
760
- if (this._type && rule._type && this._type !== rule._type) {
761
- throw new Error('merge() failed: conflicting types');
762
- }
763
- const newRule = this.cloneWithRules(rule._rules);
764
- newRule._type = this._type || rule._type;
765
- newRule._message = this._message || rule._message;
766
- newRule._required = this._mergeRequired(rule);
767
- newRule._level = this._level === 'error' ? rule._level : this._level;
768
- return newRule;
769
- }
770
- // Validation flag setters
771
- type(targetType) {
772
- const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}`;
773
- if (!ruleConstraintTypes$1.includes(type)) {
774
- throw new Error(`Unknown type "${targetType}"`);
775
- }
776
- const rule = this.cloneWithRules([{ flag: 'type', constraint: type }]);
777
- rule._type = type;
778
- return rule;
779
- }
780
- all(children) {
781
- return this.cloneWithRules([{ flag: 'all', constraint: children }]);
782
- }
783
- either(children) {
784
- return this.cloneWithRules([{ flag: 'either', constraint: children }]);
785
- }
786
- // Shared rules
787
- optional() {
788
- const rule = this.cloneWithRules([{ flag: 'presence', constraint: 'optional' }]);
789
- rule._required = 'optional';
790
- return rule;
791
- }
792
- required() {
793
- const rule = this.cloneWithRules([{ flag: 'presence', constraint: 'required' }]);
794
- rule._required = 'required';
795
- return rule;
796
- }
797
- custom(fn) {
798
- return this.cloneWithRules([{ flag: 'custom', constraint: fn }]);
799
- }
800
- /**
801
- * @deprecated use `Rule.custom` instead
802
- */
803
- block(fn) {
804
- return this.cloneWithRules([{ flag: 'custom', constraint: fn }]);
805
- }
806
- min(len) {
807
- return this.cloneWithRules([{ flag: 'min', constraint: len }]);
808
- }
809
- max(len) {
810
- return this.cloneWithRules([{ flag: 'max', constraint: len }]);
811
- }
812
- length(len) {
813
- return this.cloneWithRules([{ flag: 'length', constraint: len }]);
814
- }
815
- valid(value) {
816
- const values = Array.isArray(value) ? value : [value];
817
- return this.cloneWithRules([{ flag: 'valid', constraint: values }]);
818
- }
819
- // Numbers only
820
- integer() {
821
- return this.cloneWithRules([{ flag: 'integer' }]);
822
- }
823
- precision(limit) {
824
- return this.cloneWithRules([{ flag: 'precision', constraint: limit }]);
825
- }
826
- positive() {
827
- return this.cloneWithRules([{ flag: 'min', constraint: 0 }]);
828
- }
829
- negative() {
830
- return this.cloneWithRules([{ flag: 'lessThan', constraint: 0 }]);
831
- }
832
- greaterThan(num) {
833
- return this.cloneWithRules([{ flag: 'greaterThan', constraint: num }]);
834
- }
835
- lessThan(num) {
836
- return this.cloneWithRules([{ flag: 'lessThan', constraint: num }]);
837
- }
838
- // String only
839
- uppercase() {
840
- return this.cloneWithRules([{ flag: 'stringCasing', constraint: 'uppercase' }]);
841
- }
842
- lowercase() {
843
- return this.cloneWithRules([{ flag: 'stringCasing', constraint: 'lowercase' }]);
844
- }
845
- regex(pattern, a, b) {
846
- const name = typeof a === 'string' ? a : a?.name ?? b?.name;
847
- const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert;
848
- const constraint = {
849
- pattern,
850
- name,
851
- invert: invert || false,
852
- };
853
- return this.cloneWithRules([{ flag: 'regex', constraint }]);
854
- }
855
- email() {
856
- return this.cloneWithRules([{ flag: 'email' }]);
857
- }
858
- uri(opts) {
859
- const optsScheme = opts?.scheme || ['http', 'https'];
860
- const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme];
861
- if (!schemes.length) {
862
- throw new Error('scheme must have at least 1 scheme specified');
863
- }
864
- const constraint = {
865
- options: {
866
- scheme: schemes.map((scheme) => {
867
- if (!(scheme instanceof RegExp) && typeof scheme !== 'string') {
868
- throw new Error('scheme must be a RegExp or a String');
869
- }
870
- return typeof scheme === 'string' ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme;
871
- }),
872
- allowRelative: opts?.allowRelative || false,
873
- relativeOnly: opts?.relativeOnly || false,
874
- allowCredentials: opts?.allowCredentials || false,
875
- },
876
- };
877
- return this.cloneWithRules([{ flag: 'uri', constraint }]);
878
- }
879
- // Array only
880
- unique() {
881
- return this.cloneWithRules([{ flag: 'unique' }]);
882
- }
883
- // Objects only
884
- reference() {
885
- return this.cloneWithRules([{ flag: 'reference' }]);
886
- }
887
- fields(rules) {
888
- if (this._type !== 'Object') {
889
- throw new Error('fields() can only be called on an object type');
749
+ const newRule = this.cloneWithRules(rule._rules);
750
+ newRule._type = this._type || rule._type;
751
+ newRule._message = this._message || rule._message;
752
+ newRule._required = this._mergeRequired(rule);
753
+ newRule._level = this._level === 'error' ? rule._level : this._level;
754
+ return newRule;
755
+ }
756
+ // Validation flag setters
757
+ type(targetType) {
758
+ const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}`;
759
+ if (!ruleConstraintTypes$1.includes(type)) {
760
+ throw new Error(`Unknown type "${targetType}"`);
761
+ }
762
+ const rule = this.cloneWithRules([{ flag: 'type', constraint: type }]);
763
+ rule._type = type;
764
+ return rule;
890
765
  }
891
- const rule = this.cloneWithRules([]);
892
- rule._fieldRules = rules;
893
- return rule;
894
- }
895
- assetRequired() {
896
- const base = getBaseType(this._typeDef);
897
- let assetType;
898
- if (base && ['image', 'file'].includes(base.name)) {
899
- assetType = base.name === 'image' ? 'Image' : 'File';
766
+ all(children) {
767
+ return this.cloneWithRules([{ flag: 'all', constraint: children }]);
900
768
  }
901
- else {
902
- assetType = 'Asset';
769
+ either(children) {
770
+ return this.cloneWithRules([{ flag: 'either', constraint: children }]);
903
771
  }
904
- return this.cloneWithRules([{ flag: 'assetRequired', constraint: { assetType } }]);
905
- }
906
- async validate(value, context) {
907
- if (!context) {
908
- throw new Error('missing context');
909
- }
910
- const valueIsEmpty = value === null || value === undefined;
911
- // Short-circuit on optional, empty fields
912
- if (valueIsEmpty && this._required === 'optional') {
913
- return EMPTY_ARRAY;
914
- }
915
- const rules =
916
- // Run only the _custom_ functions if the rule is not set to required or optional
917
- this._required === undefined && valueIsEmpty
918
- ? this._rules.filter((curr) => curr.flag === 'custom')
919
- : this._rules;
920
- const validators = (this._type && typeValidators[this._type]) || genericValidators;
921
- const results = await Promise.all(rules.map(async (curr) => {
922
- if (curr.flag === undefined) {
923
- throw new Error('Invalid rule, did not contain "flag"-property');
772
+ // Shared rules
773
+ optional() {
774
+ const rule = this.cloneWithRules([{ flag: 'presence', constraint: 'optional' }]);
775
+ rule._required = 'optional';
776
+ return rule;
777
+ }
778
+ required() {
779
+ const rule = this.cloneWithRules([{ flag: 'presence', constraint: 'required' }]);
780
+ rule._required = 'required';
781
+ return rule;
782
+ }
783
+ custom(fn) {
784
+ return this.cloneWithRules([{ flag: 'custom', constraint: fn }]);
785
+ }
786
+ /**
787
+ * @deprecated use `Rule.custom` instead
788
+ */
789
+ block(fn) {
790
+ return this.cloneWithRules([{ flag: 'custom', constraint: fn }]);
791
+ }
792
+ min(len) {
793
+ return this.cloneWithRules([{ flag: 'min', constraint: len }]);
794
+ }
795
+ max(len) {
796
+ return this.cloneWithRules([{ flag: 'max', constraint: len }]);
797
+ }
798
+ length(len) {
799
+ return this.cloneWithRules([{ flag: 'length', constraint: len }]);
800
+ }
801
+ valid(value) {
802
+ const values = Array.isArray(value) ? value : [value];
803
+ return this.cloneWithRules([{ flag: 'valid', constraint: values }]);
804
+ }
805
+ // Numbers only
806
+ integer() {
807
+ return this.cloneWithRules([{ flag: 'integer' }]);
808
+ }
809
+ precision(limit) {
810
+ return this.cloneWithRules([{ flag: 'precision', constraint: limit }]);
811
+ }
812
+ positive() {
813
+ return this.cloneWithRules([{ flag: 'min', constraint: 0 }]);
814
+ }
815
+ negative() {
816
+ return this.cloneWithRules([{ flag: 'lessThan', constraint: 0 }]);
817
+ }
818
+ greaterThan(num) {
819
+ return this.cloneWithRules([{ flag: 'greaterThan', constraint: num }]);
820
+ }
821
+ lessThan(num) {
822
+ return this.cloneWithRules([{ flag: 'lessThan', constraint: num }]);
823
+ }
824
+ // String only
825
+ uppercase() {
826
+ return this.cloneWithRules([{ flag: 'stringCasing', constraint: 'uppercase' }]);
827
+ }
828
+ lowercase() {
829
+ return this.cloneWithRules([{ flag: 'stringCasing', constraint: 'lowercase' }]);
830
+ }
831
+ regex(pattern, a, b) {
832
+ const name = typeof a === 'string' ? a : a?.name ?? b?.name;
833
+ const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert;
834
+ const constraint = {
835
+ pattern,
836
+ name,
837
+ invert: invert || false,
838
+ };
839
+ return this.cloneWithRules([{ flag: 'regex', constraint }]);
840
+ }
841
+ email() {
842
+ return this.cloneWithRules([{ flag: 'email' }]);
843
+ }
844
+ uri(opts) {
845
+ const optsScheme = opts?.scheme || ['http', 'https'];
846
+ const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme];
847
+ if (!schemes.length) {
848
+ throw new Error('scheme must have at least 1 scheme specified');
924
849
  }
925
- const validator = validators[curr.flag];
926
- if (!validator) {
927
- const forType = this._type ? `type "${this._type}"` : 'rule without declared type';
928
- throw new Error(`Validator for flag "${curr.flag}" not found for ${forType}`);
850
+ const constraint = {
851
+ options: {
852
+ scheme: schemes.map((scheme) => {
853
+ if (!(scheme instanceof RegExp) && typeof scheme !== 'string') {
854
+ throw new Error('scheme must be a RegExp or a String');
855
+ }
856
+ return typeof scheme === 'string' ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme;
857
+ }),
858
+ allowRelative: opts?.allowRelative || false,
859
+ relativeOnly: opts?.relativeOnly || false,
860
+ allowCredentials: opts?.allowCredentials || false,
861
+ },
862
+ };
863
+ return this.cloneWithRules([{ flag: 'uri', constraint }]);
864
+ }
865
+ // Array only
866
+ unique() {
867
+ return this.cloneWithRules([{ flag: 'unique' }]);
868
+ }
869
+ // Objects only
870
+ reference() {
871
+ return this.cloneWithRules([{ flag: 'reference' }]);
872
+ }
873
+ fields(rules) {
874
+ if (this._type !== 'Object') {
875
+ throw new Error('fields() can only be called on an object type');
929
876
  }
930
- let specConstraint = 'constraint' in curr ? curr.constraint : null;
931
- if (isFieldRef(specConstraint)) {
932
- specConstraint = lodash.get(context.parent, specConstraint.path);
877
+ const rule = this.cloneWithRules([]);
878
+ rule._fieldRules = rules;
879
+ return rule;
880
+ }
881
+ assetRequired() {
882
+ const base = getBaseType(this._typeDef);
883
+ let assetType;
884
+ if (base && ['image', 'file'].includes(base.name)) {
885
+ assetType = base.name === 'image' ? 'Image' : 'File';
933
886
  }
934
- let result;
935
- try {
936
- result = await validator(specConstraint, value, this._message, context);
887
+ else {
888
+ assetType = 'Asset';
937
889
  }
938
- catch (err) {
939
- const errorFromException = new ValidationError(`${pathToString(context.path)}: Exception occurred while validating value: ${err.message}`);
940
- return convertToValidationMarker(errorFromException, 'error', context);
890
+ return this.cloneWithRules([{ flag: 'assetRequired', constraint: { assetType } }]);
891
+ }
892
+ async validate(value, context) {
893
+ if (!context) {
894
+ throw new Error('missing context');
941
895
  }
942
- return convertToValidationMarker(result, this._level, context);
943
- }));
944
- return results.flat();
945
- }
946
- };
896
+ const valueIsEmpty = value === null || value === undefined;
897
+ // Short-circuit on optional, empty fields
898
+ if (valueIsEmpty && this._required === 'optional') {
899
+ return EMPTY_ARRAY;
900
+ }
901
+ const rules =
902
+ // Run only the _custom_ functions if the rule is not set to required or optional
903
+ this._required === undefined && valueIsEmpty
904
+ ? this._rules.filter((curr) => curr.flag === 'custom')
905
+ : this._rules;
906
+ const validators = (this._type && typeValidators[this._type]) || genericValidators;
907
+ const results = await Promise.all(rules.map(async (curr) => {
908
+ if (curr.flag === undefined) {
909
+ throw new Error('Invalid rule, did not contain "flag"-property');
910
+ }
911
+ const validator = validators[curr.flag];
912
+ if (!validator) {
913
+ const forType = this._type ? `type "${this._type}"` : 'rule without declared type';
914
+ throw new Error(`Validator for flag "${curr.flag}" not found for ${forType}`);
915
+ }
916
+ let specConstraint = 'constraint' in curr ? curr.constraint : null;
917
+ if (isFieldRef(specConstraint)) {
918
+ specConstraint = lodash.get(context.parent, specConstraint.path);
919
+ }
920
+ let result;
921
+ try {
922
+ result = await validator(specConstraint, value, this._message, context);
923
+ }
924
+ catch (err) {
925
+ const errorFromException = new ValidationError(`${pathToString(context.path)}: Exception occurred while validating value: ${err.message}`);
926
+ return convertToValidationMarker(errorFromException, 'error', context);
927
+ }
928
+ return convertToValidationMarker(result, this._level, context);
929
+ }));
930
+ return results.flat();
931
+ }
932
+ },
933
+ _a.FIELD_REF = FIELD_REF,
934
+ _a.array = (def) => new _a(def).type('Array'),
935
+ _a.object = (def) => new _a(def).type('Object'),
936
+ _a.string = (def) => new _a(def).type('String'),
937
+ _a.number = (def) => new _a(def).type('Number'),
938
+ _a.boolean = (def) => new _a(def).type('Boolean'),
939
+ _a.dateTime = (def) => new _a(def).type('Date'),
940
+ _a.valueOfField = (path) => ({
941
+ type: FIELD_REF,
942
+ path,
943
+ }),
944
+ _a);
947
945
 
948
946
  // import getClient from '../getClient'
949
947
  const memoizedWarnOnArraySlug = lodash.memoize(warnOnArraySlug);