@mono-lit/utility 0.0.3 → 0.0.5

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.
@@ -6,31 +6,7 @@ import { Deferred } from "devextreme/core/utils/deferred";
6
6
  import { useRouter } from "vue-router";
7
7
 
8
8
  //#region \0rolldown/runtime.js
9
- var __create = Object.create;
10
- var __defProp = Object.defineProperty;
11
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
- var __getOwnPropNames = Object.getOwnPropertyNames;
13
- var __getProtoOf = Object.getPrototypeOf;
14
- var __hasOwnProp = Object.prototype.hasOwnProperty;
15
9
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
19
- key = keys[i];
20
- if (!__hasOwnProp.call(to, key) && key !== except) {
21
- __defProp(to, key, {
22
- get: ((k) => from[k]).bind(null, key),
23
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
- });
25
- }
26
- }
27
- }
28
- return to;
29
- };
30
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
31
- value: mod,
32
- enumerable: true
33
- }) : target, mod));
34
10
 
35
11
  //#endregion
36
12
  //#region src/composables/state.ts
@@ -273,7 +249,7 @@ function monoProvide(options) {
273
249
 
274
250
  //#endregion
275
251
  //#region src/core/composables/use-static-datasource.ts
276
- const toArray$1 = (v) => v == null ? [] : Array.isArray(v) ? v : [v];
252
+ const toArray = (v) => v == null ? [] : Array.isArray(v) ? v : [v];
277
253
  const norm = (v, ci) => ci && typeof v === "string" ? v.toLocaleLowerCase() : v;
278
254
  const get = (obj, path) => {
279
255
  if (!obj) return void 0;
@@ -551,7 +527,7 @@ const dxResolve = (val) => {
551
527
  async function createStaticDatasource(opts) {
552
528
  try {
553
529
  const key = String(opts.key ?? "_Id");
554
- const local = toArray$1(typeof opts.data === "function" ? opts.data() : opts.data).map((x) => ({ ...x }));
530
+ const local = toArray(typeof opts.data === "function" ? opts.data() : opts.data).map((x) => ({ ...x }));
555
531
  let nextTemp = -1;
556
532
  const ensureKey = (row) => {
557
533
  if (row[key] == null) row[key] = nextTemp--;
@@ -663,2199 +639,172 @@ async function createStaticDatasource(opts) {
663
639
  }
664
640
 
665
641
  //#endregion
666
- //#region ../../node_modules/.pnpm/property-expr@2.0.6/node_modules/property-expr/index.js
667
- /**
668
- * Based on Kendo UI Core expression code <https://github.com/telerik/kendo-ui-core#license-information>
669
- */
670
- var require_property_expr = /* @__PURE__ */ __commonJSMin(((exports, module) => {
671
- function Cache(maxSize) {
672
- this._maxSize = maxSize;
673
- this.clear();
674
- }
675
- Cache.prototype.clear = function() {
676
- this._size = 0;
677
- this._values = Object.create(null);
678
- };
679
- Cache.prototype.get = function(key) {
680
- return this._values[key];
681
- };
682
- Cache.prototype.set = function(key, value) {
683
- this._size >= this._maxSize && this.clear();
684
- if (!(key in this._values)) this._size++;
685
- return this._values[key] = value;
686
- };
687
- var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g;
688
- var DIGIT_REGEX = /^\d+$/;
689
- var LEAD_DIGIT_REGEX = /^\d/;
690
- var SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g;
691
- var CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/;
692
- var MAX_CACHE_SIZE = 512;
693
- var pathCache = new Cache(MAX_CACHE_SIZE);
694
- var setCache = new Cache(MAX_CACHE_SIZE);
695
- var getCache = new Cache(MAX_CACHE_SIZE);
696
- module.exports = {
697
- Cache,
698
- split,
699
- normalizePath,
700
- setter: function(path) {
701
- var parts = normalizePath(path);
702
- return setCache.get(path) || setCache.set(path, function setter(obj, value) {
703
- var index = 0;
704
- var len = parts.length;
705
- var data = obj;
706
- while (index < len - 1) {
707
- var part = parts[index];
708
- if (part === "__proto__" || part === "constructor" || part === "prototype") return obj;
709
- data = data[parts[index++]];
710
- }
711
- data[parts[index]] = value;
712
- });
713
- },
714
- getter: function(path, safe) {
715
- var parts = normalizePath(path);
716
- return getCache.get(path) || getCache.set(path, function getter(data) {
717
- var index = 0, len = parts.length;
718
- while (index < len) if (data != null || !safe) data = data[parts[index++]];
719
- else return;
720
- return data;
721
- });
722
- },
723
- join: function(segments) {
724
- return segments.reduce(function(path, part) {
725
- return path + (isQuoted(part) || DIGIT_REGEX.test(part) ? "[" + part + "]" : (path ? "." : "") + part);
726
- }, "");
727
- },
728
- forEach: function(path, cb, thisArg) {
729
- forEach(Array.isArray(path) ? path : split(path), cb, thisArg);
730
- }
731
- };
732
- function normalizePath(path) {
733
- return pathCache.get(path) || pathCache.set(path, split(path).map(function(part) {
734
- return part.replace(CLEAN_QUOTES_REGEX, "$2");
735
- }));
736
- }
737
- function split(path) {
738
- return path.match(SPLIT_REGEX) || [""];
739
- }
740
- function forEach(parts, iter, thisArg) {
741
- var len = parts.length, part, idx = 0, isArray, isBracket;
742
- for (; idx < len; idx++) {
743
- part = parts[idx];
744
- if (part) {
745
- if (shouldBeQuoted(part)) part = "\"" + part + "\"";
746
- isBracket = isQuoted(part);
747
- isArray = !isBracket && /^\d+$/.test(part);
748
- iter.call(thisArg, part, isBracket, isArray, idx, parts);
749
- }
750
- }
751
- }
752
- function isQuoted(str) {
753
- return typeof str === "string" && str && ["'", "\""].indexOf(str.charAt(0)) !== -1;
754
- }
755
- function hasLeadingNumber(part) {
756
- return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX);
757
- }
758
- function hasSpecialChars(part) {
759
- return SPEC_CHAR_REGEX.test(part);
760
- }
761
- function shouldBeQuoted(part) {
762
- return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part));
763
- }
764
- }));
765
-
766
- //#endregion
767
- //#region ../../node_modules/.pnpm/tiny-case@1.0.3/node_modules/tiny-case/index.js
768
- var require_tiny_case = /* @__PURE__ */ __commonJSMin(((exports, module) => {
769
- const reWords = /[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g;
770
- const words = (str) => str.match(reWords) || [];
771
- const upperFirst = (str) => str[0].toUpperCase() + str.slice(1);
772
- const join = (str, d) => words(str).join(d).toLowerCase();
773
- const camelCase = (str) => words(str).reduce((acc, next) => `${acc}${!acc ? next.toLowerCase() : next[0].toUpperCase() + next.slice(1).toLowerCase()}`, "");
774
- const pascalCase = (str) => upperFirst(camelCase(str));
775
- const snakeCase = (str) => join(str, "_");
776
- const kebabCase = (str) => join(str, "-");
777
- const sentenceCase = (str) => upperFirst(join(str, " "));
778
- const titleCase = (str) => words(str).map(upperFirst).join(" ");
779
- module.exports = {
780
- words,
781
- upperFirst,
782
- camelCase,
783
- pascalCase,
784
- snakeCase,
785
- kebabCase,
786
- sentenceCase,
787
- titleCase
788
- };
789
- }));
790
-
791
- //#endregion
792
- //#region ../../node_modules/.pnpm/toposort@2.0.2/node_modules/toposort/index.js
793
- var require_toposort = /* @__PURE__ */ __commonJSMin(((exports, module) => {
794
- /**
795
- * Topological sorting function
796
- *
797
- * @param {Array} edges
798
- * @returns {Array}
799
- */
800
- module.exports = function(edges) {
801
- return toposort(uniqueNodes(edges), edges);
802
- };
803
- module.exports.array = toposort;
804
- function toposort(nodes, edges) {
805
- var cursor = nodes.length, sorted = new Array(cursor), visited = {}, i = cursor, outgoingEdges = makeOutgoingEdges(edges), nodesHash = makeNodesHash(nodes);
806
- edges.forEach(function(edge) {
807
- if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) throw new Error("Unknown node. There is an unknown node in the supplied edges.");
808
- });
809
- while (i--) if (!visited[i]) visit(nodes[i], i, /* @__PURE__ */ new Set());
810
- return sorted;
811
- function visit(node, i, predecessors) {
812
- if (predecessors.has(node)) {
813
- var nodeRep;
814
- try {
815
- nodeRep = ", node was:" + JSON.stringify(node);
816
- } catch (e) {
817
- nodeRep = "";
818
- }
819
- throw new Error("Cyclic dependency" + nodeRep);
820
- }
821
- if (!nodesHash.has(node)) throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(node));
822
- if (visited[i]) return;
823
- visited[i] = true;
824
- var outgoing = outgoingEdges.get(node) || /* @__PURE__ */ new Set();
825
- outgoing = Array.from(outgoing);
826
- if (i = outgoing.length) {
827
- predecessors.add(node);
828
- do {
829
- var child = outgoing[--i];
830
- visit(child, nodesHash.get(child), predecessors);
831
- } while (i);
832
- predecessors.delete(node);
833
- }
834
- sorted[--cursor] = node;
835
- }
836
- }
837
- function uniqueNodes(arr) {
838
- var res = /* @__PURE__ */ new Set();
839
- for (var i = 0, len = arr.length; i < len; i++) {
840
- var edge = arr[i];
841
- res.add(edge[0]);
842
- res.add(edge[1]);
843
- }
844
- return Array.from(res);
845
- }
846
- function makeOutgoingEdges(arr) {
847
- var edges = /* @__PURE__ */ new Map();
848
- for (var i = 0, len = arr.length; i < len; i++) {
849
- var edge = arr[i];
850
- if (!edges.has(edge[0])) edges.set(edge[0], /* @__PURE__ */ new Set());
851
- if (!edges.has(edge[1])) edges.set(edge[1], /* @__PURE__ */ new Set());
852
- edges.get(edge[0]).add(edge[1]);
853
- }
854
- return edges;
855
- }
856
- function makeNodesHash(arr) {
857
- var res = /* @__PURE__ */ new Map();
858
- for (var i = 0, len = arr.length; i < len; i++) res.set(arr[i], i);
859
- return res;
860
- }
861
- }));
862
-
863
- //#endregion
864
- //#region ../../node_modules/.pnpm/yup@1.7.1/node_modules/yup/index.esm.js
865
- var import_property_expr = require_property_expr();
866
- var import_tiny_case = require_tiny_case();
867
- var import_toposort = /* @__PURE__ */ __toESM(require_toposort());
868
- const toString = Object.prototype.toString;
869
- const errorToString = Error.prototype.toString;
870
- const regExpToString = RegExp.prototype.toString;
871
- const symbolToString = typeof Symbol !== "undefined" ? Symbol.prototype.toString : () => "";
872
- const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
873
- function printNumber(val) {
874
- if (val != +val) return "NaN";
875
- return val === 0 && 1 / val < 0 ? "-0" : "" + val;
876
- }
877
- function printSimpleValue(val, quoteStrings = false) {
878
- if (val == null || val === true || val === false) return "" + val;
879
- const typeOf = typeof val;
880
- if (typeOf === "number") return printNumber(val);
881
- if (typeOf === "string") return quoteStrings ? `"${val}"` : val;
882
- if (typeOf === "function") return "[Function " + (val.name || "anonymous") + "]";
883
- if (typeOf === "symbol") return symbolToString.call(val).replace(SYMBOL_REGEXP, "Symbol($1)");
884
- const tag = toString.call(val).slice(8, -1);
885
- if (tag === "Date") return isNaN(val.getTime()) ? "" + val : val.toISOString(val);
886
- if (tag === "Error" || val instanceof Error) return "[" + errorToString.call(val) + "]";
887
- if (tag === "RegExp") return regExpToString.call(val);
888
- return null;
889
- }
890
- function printValue(value, quoteStrings) {
891
- let result = printSimpleValue(value, quoteStrings);
892
- if (result !== null) return result;
893
- return JSON.stringify(value, function(key, value) {
894
- let result = printSimpleValue(this[key], quoteStrings);
895
- if (result !== null) return result;
896
- return value;
897
- }, 2);
898
- }
899
- function toArray(value) {
900
- return value == null ? [] : [].concat(value);
901
- }
902
- let _Symbol$toStringTag;
903
- let _Symbol$hasInstance;
904
- let _Symbol$toStringTag2;
905
- let strReg = /\$\{\s*(\w+)\s*\}/g;
906
- _Symbol$toStringTag = Symbol.toStringTag;
907
- var ValidationErrorNoStack = class {
908
- constructor(errorOrErrors, value, field, type) {
909
- this.name = void 0;
910
- this.message = void 0;
911
- this.value = void 0;
912
- this.path = void 0;
913
- this.type = void 0;
914
- this.params = void 0;
915
- this.errors = void 0;
916
- this.inner = void 0;
917
- this[_Symbol$toStringTag] = "Error";
918
- this.name = "ValidationError";
919
- this.value = value;
920
- this.path = field;
921
- this.type = type;
922
- this.errors = [];
923
- this.inner = [];
924
- toArray(errorOrErrors).forEach((err) => {
925
- if (ValidationError.isError(err)) {
926
- this.errors.push(...err.errors);
927
- const innerErrors = err.inner.length ? err.inner : [err];
928
- this.inner.push(...innerErrors);
929
- } else this.errors.push(err);
930
- });
931
- this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];
932
- }
933
- };
934
- _Symbol$hasInstance = Symbol.hasInstance;
935
- _Symbol$toStringTag2 = Symbol.toStringTag;
936
- var ValidationError = class ValidationError extends Error {
937
- static formatError(message, params) {
938
- const path = params.label || params.path || "this";
939
- params = Object.assign({}, params, {
940
- path,
941
- originalPath: params.path
942
- });
943
- if (typeof message === "string") return message.replace(strReg, (_, key) => printValue(params[key]));
944
- if (typeof message === "function") return message(params);
945
- return message;
946
- }
947
- static isError(err) {
948
- return err && err.name === "ValidationError";
949
- }
950
- constructor(errorOrErrors, value, field, type, disableStack) {
951
- const errorNoStack = new ValidationErrorNoStack(errorOrErrors, value, field, type);
952
- if (disableStack) return errorNoStack;
953
- super();
954
- this.value = void 0;
955
- this.path = void 0;
956
- this.type = void 0;
957
- this.params = void 0;
958
- this.errors = [];
959
- this.inner = [];
960
- this[_Symbol$toStringTag2] = "Error";
961
- this.name = errorNoStack.name;
962
- this.message = errorNoStack.message;
963
- this.type = errorNoStack.type;
964
- this.value = errorNoStack.value;
965
- this.path = errorNoStack.path;
966
- this.errors = errorNoStack.errors;
967
- this.inner = errorNoStack.inner;
968
- if (Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);
969
- }
970
- static [_Symbol$hasInstance](inst) {
971
- return ValidationErrorNoStack[Symbol.hasInstance](inst) || super[Symbol.hasInstance](inst);
972
- }
973
- };
974
- let mixed = {
975
- default: "${path} is invalid",
976
- required: "${path} is a required field",
977
- defined: "${path} must be defined",
978
- notNull: "${path} cannot be null",
979
- oneOf: "${path} must be one of the following values: ${values}",
980
- notOneOf: "${path} must not be one of the following values: ${values}",
981
- notType: ({ path, type, value, originalValue }) => {
982
- const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : ".";
983
- return type !== "mixed" ? `${path} must be a \`${type}\` type, but the final value was: \`${printValue(value, true)}\`` + castMsg : `${path} must match the configured type. The validated value was: \`${printValue(value, true)}\`` + castMsg;
984
- }
985
- };
986
- let string = {
987
- length: "${path} must be exactly ${length} characters",
988
- min: "${path} must be at least ${min} characters",
989
- max: "${path} must be at most ${max} characters",
990
- matches: "${path} must match the following: \"${regex}\"",
991
- email: "${path} must be a valid email",
992
- url: "${path} must be a valid URL",
993
- uuid: "${path} must be a valid UUID",
994
- datetime: "${path} must be a valid ISO date-time",
995
- datetime_precision: "${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits",
996
- datetime_offset: "${path} must be a valid ISO date-time with UTC \"Z\" timezone",
997
- trim: "${path} must be a trimmed string",
998
- lowercase: "${path} must be a lowercase string",
999
- uppercase: "${path} must be a upper case string"
1000
- };
1001
- let number = {
1002
- min: "${path} must be greater than or equal to ${min}",
1003
- max: "${path} must be less than or equal to ${max}",
1004
- lessThan: "${path} must be less than ${less}",
1005
- moreThan: "${path} must be greater than ${more}",
1006
- positive: "${path} must be a positive number",
1007
- negative: "${path} must be a negative number",
1008
- integer: "${path} must be an integer"
1009
- };
1010
- let date = {
1011
- min: "${path} field must be later than ${min}",
1012
- max: "${path} field must be at earlier than ${max}"
1013
- };
1014
- let boolean = { isValue: "${path} field must be ${value}" };
1015
- let object = {
1016
- noUnknown: "${path} field has unspecified keys: ${unknown}",
1017
- exact: "${path} object contains unknown properties: ${properties}"
1018
- };
1019
- let array = {
1020
- min: "${path} field must have at least ${min} items",
1021
- max: "${path} field must have less than or equal to ${max} items",
1022
- length: "${path} must have ${length} items"
1023
- };
1024
- let tuple = { notType: (params) => {
1025
- const { path, value, spec } = params;
1026
- const typeLen = spec.types.length;
1027
- if (Array.isArray(value)) {
1028
- if (value.length < typeLen) return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
1029
- if (value.length > typeLen) return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
1030
- }
1031
- return ValidationError.formatError(mixed.notType, params);
1032
- } };
1033
- var locale = Object.assign(Object.create(null), {
1034
- mixed,
1035
- string,
1036
- number,
1037
- date,
1038
- object,
1039
- array,
1040
- boolean,
1041
- tuple
1042
- });
1043
- const isSchema = (obj) => obj && obj.__isYupSchema__;
1044
- var Condition = class Condition {
1045
- static fromOptions(refs, config) {
1046
- if (!config.then && !config.otherwise) throw new TypeError("either `then:` or `otherwise:` is required for `when()` conditions");
1047
- let { is, then, otherwise } = config;
1048
- let check = typeof is === "function" ? is : (...values) => values.every((value) => value === is);
1049
- return new Condition(refs, (values, schema) => {
1050
- var _branch;
1051
- let branch = check(...values) ? then : otherwise;
1052
- return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;
1053
- });
1054
- }
1055
- constructor(refs, builder) {
1056
- this.fn = void 0;
1057
- this.refs = refs;
1058
- this.refs = refs;
1059
- this.fn = builder;
1060
- }
1061
- resolve(base, options) {
1062
- let values = this.refs.map((ref) => ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context));
1063
- let schema = this.fn(values, base, options);
1064
- if (schema === void 0 || schema === base) return base;
1065
- if (!isSchema(schema)) throw new TypeError("conditions must return a schema object");
1066
- return schema.resolve(options);
1067
- }
1068
- };
1069
- const prefixes = {
1070
- context: "$",
1071
- value: "."
1072
- };
1073
- var Reference = class {
1074
- constructor(key, options = {}) {
1075
- this.key = void 0;
1076
- this.isContext = void 0;
1077
- this.isValue = void 0;
1078
- this.isSibling = void 0;
1079
- this.path = void 0;
1080
- this.getter = void 0;
1081
- this.map = void 0;
1082
- if (typeof key !== "string") throw new TypeError("ref must be a string, got: " + key);
1083
- this.key = key.trim();
1084
- if (key === "") throw new TypeError("ref must be a non-empty string");
1085
- this.isContext = this.key[0] === prefixes.context;
1086
- this.isValue = this.key[0] === prefixes.value;
1087
- this.isSibling = !this.isContext && !this.isValue;
1088
- let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : "";
1089
- this.path = this.key.slice(prefix.length);
1090
- this.getter = this.path && (0, import_property_expr.getter)(this.path, true);
1091
- this.map = options.map;
1092
- }
1093
- getValue(value, parent, context) {
1094
- let result = this.isContext ? context : this.isValue ? value : parent;
1095
- if (this.getter) result = this.getter(result || {});
1096
- if (this.map) result = this.map(result);
1097
- return result;
1098
- }
1099
- /**
1100
- *
1101
- * @param {*} value
1102
- * @param {Object} options
1103
- * @param {Object=} options.context
1104
- * @param {Object=} options.parent
1105
- */
1106
- cast(value, options) {
1107
- return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);
1108
- }
1109
- resolve() {
1110
- return this;
1111
- }
1112
- describe() {
1113
- return {
1114
- type: "ref",
1115
- key: this.key
1116
- };
1117
- }
1118
- toString() {
1119
- return `Ref(${this.key})`;
1120
- }
1121
- static isRef(value) {
1122
- return value && value.__isYupRef;
1123
- }
1124
- };
1125
- Reference.prototype.__isYupRef = true;
1126
- const isAbsent = (value) => value == null;
1127
- function createValidation(config) {
1128
- function validate({ value, path = "", options, originalValue, schema }, panic, next) {
1129
- const { name, test, params, message, skipAbsent } = config;
1130
- let { parent, context, abortEarly = schema.spec.abortEarly, disableStackTrace = schema.spec.disableStackTrace } = options;
1131
- const resolveOptions = {
1132
- value,
1133
- parent,
1134
- context
1135
- };
1136
- function createError(overrides = {}) {
1137
- const nextParams = resolveParams(Object.assign({
1138
- value,
1139
- originalValue,
1140
- label: schema.spec.label,
1141
- path: overrides.path || path,
1142
- spec: schema.spec,
1143
- disableStackTrace: overrides.disableStackTrace || disableStackTrace
1144
- }, params, overrides.params), resolveOptions);
1145
- const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, nextParams.disableStackTrace);
1146
- error.params = nextParams;
1147
- return error;
1148
- }
1149
- const invalid = abortEarly ? panic : next;
1150
- let ctx = {
1151
- path,
1152
- parent,
1153
- type: name,
1154
- from: options.from,
1155
- createError,
1156
- resolve(item) {
1157
- return resolveMaybeRef(item, resolveOptions);
1158
- },
1159
- options,
1160
- originalValue,
1161
- schema
1162
- };
1163
- const handleResult = (validOrError) => {
1164
- if (ValidationError.isError(validOrError)) invalid(validOrError);
1165
- else if (!validOrError) invalid(createError());
1166
- else next(null);
1167
- };
1168
- const handleError = (err) => {
1169
- if (ValidationError.isError(err)) invalid(err);
1170
- else panic(err);
1171
- };
1172
- if (skipAbsent && isAbsent(value)) return handleResult(true);
1173
- let result;
1174
- try {
1175
- var _result;
1176
- result = test.call(ctx, value, ctx);
1177
- if (typeof ((_result = result) == null ? void 0 : _result.then) === "function") {
1178
- if (options.sync) throw new Error(`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. This test will finish after the validate call has returned`);
1179
- return Promise.resolve(result).then(handleResult, handleError);
1180
- }
1181
- } catch (err) {
1182
- handleError(err);
1183
- return;
1184
- }
1185
- handleResult(result);
642
+ //#region src/core/composables/schema-validate.ts
643
+ /** yup ≥1.7 also exposes `~standard`, so yup must be checked first. */
644
+ const isYupSchema = (schema) => !!schema && (schema.__isYupSchema__ === true || typeof schema.validateAt === "function");
645
+ const isStandardSchema = (schema) => !!schema && typeof schema["~standard"]?.validate === "function";
646
+ let warnedUnknown = false;
647
+ function warnUnknown(schema) {
648
+ if (warnedUnknown) return;
649
+ warnedUnknown = true;
650
+ console.warn("[mono-utility] schema validation: expected a yup schema or a Standard Schema (e.g. Valibot), got", schema);
651
+ }
652
+ /** `'items[0].name'` / `'a["b.c"]'` / `'address.city'` → key list. */
653
+ function parsePath(path) {
654
+ if (path === void 0 || path === null || path === "") return [];
655
+ if (typeof path === "number") return [path];
656
+ const keys = [];
657
+ const re = /\[\s*"([^"]*)"\s*\]|\[\s*'([^']*)'\s*\]|\[(\d+)\]|([^.[\]]+)/g;
658
+ let m;
659
+ while (m = re.exec(path)) if (m[1] !== void 0) keys.push(m[1]);
660
+ else if (m[2] !== void 0) keys.push(m[2]);
661
+ else if (m[3] !== void 0) keys.push(Number(m[3]));
662
+ else keys.push(m[4]);
663
+ return keys;
664
+ }
665
+ const sameKey = (a, b) => String(a) === String(b);
666
+ const startsWith = (keys, prefix) => prefix.length <= keys.length && prefix.every((k, i) => sameKey(k, keys[i]));
667
+ const isSlot = (v) => v !== null && typeof v === "object" && "valid" in v && "message" in v;
668
+ /** Accept a Vue Ref or the plain/reactive object itself, without importing vue. */
669
+ const unwrapError = (error) => error && error.__v_isRef ? error.value : error;
670
+ /** Walk `keys` into the error object; never creates anything. */
671
+ function getNode(error, keys) {
672
+ let cursor = error;
673
+ for (const k of keys) {
674
+ if (cursor === null || typeof cursor !== "object") return void 0;
675
+ cursor = cursor[k];
676
+ }
677
+ return cursor;
678
+ }
679
+ /** Set every `{ valid, message }` slot under `node` back to valid. */
680
+ function resetSlots(node) {
681
+ if (node === null || typeof node !== "object") return;
682
+ if (isSlot(node)) {
683
+ node.valid = true;
684
+ node.message = "";
685
+ return;
1186
686
  }
1187
- validate.OPTIONS = config;
1188
- return validate;
687
+ for (const key of Object.keys(node)) resetSlots(node[key]);
1189
688
  }
1190
- function resolveParams(params, options) {
1191
- if (!params) return params;
1192
- for (const key of Object.keys(params)) params[key] = resolveMaybeRef(params[key], options);
1193
- return params;
689
+ /** `true` when every slot under `node` is valid. */
690
+ function everyValid(node) {
691
+ if (node === null || typeof node !== "object") return true;
692
+ if (isSlot(node)) return !!node.valid;
693
+ return Object.keys(node).every((k) => everyValid(node[k]));
1194
694
  }
1195
- function resolveMaybeRef(item, options) {
1196
- return Reference.isRef(item) ? item.getValue(options.value, options.parent, options.context) : item;
1197
- }
1198
- function getIn(schema, path, value, context = value) {
1199
- let parent, lastPart, lastPartDebug;
1200
- if (!path) return {
1201
- parent,
1202
- parentPath: path,
1203
- schema
1204
- };
1205
- (0, import_property_expr.forEach)(path, (_part, isBracket, isArray) => {
1206
- let part = isBracket ? _part.slice(1, _part.length - 1) : _part;
1207
- schema = schema.resolve({
1208
- context,
1209
- parent,
1210
- value
1211
- });
1212
- let isTuple = schema.type === "tuple";
1213
- let idx = isArray ? parseInt(part, 10) : 0;
1214
- if (schema.innerType || isTuple) {
1215
- if (isTuple && !isArray) throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${lastPartDebug}" must contain an index to the tuple element, e.g. "${lastPartDebug}[0]"`);
1216
- if (value && idx >= value.length) throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. because there is no value at that index. `);
1217
- parent = value;
1218
- value = value && value[idx];
1219
- schema = isTuple ? schema.spec.types[idx] : schema.innerType;
1220
- }
1221
- if (!isArray) {
1222
- if (!schema.fields || !schema.fields[part]) throw new Error(`The schema does not contain the path: ${path}. (failed at: ${lastPartDebug} which is a type: "${schema.type}")`);
1223
- parent = value;
1224
- value = value && value[part];
1225
- schema = schema.fields[part];
1226
- }
1227
- lastPart = part;
1228
- lastPartDebug = isBracket ? "[" + _part + "]" : "." + _part;
1229
- });
1230
- return {
1231
- schema,
1232
- parent,
1233
- parentPath: lastPart
1234
- };
1235
- }
1236
- var ReferenceSet = class ReferenceSet extends Set {
1237
- describe() {
1238
- const description = [];
1239
- for (const item of this.values()) description.push(Reference.isRef(item) ? item.describe() : item);
1240
- return description;
1241
- }
1242
- resolveAll(resolve) {
1243
- let result = [];
1244
- for (const item of this.values()) result.push(resolve(item));
1245
- return result;
1246
- }
1247
- clone() {
1248
- return new ReferenceSet(this.values());
1249
- }
1250
- merge(newItems, removeItems) {
1251
- const next = this.clone();
1252
- newItems.forEach((value) => next.add(value));
1253
- removeItems.forEach((value) => next.delete(value));
1254
- return next;
695
+ /**
696
+ * Write issues into the error object. Only slots that already exist are
697
+ * touched; the first message for a slot wins. An issue on a nested object/array
698
+ * with no slot of its own is ignored, like today's yup behaviour.
699
+ */
700
+ function applyIssues(error, issues) {
701
+ const seen = /* @__PURE__ */ new Set();
702
+ for (const issue of issues) {
703
+ const slot = getNode(error, issue.keys);
704
+ if (!isSlot(slot) || seen.has(slot)) continue;
705
+ seen.add(slot);
706
+ slot.valid = false;
707
+ slot.message = issue.message;
1255
708
  }
1256
- };
1257
- function clone(src, seen = /* @__PURE__ */ new Map()) {
1258
- if (isSchema(src) || !src || typeof src !== "object") return src;
1259
- if (seen.has(src)) return seen.get(src);
1260
- let copy;
1261
- if (src instanceof Date) {
1262
- copy = new Date(src.getTime());
1263
- seen.set(src, copy);
1264
- } else if (src instanceof RegExp) {
1265
- copy = new RegExp(src);
1266
- seen.set(src, copy);
1267
- } else if (Array.isArray(src)) {
1268
- copy = new Array(src.length);
1269
- seen.set(src, copy);
1270
- for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);
1271
- } else if (src instanceof Map) {
1272
- copy = /* @__PURE__ */ new Map();
1273
- seen.set(src, copy);
1274
- for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));
1275
- } else if (src instanceof Set) {
1276
- copy = /* @__PURE__ */ new Set();
1277
- seen.set(src, copy);
1278
- for (const v of src) copy.add(clone(v, seen));
1279
- } else if (src instanceof Object) {
1280
- copy = {};
1281
- seen.set(src, copy);
1282
- for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);
1283
- } else throw Error(`Unable to clone ${src}`);
1284
- return copy;
1285
709
  }
1286
710
  /**
1287
- * Copied from @standard-schema/spec to avoid having a dependency on it.
1288
- * https://github.com/standard-schema/standard-schema/blob/main/packages/spec/src/index.ts
711
+ * Drop issues for keys the input doesn't carry: a field that is absent from
712
+ * `input` is not part of this form, so it isn't validated (the yup helper has
713
+ * always worked on the "partial" schema of present keys).
1289
714
  */
1290
- function createStandardPath(path) {
1291
- if (!(path != null && path.length)) return;
1292
- const segments = [];
1293
- let currentSegment = "";
1294
- let inBrackets = false;
1295
- let inQuotes = false;
1296
- for (let i = 0; i < path.length; i++) {
1297
- const char = path[i];
1298
- if (char === "[" && !inQuotes) {
1299
- if (currentSegment) {
1300
- segments.push(...currentSegment.split(".").filter(Boolean));
1301
- currentSegment = "";
1302
- }
1303
- inBrackets = true;
1304
- continue;
1305
- }
1306
- if (char === "]" && !inQuotes) {
1307
- if (currentSegment) {
1308
- if (/^\d+$/.test(currentSegment)) segments.push(currentSegment);
1309
- else segments.push(currentSegment.replace(/^"|"$/g, ""));
1310
- currentSegment = "";
1311
- }
1312
- inBrackets = false;
1313
- continue;
1314
- }
1315
- if (char === "\"") {
1316
- inQuotes = !inQuotes;
1317
- continue;
1318
- }
1319
- if (char === "." && !inBrackets && !inQuotes) {
1320
- if (currentSegment) {
1321
- segments.push(currentSegment);
1322
- currentSegment = "";
1323
- }
1324
- continue;
1325
- }
1326
- currentSegment += char;
715
+ function presentInInput(input, keys) {
716
+ let cursor = input;
717
+ for (const k of keys) {
718
+ if (cursor === null || typeof cursor !== "object") return true;
719
+ if (!(k in cursor)) return false;
720
+ cursor = cursor[k];
1327
721
  }
1328
- if (currentSegment) segments.push(...currentSegment.split(".").filter(Boolean));
1329
- return segments;
722
+ return true;
1330
723
  }
1331
- function createStandardIssues(error, parentPath) {
1332
- const path = parentPath ? `${parentPath}.${error.path}` : error.path;
1333
- return error.errors.map((err) => ({
1334
- message: err,
1335
- path: createStandardPath(path)
724
+ function yupIssues(e) {
725
+ if (!e || !Array.isArray(e.errors)) throw e;
726
+ return (Array.isArray(e.inner) && e.inner.length ? e.inner : [e]).map((err) => ({
727
+ keys: parsePath(err.path),
728
+ message: String(err.message ?? "")
1336
729
  }));
1337
730
  }
1338
- function issuesFromValidationError(error, parentPath) {
1339
- var _error$inner;
1340
- if (!((_error$inner = error.inner) != null && _error$inner.length) && error.errors.length) return createStandardIssues(error, parentPath);
1341
- const path = parentPath ? `${parentPath}.${error.path}` : error.path;
1342
- return error.inner.flatMap((err) => issuesFromValidationError(err, path));
1343
- }
1344
- var Schema = class {
1345
- constructor(options) {
1346
- this.type = void 0;
1347
- this.deps = [];
1348
- this.tests = void 0;
1349
- this.transforms = void 0;
1350
- this.conditions = [];
1351
- this._mutate = void 0;
1352
- this.internalTests = {};
1353
- this._whitelist = new ReferenceSet();
1354
- this._blacklist = new ReferenceSet();
1355
- this.exclusiveTests = Object.create(null);
1356
- this._typeCheck = void 0;
1357
- this.spec = void 0;
1358
- this.tests = [];
1359
- this.transforms = [];
1360
- this.withMutation(() => {
1361
- this.typeError(mixed.notType);
1362
- });
1363
- this.type = options.type;
1364
- this._typeCheck = options.check;
1365
- this.spec = Object.assign({
1366
- strip: false,
1367
- strict: false,
1368
- abortEarly: true,
1369
- recursive: true,
1370
- disableStackTrace: false,
1371
- nullable: false,
1372
- optional: true,
1373
- coerce: true
1374
- }, options == null ? void 0 : options.spec);
1375
- this.withMutation((s) => {
1376
- s.nonNullable();
1377
- });
1378
- }
1379
- get _type() {
1380
- return this.type;
1381
- }
1382
- clone(spec) {
1383
- if (this._mutate) {
1384
- if (spec) Object.assign(this.spec, spec);
1385
- return this;
1386
- }
1387
- const next = Object.create(Object.getPrototypeOf(this));
1388
- next.type = this.type;
1389
- next._typeCheck = this._typeCheck;
1390
- next._whitelist = this._whitelist.clone();
1391
- next._blacklist = this._blacklist.clone();
1392
- next.internalTests = Object.assign({}, this.internalTests);
1393
- next.exclusiveTests = Object.assign({}, this.exclusiveTests);
1394
- next.deps = [...this.deps];
1395
- next.conditions = [...this.conditions];
1396
- next.tests = [...this.tests];
1397
- next.transforms = [...this.transforms];
1398
- next.spec = clone(Object.assign({}, this.spec, spec));
1399
- return next;
1400
- }
1401
- label(label) {
1402
- let next = this.clone();
1403
- next.spec.label = label;
1404
- return next;
1405
- }
1406
- meta(...args) {
1407
- if (args.length === 0) return this.spec.meta;
1408
- let next = this.clone();
1409
- next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);
1410
- return next;
1411
- }
1412
- withMutation(fn) {
1413
- let before = this._mutate;
1414
- this._mutate = true;
1415
- let result = fn(this);
1416
- this._mutate = before;
1417
- return result;
1418
- }
1419
- concat(schema) {
1420
- if (!schema || schema === this) return this;
1421
- if (schema.type !== this.type && this.type !== "mixed") throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`);
1422
- let base = this;
1423
- let combined = schema.clone();
1424
- combined.spec = Object.assign({}, base.spec, combined.spec);
1425
- combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests);
1426
- combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);
1427
- combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist);
1428
- combined.tests = base.tests;
1429
- combined.exclusiveTests = base.exclusiveTests;
1430
- combined.withMutation((next) => {
1431
- schema.tests.forEach((fn) => {
1432
- next.test(fn.OPTIONS);
1433
- });
1434
- });
1435
- combined.transforms = [...base.transforms, ...combined.transforms];
1436
- return combined;
1437
- }
1438
- isType(v) {
1439
- if (v == null) {
1440
- if (this.spec.nullable && v === null) return true;
1441
- if (this.spec.optional && v === void 0) return true;
1442
- return false;
1443
- }
1444
- return this._typeCheck(v);
1445
- }
1446
- resolve(options) {
1447
- let schema = this;
1448
- if (schema.conditions.length) {
1449
- let conditions = schema.conditions;
1450
- schema = schema.clone();
1451
- schema.conditions = [];
1452
- schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);
1453
- schema = schema.resolve(options);
1454
- }
1455
- return schema;
1456
- }
1457
- resolveOptions(options) {
1458
- var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack;
1459
- return Object.assign({}, options, {
1460
- from: options.from || [],
1461
- strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,
1462
- abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,
1463
- recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive,
1464
- disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace
1465
- });
1466
- }
1467
- /**
1468
- * Run the configured transform pipeline over an input value.
1469
- */
1470
- cast(value, options = {}) {
1471
- let resolvedSchema = this.resolve(Object.assign({}, options, { value }));
1472
- let allowOptionality = options.assert === "ignore-optionality";
1473
- let result = resolvedSchema._cast(value, options);
1474
- if (options.assert !== false && !resolvedSchema.isType(result)) {
1475
- if (allowOptionality && isAbsent(result)) return result;
1476
- let formattedValue = printValue(value);
1477
- let formattedResult = printValue(result);
1478
- throw new TypeError(`The value of ${options.path || "field"} could not be cast to a value that satisfies the schema type: "${resolvedSchema.type}". \n\nattempted value: ${formattedValue} \n` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ""));
1479
- }
1480
- return result;
1481
- }
1482
- _cast(rawValue, options) {
1483
- let value = rawValue === void 0 ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this, options), rawValue);
1484
- if (value === void 0) value = this.getDefault(options);
1485
- return value;
1486
- }
1487
- _validate(_value, options = {}, panic, next) {
1488
- let { path, originalValue = _value, strict = this.spec.strict } = options;
1489
- let value = _value;
1490
- if (!strict) value = this._cast(value, Object.assign({ assert: false }, options));
1491
- let initialTests = [];
1492
- for (let test of Object.values(this.internalTests)) if (test) initialTests.push(test);
1493
- this.runTests({
1494
- path,
1495
- value,
1496
- originalValue,
1497
- options,
1498
- tests: initialTests
1499
- }, panic, (initialErrors) => {
1500
- if (initialErrors.length) return next(initialErrors, value);
1501
- this.runTests({
1502
- path,
1503
- value,
1504
- originalValue,
1505
- options,
1506
- tests: this.tests
1507
- }, panic, next);
1508
- });
1509
- }
1510
- /**
1511
- * Executes a set of validations, either schema, produced Tests or a nested
1512
- * schema validate result.
1513
- */
1514
- runTests(runOptions, panic, next) {
1515
- let fired = false;
1516
- let { tests, value, originalValue, path, options } = runOptions;
1517
- let panicOnce = (arg) => {
1518
- if (fired) return;
1519
- fired = true;
1520
- panic(arg, value);
1521
- };
1522
- let nextOnce = (arg) => {
1523
- if (fired) return;
1524
- fired = true;
1525
- next(arg, value);
1526
- };
1527
- let count = tests.length;
1528
- let nestedErrors = [];
1529
- if (!count) return nextOnce([]);
1530
- let args = {
1531
- value,
1532
- originalValue,
1533
- path,
1534
- options,
1535
- schema: this
1536
- };
1537
- for (let i = 0; i < tests.length; i++) {
1538
- const test = tests[i];
1539
- test(args, panicOnce, function finishTestRun(err) {
1540
- if (err) Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err);
1541
- if (--count <= 0) nextOnce(nestedErrors);
1542
- });
1543
- }
1544
- }
1545
- asNestedTest({ key, index, parent, parentPath, originalParent, options }) {
1546
- const k = key != null ? key : index;
1547
- if (k == null) throw TypeError("Must include `key` or `index` for nested validations");
1548
- const isIndex = typeof k === "number";
1549
- let value = parent[k];
1550
- const testOptions = Object.assign({}, options, {
1551
- strict: true,
1552
- parent,
1553
- value,
1554
- originalValue: originalParent[k],
1555
- key: void 0,
1556
- [isIndex ? "index" : "key"]: k,
1557
- path: isIndex || k.includes(".") ? `${parentPath || ""}[${isIndex ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : "") + key
1558
- });
1559
- return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);
1560
- }
1561
- validate(value, options) {
1562
- var _options$disableStack2;
1563
- let schema = this.resolve(Object.assign({}, options, { value }));
1564
- let disableStackTrace = (_options$disableStack2 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace;
1565
- return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {
1566
- if (ValidationError.isError(error)) error.value = parsed;
1567
- reject(error);
1568
- }, (errors, validated) => {
1569
- if (errors.length) reject(new ValidationError(errors, validated, void 0, void 0, disableStackTrace));
1570
- else resolve(validated);
1571
- }));
1572
- }
1573
- validateSync(value, options) {
1574
- var _options$disableStack3;
1575
- let schema = this.resolve(Object.assign({}, options, { value }));
1576
- let result;
1577
- let disableStackTrace = (_options$disableStack3 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace;
1578
- schema._validate(value, Object.assign({}, options, { sync: true }), (error, parsed) => {
1579
- if (ValidationError.isError(error)) error.value = parsed;
1580
- throw error;
1581
- }, (errors, validated) => {
1582
- if (errors.length) throw new ValidationError(errors, value, void 0, void 0, disableStackTrace);
1583
- result = validated;
1584
- });
1585
- return result;
1586
- }
1587
- isValid(value, options) {
1588
- return this.validate(value, options).then(() => true, (err) => {
1589
- if (ValidationError.isError(err)) return false;
1590
- throw err;
1591
- });
1592
- }
1593
- isValidSync(value, options) {
1594
- try {
1595
- this.validateSync(value, options);
1596
- return true;
1597
- } catch (err) {
1598
- if (ValidationError.isError(err)) return false;
1599
- throw err;
1600
- }
1601
- }
1602
- _getDefault(options) {
1603
- let defaultValue = this.spec.default;
1604
- if (defaultValue == null) return defaultValue;
1605
- return typeof defaultValue === "function" ? defaultValue.call(this, options) : clone(defaultValue);
1606
- }
1607
- getDefault(options) {
1608
- return this.resolve(options || {})._getDefault(options);
1609
- }
1610
- default(def) {
1611
- if (arguments.length === 0) return this._getDefault();
1612
- return this.clone({ default: def });
1613
- }
1614
- strict(isStrict = true) {
1615
- return this.clone({ strict: isStrict });
1616
- }
1617
- nullability(nullable, message) {
1618
- const next = this.clone({ nullable });
1619
- next.internalTests.nullable = createValidation({
1620
- message,
1621
- name: "nullable",
1622
- test(value) {
1623
- return value === null ? this.schema.spec.nullable : true;
1624
- }
1625
- });
1626
- return next;
1627
- }
1628
- optionality(optional, message) {
1629
- const next = this.clone({ optional });
1630
- next.internalTests.optionality = createValidation({
1631
- message,
1632
- name: "optionality",
1633
- test(value) {
1634
- return value === void 0 ? this.schema.spec.optional : true;
1635
- }
1636
- });
1637
- return next;
1638
- }
1639
- optional() {
1640
- return this.optionality(true);
1641
- }
1642
- defined(message = mixed.defined) {
1643
- return this.optionality(false, message);
1644
- }
1645
- nullable() {
1646
- return this.nullability(true);
1647
- }
1648
- nonNullable(message = mixed.notNull) {
1649
- return this.nullability(false, message);
1650
- }
1651
- required(message = mixed.required) {
1652
- return this.clone().withMutation((next) => next.nonNullable(message).defined(message));
1653
- }
1654
- notRequired() {
1655
- return this.clone().withMutation((next) => next.nullable().optional());
1656
- }
1657
- transform(fn) {
1658
- let next = this.clone();
1659
- next.transforms.push(fn);
1660
- return next;
1661
- }
1662
- /**
1663
- * Adds a test function to the schema's queue of tests.
1664
- * tests can be exclusive or non-exclusive.
1665
- *
1666
- * - exclusive tests, will replace any existing tests of the same name.
1667
- * - non-exclusive: can be stacked
1668
- *
1669
- * If a non-exclusive test is added to a schema with an exclusive test of the same name
1670
- * the exclusive test is removed and further tests of the same name will be stacked.
1671
- *
1672
- * If an exclusive test is added to a schema with non-exclusive tests of the same name
1673
- * the previous tests are removed and further tests of the same name will replace each other.
1674
- */
1675
- test(...args) {
1676
- let opts;
1677
- if (args.length === 1) {
1678
- if (typeof args[0] === "function") opts = { test: args[0] };
1679
- else opts = args[0];
1680
- } else if (args.length === 2) opts = {
1681
- name: args[0],
1682
- test: args[1]
1683
- };
1684
- else opts = {
1685
- name: args[0],
1686
- message: args[1],
1687
- test: args[2]
1688
- };
1689
- if (opts.message === void 0) opts.message = mixed.default;
1690
- if (typeof opts.test !== "function") throw new TypeError("`test` is a required parameters");
1691
- let next = this.clone();
1692
- let validate = createValidation(opts);
1693
- let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;
1694
- if (opts.exclusive) {
1695
- if (!opts.name) throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");
1696
- }
1697
- if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;
1698
- next.tests = next.tests.filter((fn) => {
1699
- if (fn.OPTIONS.name === opts.name) {
1700
- if (isExclusive) return false;
1701
- if (fn.OPTIONS.test === validate.OPTIONS.test) return false;
1702
- }
1703
- return true;
1704
- });
1705
- next.tests.push(validate);
1706
- return next;
1707
- }
1708
- when(keys, options) {
1709
- if (!Array.isArray(keys) && typeof keys !== "string") {
1710
- options = keys;
1711
- keys = ".";
1712
- }
1713
- let next = this.clone();
1714
- let deps = toArray(keys).map((key) => new Reference(key));
1715
- deps.forEach((dep) => {
1716
- if (dep.isSibling) next.deps.push(dep.key);
1717
- });
1718
- next.conditions.push(typeof options === "function" ? new Condition(deps, options) : Condition.fromOptions(deps, options));
1719
- return next;
1720
- }
1721
- typeError(message) {
1722
- let next = this.clone();
1723
- next.internalTests.typeError = createValidation({
1724
- message,
1725
- name: "typeError",
1726
- skipAbsent: true,
1727
- test(value) {
1728
- if (!this.schema._typeCheck(value)) return this.createError({ params: { type: this.schema.type } });
1729
- return true;
1730
- }
1731
- });
1732
- return next;
1733
- }
1734
- oneOf(enums, message = mixed.oneOf) {
1735
- let next = this.clone();
1736
- enums.forEach((val) => {
1737
- next._whitelist.add(val);
1738
- next._blacklist.delete(val);
1739
- });
1740
- next.internalTests.whiteList = createValidation({
1741
- message,
1742
- name: "oneOf",
1743
- skipAbsent: true,
1744
- test(value) {
1745
- let valids = this.schema._whitelist;
1746
- let resolved = valids.resolveAll(this.resolve);
1747
- return resolved.includes(value) ? true : this.createError({ params: {
1748
- values: Array.from(valids).join(", "),
1749
- resolved
1750
- } });
1751
- }
1752
- });
1753
- return next;
1754
- }
1755
- notOneOf(enums, message = mixed.notOneOf) {
1756
- let next = this.clone();
1757
- enums.forEach((val) => {
1758
- next._blacklist.add(val);
1759
- next._whitelist.delete(val);
1760
- });
1761
- next.internalTests.blacklist = createValidation({
1762
- message,
1763
- name: "notOneOf",
1764
- test(value) {
1765
- let invalids = this.schema._blacklist;
1766
- let resolved = invalids.resolveAll(this.resolve);
1767
- if (resolved.includes(value)) return this.createError({ params: {
1768
- values: Array.from(invalids).join(", "),
1769
- resolved
1770
- } });
1771
- return true;
1772
- }
1773
- });
1774
- return next;
1775
- }
1776
- strip(strip = true) {
1777
- let next = this.clone();
1778
- next.spec.strip = strip;
1779
- return next;
1780
- }
1781
- /**
1782
- * Return a serialized description of the schema including validations, flags, types etc.
1783
- *
1784
- * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).
1785
- */
1786
- describe(options) {
1787
- const next = (options ? this.resolve(options) : this).clone();
1788
- const { label, meta, optional, nullable } = next.spec;
731
+ /** Rebuild an object schema keeping only the keys present in `input`, recursively. */
732
+ function yupPartial(schema, input) {
733
+ if (!schema || !schema.fields || input === null || typeof input !== "object" || Array.isArray(input)) return schema;
734
+ const keys = Object.keys(schema.fields).filter((k) => k in input);
735
+ let partial = schema.pick(keys);
736
+ const nested = {};
737
+ for (const k of keys) {
738
+ const field = schema.fields[k];
739
+ const value = input[k];
740
+ if (field?.type === "object" && field.fields && value !== null && typeof value === "object" && !Array.isArray(value)) nested[k] = yupPartial(field, value);
741
+ }
742
+ if (Object.keys(nested).length) partial = partial.shape(nested);
743
+ return partial;
744
+ }
745
+ async function runYup(schema, input, field) {
746
+ try {
747
+ if (field?.length) await schema.validateAt(field.map(String).join("."), input, { abortEarly: false });
748
+ else await yupPartial(schema, input).validate(input, { abortEarly: false });
1789
749
  return {
1790
- meta,
1791
- label,
1792
- optional,
1793
- nullable,
1794
- default: next.getDefault(options),
1795
- type: next.type,
1796
- oneOf: next._whitelist.describe(),
1797
- notOneOf: next._blacklist.describe(),
1798
- tests: next.tests.filter((n, idx, list) => list.findIndex((c) => c.OPTIONS.name === n.OPTIONS.name) === idx).map((fn) => {
1799
- const params = fn.OPTIONS.params && options ? resolveParams(Object.assign({}, fn.OPTIONS.params), options) : fn.OPTIONS.params;
1800
- return {
1801
- name: fn.OPTIONS.name,
1802
- params
1803
- };
1804
- })
750
+ ok: true,
751
+ issues: []
1805
752
  };
1806
- }
1807
- get ["~standard"]() {
1808
- const schema = this;
753
+ } catch (e) {
1809
754
  return {
1810
- version: 1,
1811
- vendor: "yup",
1812
- async validate(value) {
1813
- try {
1814
- return { value: await schema.validate(value, { abortEarly: false }) };
1815
- } catch (err) {
1816
- if (err instanceof ValidationError) return { issues: issuesFromValidationError(err) };
1817
- throw err;
1818
- }
1819
- }
755
+ ok: false,
756
+ issues: yupIssues(e).map((i) => field?.length && !startsWith(i.keys, field) ? {
757
+ ...i,
758
+ keys: [...field, ...i.keys]
759
+ } : i)
1820
760
  };
1821
761
  }
1822
- };
1823
- Schema.prototype.__isYupSchema__ = true;
1824
- for (const method of ["validate", "validateSync"]) Schema.prototype[`${method}At`] = function(path, value, options = {}) {
1825
- const { parent, parentPath, schema } = getIn(this, path, value, options.context);
1826
- return schema[method](parent && parent[parentPath], Object.assign({}, options, {
1827
- parent,
1828
- path
1829
- }));
1830
- };
1831
- for (const alias of ["equals", "is"]) Schema.prototype[alias] = Schema.prototype.oneOf;
1832
- for (const alias of ["not", "nope"]) Schema.prototype[alias] = Schema.prototype.notOneOf;
1833
- const returnsTrue = () => true;
1834
- function create$8(spec) {
1835
- return new MixedSchema(spec);
1836
- }
1837
- var MixedSchema = class extends Schema {
1838
- constructor(spec) {
1839
- super(typeof spec === "function" ? {
1840
- type: "mixed",
1841
- check: spec
1842
- } : Object.assign({
1843
- type: "mixed",
1844
- check: returnsTrue
1845
- }, spec));
1846
- }
1847
- };
1848
- create$8.prototype = MixedSchema.prototype;
1849
- function create$7() {
1850
- return new BooleanSchema();
1851
- }
1852
- var BooleanSchema = class extends Schema {
1853
- constructor() {
1854
- super({
1855
- type: "boolean",
1856
- check(v) {
1857
- if (v instanceof Boolean) v = v.valueOf();
1858
- return typeof v === "boolean";
1859
- }
1860
- });
1861
- this.withMutation(() => {
1862
- this.transform((value, _raw) => {
1863
- if (this.spec.coerce && !this.isType(value)) {
1864
- if (/^(true|1)$/i.test(String(value))) return true;
1865
- if (/^(false|0)$/i.test(String(value))) return false;
1866
- }
1867
- return value;
1868
- });
1869
- });
1870
- }
1871
- isTrue(message = boolean.isValue) {
1872
- return this.test({
1873
- message,
1874
- name: "is-value",
1875
- exclusive: true,
1876
- params: { value: "true" },
1877
- test(value) {
1878
- return isAbsent(value) || value === true;
1879
- }
1880
- });
1881
- }
1882
- isFalse(message = boolean.isValue) {
1883
- return this.test({
1884
- message,
1885
- name: "is-value",
1886
- exclusive: true,
1887
- params: { value: "false" },
1888
- test(value) {
1889
- return isAbsent(value) || value === false;
1890
- }
1891
- });
1892
- }
1893
- default(def) {
1894
- return super.default(def);
1895
- }
1896
- defined(msg) {
1897
- return super.defined(msg);
1898
- }
1899
- optional() {
1900
- return super.optional();
1901
- }
1902
- required(msg) {
1903
- return super.required(msg);
1904
- }
1905
- notRequired() {
1906
- return super.notRequired();
1907
- }
1908
- nullable() {
1909
- return super.nullable();
1910
- }
1911
- nonNullable(msg) {
1912
- return super.nonNullable(msg);
1913
- }
1914
- strip(v) {
1915
- return super.strip(v);
1916
- }
1917
- };
1918
- create$7.prototype = BooleanSchema.prototype;
1919
- /**
1920
- * This file is a modified version of the file from the following repository:
1921
- * Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
1922
- * NON-CONFORMANT EDITION.
1923
- * © 2011 Colin Snover <http://zetafleet.com>
1924
- * Released under MIT license.
1925
- */
1926
- const isoReg = /^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
1927
- function parseIsoDate(date) {
1928
- const struct = parseDateStruct(date);
1929
- if (!struct) return Date.parse ? Date.parse(date) : NaN;
1930
- if (struct.z === void 0 && struct.plusMinus === void 0) return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf();
1931
- let totalMinutesOffset = 0;
1932
- if (struct.z !== "Z" && struct.plusMinus !== void 0) {
1933
- totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset;
1934
- if (struct.plusMinus === "+") totalMinutesOffset = 0 - totalMinutesOffset;
1935
- }
1936
- return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond);
1937
762
  }
1938
- function parseDateStruct(date) {
1939
- var _regexResult$7$length, _regexResult$;
1940
- const regexResult = isoReg.exec(date);
1941
- if (!regexResult) return null;
1942
- return {
1943
- year: toNumber(regexResult[1]),
1944
- month: toNumber(regexResult[2], 1) - 1,
1945
- day: toNumber(regexResult[3], 1),
1946
- hour: toNumber(regexResult[4]),
1947
- minute: toNumber(regexResult[5]),
1948
- second: toNumber(regexResult[6]),
1949
- millisecond: regexResult[7] ? toNumber(regexResult[7].substring(0, 3)) : 0,
1950
- precision: (_regexResult$7$length = (_regexResult$ = regexResult[7]) == null ? void 0 : _regexResult$.length) != null ? _regexResult$7$length : void 0,
1951
- z: regexResult[8] || void 0,
1952
- plusMinus: regexResult[9] || void 0,
1953
- hourOffset: toNumber(regexResult[10]),
1954
- minuteOffset: toNumber(regexResult[11])
763
+ async function runStandard(schema, input) {
764
+ const result = await schema["~standard"].validate(input);
765
+ if (!result.issues) return {
766
+ ok: true,
767
+ issues: []
1955
768
  };
1956
- }
1957
- function toNumber(str, defaultValue = 0) {
1958
- return Number(str) || defaultValue;
1959
- }
1960
- let rEmail = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1961
- let rUrl = /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
1962
- let rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
1963
- let rIsoDateTime = new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1964
- let isTrimmed = (value) => isAbsent(value) || value === value.trim();
1965
- let objStringTag = {}.toString();
1966
- function create$6() {
1967
- return new StringSchema();
1968
- }
1969
- var StringSchema = class extends Schema {
1970
- constructor() {
1971
- super({
1972
- type: "string",
1973
- check(value) {
1974
- if (value instanceof String) value = value.valueOf();
1975
- return typeof value === "string";
1976
- }
1977
- });
1978
- this.withMutation(() => {
1979
- this.transform((value, _raw) => {
1980
- if (!this.spec.coerce || this.isType(value)) return value;
1981
- if (Array.isArray(value)) return value;
1982
- const strValue = value != null && value.toString ? value.toString() : value;
1983
- if (strValue === objStringTag) return value;
1984
- return strValue;
1985
- });
1986
- });
1987
- }
1988
- required(message) {
1989
- return super.required(message).withMutation((schema) => schema.test({
1990
- message: message || mixed.required,
1991
- name: "required",
1992
- skipAbsent: true,
1993
- test: (value) => !!value.length
1994
- }));
1995
- }
1996
- notRequired() {
1997
- return super.notRequired().withMutation((schema) => {
1998
- schema.tests = schema.tests.filter((t) => t.OPTIONS.name !== "required");
1999
- return schema;
2000
- });
2001
- }
2002
- length(length, message = string.length) {
2003
- return this.test({
2004
- message,
2005
- name: "length",
2006
- exclusive: true,
2007
- params: { length },
2008
- skipAbsent: true,
2009
- test(value) {
2010
- return value.length === this.resolve(length);
2011
- }
2012
- });
2013
- }
2014
- min(min, message = string.min) {
2015
- return this.test({
2016
- message,
2017
- name: "min",
2018
- exclusive: true,
2019
- params: { min },
2020
- skipAbsent: true,
2021
- test(value) {
2022
- return value.length >= this.resolve(min);
2023
- }
2024
- });
2025
- }
2026
- max(max, message = string.max) {
2027
- return this.test({
2028
- name: "max",
2029
- exclusive: true,
2030
- message,
2031
- params: { max },
2032
- skipAbsent: true,
2033
- test(value) {
2034
- return value.length <= this.resolve(max);
2035
- }
2036
- });
2037
- }
2038
- matches(regex, options) {
2039
- let excludeEmptyString = false;
2040
- let message;
2041
- let name;
2042
- if (options) {
2043
- if (typeof options === "object") ({excludeEmptyString = false, message, name} = options);
2044
- else message = options;
2045
- }
2046
- return this.test({
2047
- name: name || "matches",
2048
- message: message || string.matches,
2049
- params: { regex },
2050
- skipAbsent: true,
2051
- test: (value) => value === "" && excludeEmptyString || value.search(regex) !== -1
2052
- });
2053
- }
2054
- email(message = string.email) {
2055
- return this.matches(rEmail, {
2056
- name: "email",
2057
- message,
2058
- excludeEmptyString: true
2059
- });
2060
- }
2061
- url(message = string.url) {
2062
- return this.matches(rUrl, {
2063
- name: "url",
2064
- message,
2065
- excludeEmptyString: true
2066
- });
2067
- }
2068
- uuid(message = string.uuid) {
2069
- return this.matches(rUUID, {
2070
- name: "uuid",
2071
- message,
2072
- excludeEmptyString: false
2073
- });
2074
- }
2075
- datetime(options) {
2076
- let message = "";
2077
- let allowOffset;
2078
- let precision;
2079
- if (options) {
2080
- if (typeof options === "object") ({message = "", allowOffset = false, precision = void 0} = options);
2081
- else message = options;
2082
- }
2083
- return this.matches(rIsoDateTime, {
2084
- name: "datetime",
2085
- message: message || string.datetime,
2086
- excludeEmptyString: true
2087
- }).test({
2088
- name: "datetime_offset",
2089
- message: message || string.datetime_offset,
2090
- params: { allowOffset },
2091
- skipAbsent: true,
2092
- test: (value) => {
2093
- if (!value || allowOffset) return true;
2094
- const struct = parseDateStruct(value);
2095
- if (!struct) return false;
2096
- return !!struct.z;
2097
- }
2098
- }).test({
2099
- name: "datetime_precision",
2100
- message: message || string.datetime_precision,
2101
- params: { precision },
2102
- skipAbsent: true,
2103
- test: (value) => {
2104
- if (!value || precision == void 0) return true;
2105
- const struct = parseDateStruct(value);
2106
- if (!struct) return false;
2107
- return struct.precision === precision;
2108
- }
2109
- });
2110
- }
2111
- ensure() {
2112
- return this.default("").transform((val) => val === null ? "" : val);
2113
- }
2114
- trim(message = string.trim) {
2115
- return this.transform((val) => val != null ? val.trim() : val).test({
2116
- message,
2117
- name: "trim",
2118
- test: isTrimmed
2119
- });
2120
- }
2121
- lowercase(message = string.lowercase) {
2122
- return this.transform((value) => !isAbsent(value) ? value.toLowerCase() : value).test({
2123
- message,
2124
- name: "string_case",
2125
- exclusive: true,
2126
- skipAbsent: true,
2127
- test: (value) => isAbsent(value) || value === value.toLowerCase()
2128
- });
2129
- }
2130
- uppercase(message = string.uppercase) {
2131
- return this.transform((value) => !isAbsent(value) ? value.toUpperCase() : value).test({
2132
- message,
2133
- name: "string_case",
2134
- exclusive: true,
2135
- skipAbsent: true,
2136
- test: (value) => isAbsent(value) || value === value.toUpperCase()
2137
- });
2138
- }
2139
- };
2140
- create$6.prototype = StringSchema.prototype;
2141
- let isNaN$1 = (value) => value != +value;
2142
- function create$5() {
2143
- return new NumberSchema();
2144
- }
2145
- var NumberSchema = class extends Schema {
2146
- constructor() {
2147
- super({
2148
- type: "number",
2149
- check(value) {
2150
- if (value instanceof Number) value = value.valueOf();
2151
- return typeof value === "number" && !isNaN$1(value);
2152
- }
2153
- });
2154
- this.withMutation(() => {
2155
- this.transform((value, _raw) => {
2156
- if (!this.spec.coerce) return value;
2157
- let parsed = value;
2158
- if (typeof parsed === "string") {
2159
- parsed = parsed.replace(/\s/g, "");
2160
- if (parsed === "") return NaN;
2161
- parsed = +parsed;
2162
- }
2163
- if (this.isType(parsed) || parsed === null) return parsed;
2164
- return parseFloat(parsed);
2165
- });
2166
- });
2167
- }
2168
- min(min, message = number.min) {
2169
- return this.test({
2170
- message,
2171
- name: "min",
2172
- exclusive: true,
2173
- params: { min },
2174
- skipAbsent: true,
2175
- test(value) {
2176
- return value >= this.resolve(min);
2177
- }
2178
- });
2179
- }
2180
- max(max, message = number.max) {
2181
- return this.test({
2182
- message,
2183
- name: "max",
2184
- exclusive: true,
2185
- params: { max },
2186
- skipAbsent: true,
2187
- test(value) {
2188
- return value <= this.resolve(max);
2189
- }
2190
- });
2191
- }
2192
- lessThan(less, message = number.lessThan) {
2193
- return this.test({
2194
- message,
2195
- name: "max",
2196
- exclusive: true,
2197
- params: { less },
2198
- skipAbsent: true,
2199
- test(value) {
2200
- return value < this.resolve(less);
2201
- }
2202
- });
2203
- }
2204
- moreThan(more, message = number.moreThan) {
2205
- return this.test({
2206
- message,
2207
- name: "min",
2208
- exclusive: true,
2209
- params: { more },
2210
- skipAbsent: true,
2211
- test(value) {
2212
- return value > this.resolve(more);
2213
- }
2214
- });
2215
- }
2216
- positive(msg = number.positive) {
2217
- return this.moreThan(0, msg);
2218
- }
2219
- negative(msg = number.negative) {
2220
- return this.lessThan(0, msg);
2221
- }
2222
- integer(message = number.integer) {
2223
- return this.test({
2224
- name: "integer",
2225
- message,
2226
- skipAbsent: true,
2227
- test: (val) => Number.isInteger(val)
2228
- });
2229
- }
2230
- truncate() {
2231
- return this.transform((value) => !isAbsent(value) ? value | 0 : value);
2232
- }
2233
- round(method) {
2234
- var _method;
2235
- let avail = [
2236
- "ceil",
2237
- "floor",
2238
- "round",
2239
- "trunc"
2240
- ];
2241
- method = ((_method = method) == null ? void 0 : _method.toLowerCase()) || "round";
2242
- if (method === "trunc") return this.truncate();
2243
- if (avail.indexOf(method.toLowerCase()) === -1) throw new TypeError("Only valid options for round() are: " + avail.join(", "));
2244
- return this.transform((value) => !isAbsent(value) ? Math[method](value) : value);
2245
- }
2246
- };
2247
- create$5.prototype = NumberSchema.prototype;
2248
- let invalidDate = /* @__PURE__ */ new Date("");
2249
- let isDate = (obj) => Object.prototype.toString.call(obj) === "[object Date]";
2250
- function create$4() {
2251
- return new DateSchema();
2252
- }
2253
- var DateSchema = class DateSchema extends Schema {
2254
- constructor() {
2255
- super({
2256
- type: "date",
2257
- check(v) {
2258
- return isDate(v) && !isNaN(v.getTime());
2259
- }
2260
- });
2261
- this.withMutation(() => {
2262
- this.transform((value, _raw) => {
2263
- if (!this.spec.coerce || this.isType(value) || value === null) return value;
2264
- value = parseIsoDate(value);
2265
- return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE;
2266
- });
2267
- });
2268
- }
2269
- prepareParam(ref, name) {
2270
- let param;
2271
- if (!Reference.isRef(ref)) {
2272
- let cast = this.cast(ref);
2273
- if (!this._typeCheck(cast)) throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`);
2274
- param = cast;
2275
- } else param = ref;
2276
- return param;
2277
- }
2278
- min(min, message = date.min) {
2279
- let limit = this.prepareParam(min, "min");
2280
- return this.test({
2281
- message,
2282
- name: "min",
2283
- exclusive: true,
2284
- params: { min },
2285
- skipAbsent: true,
2286
- test(value) {
2287
- return value >= this.resolve(limit);
2288
- }
2289
- });
2290
- }
2291
- max(max, message = date.max) {
2292
- let limit = this.prepareParam(max, "max");
2293
- return this.test({
2294
- message,
2295
- name: "max",
2296
- exclusive: true,
2297
- params: { max },
2298
- skipAbsent: true,
2299
- test(value) {
2300
- return value <= this.resolve(limit);
2301
- }
2302
- });
2303
- }
2304
- };
2305
- DateSchema.INVALID_DATE = invalidDate;
2306
- create$4.prototype = DateSchema.prototype;
2307
- create$4.INVALID_DATE = invalidDate;
2308
- function sortFields(fields, excludedEdges = []) {
2309
- let edges = [];
2310
- let nodes = /* @__PURE__ */ new Set();
2311
- let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));
2312
- function addNode(depPath, key) {
2313
- let node = (0, import_property_expr.split)(depPath)[0];
2314
- nodes.add(node);
2315
- if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);
2316
- }
2317
- for (const key of Object.keys(fields)) {
2318
- let value = fields[key];
2319
- nodes.add(key);
2320
- if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);
2321
- else if (isSchema(value) && "deps" in value) value.deps.forEach((path) => addNode(path, key));
2322
- }
2323
- return import_toposort.default.array(Array.from(nodes), edges).reverse();
2324
- }
2325
- function findIndex(arr, err) {
2326
- let idx = Infinity;
2327
- arr.some((key, ii) => {
2328
- var _err$path;
2329
- if ((_err$path = err.path) != null && _err$path.includes(key)) {
2330
- idx = ii;
2331
- return true;
2332
- }
2333
- });
2334
- return idx;
2335
- }
2336
- function sortByKeyOrder(keys) {
2337
- return (a, b) => {
2338
- return findIndex(keys, a) - findIndex(keys, b);
769
+ return {
770
+ ok: false,
771
+ issues: result.issues.map((issue) => ({
772
+ keys: (issue.path ?? []).map((seg) => seg !== null && typeof seg === "object" ? seg.key : seg),
773
+ message: String(issue.message ?? "")
774
+ }))
2339
775
  };
2340
776
  }
2341
- const parseJson = (value, _, schema) => {
2342
- if (typeof value !== "string") return value;
2343
- let parsed = value;
2344
- try {
2345
- parsed = JSON.parse(value);
2346
- } catch (err) {}
2347
- return schema.isType(parsed) ? parsed : value;
2348
- };
2349
- function deepPartial(schema) {
2350
- if ("fields" in schema) {
2351
- const partial = {};
2352
- for (const [key, fieldSchema] of Object.entries(schema.fields)) partial[key] = deepPartial(fieldSchema);
2353
- return schema.setFields(partial);
2354
- }
2355
- if (schema.type === "array") {
2356
- const nextArray = schema.optional();
2357
- if (nextArray.innerType) nextArray.innerType = deepPartial(nextArray.innerType);
2358
- return nextArray;
2359
- }
2360
- if (schema.type === "tuple") return schema.optional().clone({ types: schema.spec.types.map(deepPartial) });
2361
- if ("optional" in schema) return schema.optional();
2362
- return schema;
2363
- }
2364
- const deepHas = (obj, p) => {
2365
- const path = [...(0, import_property_expr.normalizePath)(p)];
2366
- if (path.length === 1) return path[0] in obj;
2367
- let last = path.pop();
2368
- let parent = (0, import_property_expr.getter)((0, import_property_expr.join)(path), true)(obj);
2369
- return !!(parent && last in parent);
2370
- };
2371
- let isObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]";
2372
- function unknown(ctx, value) {
2373
- let known = Object.keys(ctx.fields);
2374
- return Object.keys(value).filter((key) => known.indexOf(key) === -1);
2375
- }
2376
- const defaultSort = sortByKeyOrder([]);
2377
- function create$3(spec) {
2378
- return new ObjectSchema(spec);
2379
- }
2380
- var ObjectSchema = class extends Schema {
2381
- constructor(spec) {
2382
- super({
2383
- type: "object",
2384
- check(value) {
2385
- return isObject(value) || typeof value === "function";
2386
- }
2387
- });
2388
- this.fields = Object.create(null);
2389
- this._sortErrors = defaultSort;
2390
- this._nodes = [];
2391
- this._excludedEdges = [];
2392
- this.withMutation(() => {
2393
- if (spec) this.shape(spec);
2394
- });
2395
- }
2396
- _cast(_value, options = {}) {
2397
- var _options$stripUnknown;
2398
- let value = super._cast(_value, options);
2399
- if (value === void 0) return this.getDefault(options);
2400
- if (!this._typeCheck(value)) return value;
2401
- let fields = this.fields;
2402
- let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;
2403
- let props = [].concat(this._nodes, Object.keys(value).filter((v) => !this._nodes.includes(v)));
2404
- let intermediateValue = {};
2405
- let innerOptions = Object.assign({}, options, {
2406
- parent: intermediateValue,
2407
- __validating: options.__validating || false
2408
- });
2409
- let isChanged = false;
2410
- for (const prop of props) {
2411
- let field = fields[prop];
2412
- let exists = prop in value;
2413
- let inputValue = value[prop];
2414
- if (field) {
2415
- let fieldValue;
2416
- innerOptions.path = (options.path ? `${options.path}.` : "") + prop;
2417
- field = field.resolve({
2418
- value: inputValue,
2419
- context: options.context,
2420
- parent: intermediateValue
2421
- });
2422
- let fieldSpec = field instanceof Schema ? field.spec : void 0;
2423
- let strict = fieldSpec == null ? void 0 : fieldSpec.strict;
2424
- if (fieldSpec != null && fieldSpec.strip) {
2425
- isChanged = isChanged || prop in value;
2426
- continue;
2427
- }
2428
- fieldValue = !options.__validating || !strict ? field.cast(inputValue, innerOptions) : inputValue;
2429
- if (fieldValue !== void 0) intermediateValue[prop] = fieldValue;
2430
- } else if (exists && !strip) intermediateValue[prop] = inputValue;
2431
- if (exists !== prop in intermediateValue || intermediateValue[prop] !== inputValue) isChanged = true;
2432
- }
2433
- return isChanged ? intermediateValue : value;
2434
- }
2435
- _validate(_value, options = {}, panic, next) {
2436
- let { from = [], originalValue = _value, recursive = this.spec.recursive } = options;
2437
- options.from = [{
2438
- schema: this,
2439
- value: originalValue
2440
- }, ...from];
2441
- options.__validating = true;
2442
- options.originalValue = originalValue;
2443
- super._validate(_value, options, panic, (objectErrors, value) => {
2444
- if (!recursive || !isObject(value)) {
2445
- next(objectErrors, value);
2446
- return;
2447
- }
2448
- originalValue = originalValue || value;
2449
- let tests = [];
2450
- for (let key of this._nodes) {
2451
- let field = this.fields[key];
2452
- if (!field || Reference.isRef(field)) continue;
2453
- tests.push(field.asNestedTest({
2454
- options,
2455
- key,
2456
- parent: value,
2457
- parentPath: options.path,
2458
- originalParent: originalValue
2459
- }));
2460
- }
2461
- this.runTests({
2462
- tests,
2463
- value,
2464
- originalValue,
2465
- options
2466
- }, panic, (fieldErrors) => {
2467
- next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);
2468
- });
2469
- });
2470
- }
2471
- clone(spec) {
2472
- const next = super.clone(spec);
2473
- next.fields = Object.assign({}, this.fields);
2474
- next._nodes = this._nodes;
2475
- next._excludedEdges = this._excludedEdges;
2476
- next._sortErrors = this._sortErrors;
2477
- return next;
2478
- }
2479
- concat(schema) {
2480
- let next = super.concat(schema);
2481
- let nextFields = next.fields;
2482
- for (let [field, schemaOrRef] of Object.entries(this.fields)) {
2483
- const target = nextFields[field];
2484
- nextFields[field] = target === void 0 ? schemaOrRef : target;
2485
- }
2486
- return next.withMutation((s) => s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges]));
2487
- }
2488
- _getDefault(options) {
2489
- if ("default" in this.spec) return super._getDefault(options);
2490
- if (!this._nodes.length) return;
2491
- let dft = {};
2492
- this._nodes.forEach((key) => {
2493
- var _innerOptions;
2494
- const field = this.fields[key];
2495
- let innerOptions = options;
2496
- if ((_innerOptions = innerOptions) != null && _innerOptions.value) innerOptions = Object.assign({}, innerOptions, {
2497
- parent: innerOptions.value,
2498
- value: innerOptions.value[key]
2499
- });
2500
- dft[key] = field && "getDefault" in field ? field.getDefault(innerOptions) : void 0;
2501
- });
2502
- return dft;
2503
- }
2504
- setFields(shape, excludedEdges) {
2505
- let next = this.clone();
2506
- next.fields = shape;
2507
- next._nodes = sortFields(shape, excludedEdges);
2508
- next._sortErrors = sortByKeyOrder(Object.keys(shape));
2509
- if (excludedEdges) next._excludedEdges = excludedEdges;
2510
- return next;
2511
- }
2512
- shape(additions, excludes = []) {
2513
- return this.clone().withMutation((next) => {
2514
- let edges = next._excludedEdges;
2515
- if (excludes.length) {
2516
- if (!Array.isArray(excludes[0])) excludes = [excludes];
2517
- edges = [...next._excludedEdges, ...excludes];
2518
- }
2519
- return next.setFields(Object.assign(next.fields, additions), edges);
2520
- });
2521
- }
2522
- partial() {
2523
- const partial = {};
2524
- for (const [key, schema] of Object.entries(this.fields)) partial[key] = "optional" in schema && schema.optional instanceof Function ? schema.optional() : schema;
2525
- return this.setFields(partial);
2526
- }
2527
- deepPartial() {
2528
- return deepPartial(this);
2529
- }
2530
- pick(keys) {
2531
- const picked = {};
2532
- for (const key of keys) if (this.fields[key]) picked[key] = this.fields[key];
2533
- return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b)));
2534
- }
2535
- omit(keys) {
2536
- const remaining = [];
2537
- for (const key of Object.keys(this.fields)) {
2538
- if (keys.includes(key)) continue;
2539
- remaining.push(key);
2540
- }
2541
- return this.pick(remaining);
2542
- }
2543
- from(from, to, alias) {
2544
- let fromGetter = (0, import_property_expr.getter)(from, true);
2545
- return this.transform((obj) => {
2546
- if (!obj) return obj;
2547
- let newObj = obj;
2548
- if (deepHas(obj, from)) {
2549
- newObj = Object.assign({}, obj);
2550
- if (!alias) delete newObj[from];
2551
- newObj[to] = fromGetter(obj);
2552
- }
2553
- return newObj;
2554
- });
2555
- }
2556
- /** Parse an input JSON string to an object */
2557
- json() {
2558
- return this.transform(parseJson);
2559
- }
2560
- /**
2561
- * Similar to `noUnknown` but only validates that an object is the right shape without stripping the unknown keys
2562
- */
2563
- exact(message) {
2564
- return this.test({
2565
- name: "exact",
2566
- exclusive: true,
2567
- message: message || object.exact,
2568
- test(value) {
2569
- if (value == null) return true;
2570
- const unknownKeys = unknown(this.schema, value);
2571
- return unknownKeys.length === 0 || this.createError({ params: { properties: unknownKeys.join(", ") } });
2572
- }
2573
- });
2574
- }
2575
- stripUnknown() {
2576
- return this.clone({ noUnknown: true });
2577
- }
2578
- noUnknown(noAllow = true, message = object.noUnknown) {
2579
- if (typeof noAllow !== "boolean") {
2580
- message = noAllow;
2581
- noAllow = true;
2582
- }
2583
- let next = this.test({
2584
- name: "noUnknown",
2585
- exclusive: true,
2586
- message,
2587
- test(value) {
2588
- if (value == null) return true;
2589
- const unknownKeys = unknown(this.schema, value);
2590
- return !noAllow || unknownKeys.length === 0 || this.createError({ params: { unknown: unknownKeys.join(", ") } });
2591
- }
2592
- });
2593
- next.spec.noUnknown = noAllow;
2594
- return next;
2595
- }
2596
- unknown(allow = true, message = object.noUnknown) {
2597
- return this.noUnknown(!allow, message);
2598
- }
2599
- transformKeys(fn) {
2600
- return this.transform((obj) => {
2601
- if (!obj) return obj;
2602
- const result = {};
2603
- for (const key of Object.keys(obj)) result[fn(key)] = obj[key];
2604
- return result;
2605
- });
2606
- }
2607
- camelCase() {
2608
- return this.transformKeys(import_tiny_case.camelCase);
2609
- }
2610
- snakeCase() {
2611
- return this.transformKeys(import_tiny_case.snakeCase);
2612
- }
2613
- constantCase() {
2614
- return this.transformKeys((key) => (0, import_tiny_case.snakeCase)(key).toUpperCase());
2615
- }
2616
- describe(options) {
2617
- const next = (options ? this.resolve(options) : this).clone();
2618
- const base = super.describe(options);
2619
- base.fields = {};
2620
- for (const [key, value] of Object.entries(next.fields)) {
2621
- var _innerOptions2;
2622
- let innerOptions = options;
2623
- if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) innerOptions = Object.assign({}, innerOptions, {
2624
- parent: innerOptions.value,
2625
- value: innerOptions.value[key]
2626
- });
2627
- base.fields[key] = value.describe(innerOptions);
2628
- }
2629
- return base;
2630
- }
2631
- };
2632
- create$3.prototype = ObjectSchema.prototype;
2633
- function create$2(type) {
2634
- return new ArraySchema(type);
777
+ /** Validate with whichever library `schema` belongs to. `null` = unknown schema. */
778
+ async function runSchema(schema, input, field) {
779
+ if (isYupSchema(schema)) return runYup(schema, input, field);
780
+ if (isStandardSchema(schema)) return runStandard(schema, input);
781
+ warnUnknown(schema);
782
+ return null;
2635
783
  }
2636
- var ArraySchema = class extends Schema {
2637
- constructor(type) {
2638
- super({
2639
- type: "array",
2640
- spec: { types: type },
2641
- check(v) {
2642
- return Array.isArray(v);
2643
- }
2644
- });
2645
- this.innerType = void 0;
2646
- this.innerType = type;
2647
- }
2648
- _cast(_value, _opts) {
2649
- const value = super._cast(_value, _opts);
2650
- if (!this._typeCheck(value) || !this.innerType) return value;
2651
- let isChanged = false;
2652
- const castArray = value.map((v, idx) => {
2653
- const castElement = this.innerType.cast(v, Object.assign({}, _opts, {
2654
- path: `${_opts.path || ""}[${idx}]`,
2655
- parent: value,
2656
- originalValue: v,
2657
- value: v,
2658
- index: idx
2659
- }));
2660
- if (castElement !== v) isChanged = true;
2661
- return castElement;
2662
- });
2663
- return isChanged ? castArray : value;
2664
- }
2665
- _validate(_value, options = {}, panic, next) {
2666
- var _options$recursive;
2667
- let innerType = this.innerType;
2668
- let recursive = (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive;
2669
- options.originalValue != null && options.originalValue;
2670
- super._validate(_value, options, panic, (arrayErrors, value) => {
2671
- var _options$originalValu2;
2672
- if (!recursive || !innerType || !this._typeCheck(value)) {
2673
- next(arrayErrors, value);
2674
- return;
2675
- }
2676
- let tests = new Array(value.length);
2677
- for (let index = 0; index < value.length; index++) {
2678
- var _options$originalValu;
2679
- tests[index] = innerType.asNestedTest({
2680
- options,
2681
- index,
2682
- parent: value,
2683
- parentPath: options.path,
2684
- originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value
2685
- });
2686
- }
2687
- this.runTests({
2688
- value,
2689
- tests,
2690
- originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value,
2691
- options
2692
- }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(arrayErrors), value));
2693
- });
2694
- }
2695
- clone(spec) {
2696
- const next = super.clone(spec);
2697
- next.innerType = this.innerType;
2698
- return next;
2699
- }
2700
- /** Parse an input JSON string to an object */
2701
- json() {
2702
- return this.transform(parseJson);
2703
- }
2704
- concat(schema) {
2705
- let next = super.concat(schema);
2706
- next.innerType = this.innerType;
2707
- if (schema.innerType) next.innerType = next.innerType ? next.innerType.concat(schema.innerType) : schema.innerType;
2708
- return next;
2709
- }
2710
- of(schema) {
2711
- let next = this.clone();
2712
- if (!isSchema(schema)) throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: " + printValue(schema));
2713
- next.innerType = schema;
2714
- next.spec = Object.assign({}, next.spec, { types: schema });
2715
- return next;
2716
- }
2717
- length(length, message = array.length) {
2718
- return this.test({
2719
- message,
2720
- name: "length",
2721
- exclusive: true,
2722
- params: { length },
2723
- skipAbsent: true,
2724
- test(value) {
2725
- return value.length === this.resolve(length);
2726
- }
2727
- });
2728
- }
2729
- min(min, message) {
2730
- message = message || array.min;
2731
- return this.test({
2732
- message,
2733
- name: "min",
2734
- exclusive: true,
2735
- params: { min },
2736
- skipAbsent: true,
2737
- test(value) {
2738
- return value.length >= this.resolve(min);
2739
- }
2740
- });
2741
- }
2742
- max(max, message) {
2743
- message = message || array.max;
2744
- return this.test({
2745
- message,
2746
- name: "max",
2747
- exclusive: true,
2748
- params: { max },
2749
- skipAbsent: true,
2750
- test(value) {
2751
- return value.length <= this.resolve(max);
2752
- }
2753
- });
2754
- }
2755
- ensure() {
2756
- return this.default(() => []).transform((val, original) => {
2757
- if (this._typeCheck(val)) return val;
2758
- return original == null ? [] : [].concat(original);
2759
- });
2760
- }
2761
- compact(rejector) {
2762
- let reject = !rejector ? (v) => !!v : (v, i, a) => !rejector(v, i, a);
2763
- return this.transform((values) => values != null ? values.filter(reject) : values);
2764
- }
2765
- describe(options) {
2766
- const next = (options ? this.resolve(options) : this).clone();
2767
- const base = super.describe(options);
2768
- if (next.innerType) {
2769
- var _innerOptions;
2770
- let innerOptions = options;
2771
- if ((_innerOptions = innerOptions) != null && _innerOptions.value) innerOptions = Object.assign({}, innerOptions, {
2772
- parent: innerOptions.value,
2773
- value: innerOptions.value[0]
2774
- });
2775
- base.innerType = next.innerType.describe(innerOptions);
2776
- }
2777
- return base;
2778
- }
2779
- };
2780
- create$2.prototype = ArraySchema.prototype;
2781
- function create$1(schemas) {
2782
- return new TupleSchema(schemas);
784
+ /** Whole form. Resolves `true` when every slot is valid. */
785
+ async function validateAll(schema, input, errorIn) {
786
+ const error = unwrapError(errorIn);
787
+ const result = await runSchema(schema, input);
788
+ if (!result) return false;
789
+ resetSlots(error);
790
+ applyIssues(error, result.issues.filter((i) => presentInInput(input, i.keys)));
791
+ return everyValid(error);
792
+ }
793
+ /** One field (dotted path allowed). Resolves `true` when that field is valid. */
794
+ async function validateField(schema, field, input, errorIn) {
795
+ const error = unwrapError(errorIn);
796
+ const keys = typeof field === "number" ? [field] : parsePath(field);
797
+ const result = await runSchema(schema, input, keys);
798
+ if (!result) return false;
799
+ const node = getNode(error, keys);
800
+ resetSlots(node);
801
+ applyIssues(error, result.issues.filter((i) => startsWith(i.keys, keys)));
802
+ return everyValid(node);
803
+ }
804
+ /** Reset every slot. Takes a Ref or the object itself. */
805
+ function clearAll(errorIn) {
806
+ resetSlots(unwrapError(errorIn));
2783
807
  }
2784
- var TupleSchema = class extends Schema {
2785
- constructor(schemas) {
2786
- super({
2787
- type: "tuple",
2788
- spec: { types: schemas },
2789
- check(v) {
2790
- const types = this.spec.types;
2791
- return Array.isArray(v) && v.length === types.length;
2792
- }
2793
- });
2794
- this.withMutation(() => {
2795
- this.typeError(tuple.notType);
2796
- });
2797
- }
2798
- _cast(inputValue, options) {
2799
- const { types } = this.spec;
2800
- const value = super._cast(inputValue, options);
2801
- if (!this._typeCheck(value)) return value;
2802
- let isChanged = false;
2803
- const castArray = types.map((type, idx) => {
2804
- const castElement = type.cast(value[idx], Object.assign({}, options, {
2805
- path: `${options.path || ""}[${idx}]`,
2806
- parent: value,
2807
- originalValue: value[idx],
2808
- value: value[idx],
2809
- index: idx
2810
- }));
2811
- if (castElement !== value[idx]) isChanged = true;
2812
- return castElement;
2813
- });
2814
- return isChanged ? castArray : value;
2815
- }
2816
- _validate(_value, options = {}, panic, next) {
2817
- let itemTypes = this.spec.types;
2818
- super._validate(_value, options, panic, (tupleErrors, value) => {
2819
- var _options$originalValu2;
2820
- if (!this._typeCheck(value)) {
2821
- next(tupleErrors, value);
2822
- return;
2823
- }
2824
- let tests = [];
2825
- for (let [index, itemSchema] of itemTypes.entries()) {
2826
- var _options$originalValu;
2827
- tests[index] = itemSchema.asNestedTest({
2828
- options,
2829
- index,
2830
- parent: value,
2831
- parentPath: options.path,
2832
- originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value
2833
- });
2834
- }
2835
- this.runTests({
2836
- value,
2837
- tests,
2838
- originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value,
2839
- options
2840
- }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(tupleErrors), value));
2841
- });
2842
- }
2843
- describe(options) {
2844
- const next = (options ? this.resolve(options) : this).clone();
2845
- const base = super.describe(options);
2846
- base.innerType = next.spec.types.map((schema, index) => {
2847
- var _innerOptions;
2848
- let innerOptions = options;
2849
- if ((_innerOptions = innerOptions) != null && _innerOptions.value) innerOptions = Object.assign({}, innerOptions, {
2850
- parent: innerOptions.value,
2851
- value: innerOptions.value[index]
2852
- });
2853
- return schema.describe(innerOptions);
2854
- });
2855
- return base;
2856
- }
2857
- };
2858
- create$1.prototype = TupleSchema.prototype;
2859
808
 
2860
809
  //#endregion
2861
810
  //#region src/core/composables/use-helper.ts
@@ -2907,91 +856,46 @@ const useHelper = () => {
2907
856
  }
2908
857
  };
2909
858
  /**
2910
- * fungsi mengecek semua inputan validasi, jika satu inputan masih salah maka akan mereturn true
2911
- * @param error adalah list data error
859
+ * `true` when ANY `{ valid, message }` slot in the error object (nested
860
+ * objects/arrays included) is invalid.
861
+ * @param error the error object (or a Ref of it)
2912
862
  */
2913
- let validateAllSchemaCheck = (error) => !Object.values(error).every((e) => e.valid);
863
+ let validateAllSchemaCheck = (error) => !everyValid(unwrapError(error));
2914
864
  /**
2915
-
2916
- * ShortHand Validasi batch schema yup
2917
- * @param schema adalah list data schema yang ingin divalidasi
2918
- * @param input adalah list data input yang ingin divalidasi, harus dicocokkan
2919
- * @param error adalah list data error yang akan ditampilkan
865
+ * Validate the whole form against a yup schema or any Standard Schema
866
+ * (Valibot, Zod, …). Keys absent from `input` are skipped. Every slot is
867
+ * reset first, so a field that now passes is cleared.
868
+ * @param schema yup object schema or Standard Schema
869
+ * @param input the form values
870
+ * @param error `{ valid, message }` slots mirroring `input` (object or Ref)
871
+ * @param callback awaited only when everything is valid
872
+ * @returns `true` when the form is valid
2920
873
  */
2921
- /** ───────────────── helpers ───────────────── */
2922
874
  async function validateAllSchema({ schema, input, error }, callback) {
2923
- function buildPartialSchema(inputObj, schemaObj) {
2924
- if (!("fields" in schemaObj)) return schemaObj;
2925
- const picked = {};
2926
- const shape = schemaObj.fields;
2927
- for (const key of Object.keys(shape)) if (key in (inputObj ?? {})) {
2928
- const fieldSchema = shape[key];
2929
- const value = inputObj?.[key];
2930
- picked[key] = fieldSchema.type === "object" && value !== null && typeof value === "object" && !Array.isArray(value) ? buildPartialSchema(value, fieldSchema) : fieldSchema;
2931
- }
2932
- return create$3().shape(picked);
2933
- }
2934
- const partialSchema = buildPartialSchema(input, schema);
2935
- function setNestedError(obj, path, message) {
2936
- const keys = path.split(".");
2937
- const lastKey = keys.pop();
2938
- let cursor = obj;
2939
- for (const k of keys) {
2940
- cursor[k] = cursor[k] ?? {};
2941
- cursor = cursor[k];
2942
- }
2943
- if (cursor[lastKey]) {
2944
- cursor[lastKey].message = message;
2945
- cursor[lastKey].valid = false;
2946
- }
2947
- }
2948
- try {
2949
- await partialSchema.validate(input, { abortEarly: false });
2950
- callback?.();
2951
- return true;
2952
- } catch (e) {
2953
- if ("inner" in e) e.inner.forEach((err) => setNestedError(error, err.path, err.message));
2954
- const everyValid = (obj) => Object.values(obj).every((v) => typeof v === "object" && "valid" in v ? v.valid : everyValid(v));
2955
- return everyValid(error);
2956
- }
875
+ const valid = await validateAll(schema, input, error);
876
+ if (valid) await callback?.();
877
+ return valid;
2957
878
  }
2958
879
  /**
2959
- * ShortHand single Validasi schema yup
2960
- * @param schema adalah list data schema yang ingin divalidasi
2961
- * @param field adalah field data yang ingin divalidasi
2962
- * @param input adalah data input yang ingin divalidasi, harus dicocokkan
2963
- * @param error adalah data error yang akan ditampilkan
2964
- * @param callback
880
+ * Validate ONE field (dotted / indexed paths allowed: `'address.city'`,
881
+ * `'items[0].name'`) against a yup schema or any Standard Schema.
882
+ * Without `field` it validates the whole form.
883
+ * @param callback awaited only when the field is valid
884
+ * @returns `true` when the field is valid
2965
885
  */
2966
886
  let validateSchema = async ({ schema, field, input, error }, callback) => {
2967
- if (schema?.fields[field]) await schema.validateAt(field, input).then(() => {
2968
- error[field].message = "";
2969
- error[field].valid = true;
2970
- if (callback) return callback();
2971
- }).catch((err) => {
2972
- if (field && !Array.isArray(input[field])) {
2973
- if (!input[field]) {
2974
- error[err.path].message = err.message;
2975
- error[err.path].valid = false;
2976
- }
2977
- } else {
2978
- error[err.path].message = err.message;
2979
- error[err.path].valid = false;
2980
- }
2981
- });
2982
- return !error[field].valid;
887
+ if (field === void 0 || field === null) return validateAllSchema({
888
+ schema,
889
+ input,
890
+ error
891
+ }, callback);
892
+ const valid = await validateField(schema, field, input, error);
893
+ if (valid) await callback?.();
894
+ return valid;
2983
895
  };
896
+ /** Reset every `{ valid, message }` slot. Accepts a Ref or the object itself. */
2984
897
  function clearSchemaValidation({ error }) {
2985
- const clear = (obj) => {
2986
- for (const key in obj.value) {
2987
- const val = obj.value[key];
2988
- if (typeof val === "object" && val !== null && "valid" in val && "message" in val) {
2989
- val.valid = true;
2990
- val.message = "";
2991
- } else if (typeof val === "object" && val !== null) clear(val);
2992
- }
2993
- };
2994
- clear(error);
898
+ clearAll(error);
2995
899
  }
2996
900
  function replacerData({ fn, type, item, key, items }) {
2997
901
  if (type === "data") {