@rjsf/utils 5.0.0-beta.17 → 5.0.0-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils.esm.js CHANGED
@@ -3,13 +3,17 @@ import get from 'lodash-es/get';
3
3
  import isEmpty from 'lodash-es/isEmpty';
4
4
  import jsonpointer from 'jsonpointer';
5
5
  import omit from 'lodash-es/omit';
6
+ import has from 'lodash-es/has';
7
+ import isObject$1 from 'lodash-es/isObject';
8
+ import isString from 'lodash-es/isString';
9
+ import reduce from 'lodash-es/reduce';
10
+ import times from 'lodash-es/times';
6
11
  import set from 'lodash-es/set';
7
12
  import mergeAllOf from 'json-schema-merge-allof';
8
13
  import union from 'lodash-es/union';
9
14
  import cloneDeep from 'lodash-es/cloneDeep';
10
15
  import React from 'react';
11
16
  import ReactIs from 'react-is';
12
- import isString from 'lodash-es/isString';
13
17
 
14
18
  /** Determines whether a `thing` is an object for the purposes of RSJF. In this case, `thing` is an object if it has
15
19
  * the type `object` but is NOT null, an array or a File.
@@ -290,12 +294,14 @@ function findSchemaDefinition($ref, rootSchema) {
290
294
  }
291
295
 
292
296
  /** Given the `formData` and list of `options`, attempts to find the index of the option that best matches the data.
297
+ * Deprecated, use `getFirstMatchingOption()` instead.
293
298
  *
294
299
  * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
295
300
  * @param formData - The current formData, if any, used to figure out a match
296
301
  * @param options - The list of options to find a matching options from
297
302
  * @param rootSchema - The root schema, used to primarily to look up `$ref`s
298
303
  * @returns - The index of the matched option or 0 if none is available
304
+ * @deprecated
299
305
  */
300
306
  function getMatchingOption(validator, formData, options, rootSchema) {
301
307
  // For performance, skip validating subschemas if formData is undefined. We just
@@ -351,6 +357,19 @@ function getMatchingOption(validator, formData, options, rootSchema) {
351
357
  return 0;
352
358
  }
353
359
 
360
+ /** Given the `formData` and list of `options`, attempts to find the index of the first option that matches the data.
361
+ * Always returns the first option if there is nothing that matches.
362
+ *
363
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
364
+ * @param formData - The current formData, if any, used to figure out a match
365
+ * @param options - The list of options to find a matching options from
366
+ * @param rootSchema - The root schema, used to primarily to look up `$ref`s
367
+ * @returns - The index of the first matched option or 0 if none is available
368
+ */
369
+ function getFirstMatchingOption(validator, formData, options, rootSchema) {
370
+ return getMatchingOption(validator, formData, options, rootSchema);
371
+ }
372
+
354
373
  /** Given a specific `value` attempts to guess the type of a schema element. In the case where we have to implicitly
355
374
  * create a schema, it is useful to know what type to use based on the data we are defining.
356
375
  *
@@ -402,6 +421,12 @@ function getSchemaType(schema) {
402
421
  if (!type && (schema.properties || schema.additionalProperties)) {
403
422
  return "object";
404
423
  }
424
+ if (!type && Array.isArray(schema.oneOf) && schema.oneOf.length) {
425
+ return getSchemaType(schema.oneOf[0]);
426
+ }
427
+ if (!type && Array.isArray(schema.anyOf) && schema.anyOf.length) {
428
+ return getSchemaType(schema.anyOf[0]);
429
+ }
405
430
  if (Array.isArray(type) && type.length === 2 && type.includes("null")) {
406
431
  type = type.find(function (type) {
407
432
  return type !== "null";
@@ -410,99 +435,6 @@ function getSchemaType(schema) {
410
435
  return type;
411
436
  }
412
437
 
413
- /** Detects whether the given `schema` contains fixed items. This is the case when `schema.items` is a non-empty array
414
- * that only contains objects.
415
- *
416
- * @param schema - The schema in which to check for fixed items
417
- * @returns - True if there are fixed items in the schema, false otherwise
418
- */
419
- function isFixedItems(schema) {
420
- return Array.isArray(schema.items) && schema.items.length > 0 && schema.items.every(function (item) {
421
- return isObject(item);
422
- });
423
- }
424
-
425
- /** Merges the `defaults` object of type `T` into the `formData` of type `T`
426
- *
427
- * When merging defaults and form data, we want to merge in this specific way:
428
- * - objects are deeply merged
429
- * - arrays are merged in such a way that:
430
- * - when the array is set in form data, only array entries set in form data
431
- * are deeply merged; additional entries from the defaults are ignored
432
- * - when the array is not set in form data, the default is copied over
433
- * - scalars are overwritten/set by form data
434
- *
435
- * @param defaults - The defaults to merge
436
- * @param formData - The form data into which the defaults will be merged
437
- * @returns - The resulting merged form data with defaults
438
- */
439
- function mergeDefaultsWithFormData(defaults, formData) {
440
- if (Array.isArray(formData)) {
441
- var defaultsArray = Array.isArray(defaults) ? defaults : [];
442
- var mapped = formData.map(function (value, idx) {
443
- if (defaultsArray[idx]) {
444
- return mergeDefaultsWithFormData(defaultsArray[idx], value);
445
- }
446
- return value;
447
- });
448
- return mapped;
449
- }
450
- if (isObject(formData)) {
451
- var acc = Object.assign({}, defaults); // Prevent mutation of source object.
452
- return Object.keys(formData).reduce(function (acc, key) {
453
- acc[key] = mergeDefaultsWithFormData(defaults ? get(defaults, key) : {}, get(formData, key));
454
- return acc;
455
- }, acc);
456
- }
457
- return formData;
458
- }
459
-
460
- /** Recursively merge deeply nested objects.
461
- *
462
- * @param obj1 - The first object to merge
463
- * @param obj2 - The second object to merge
464
- * @param [concatArrays=false] - Optional flag that, when true, will cause arrays to be concatenated. Use
465
- * "preventDuplicates" to merge arrays in a manner that prevents any duplicate entries from being merged.
466
- * NOTE: Uses shallow comparison for the duplicate checking.
467
- * @returns - A new object that is the merge of the two given objects
468
- */
469
- function mergeObjects(obj1, obj2, concatArrays) {
470
- if (concatArrays === void 0) {
471
- concatArrays = false;
472
- }
473
- return Object.keys(obj2).reduce(function (acc, key) {
474
- var left = obj1 ? obj1[key] : {},
475
- right = obj2[key];
476
- if (obj1 && key in obj1 && isObject(right)) {
477
- acc[key] = mergeObjects(left, right, concatArrays);
478
- } else if (concatArrays && Array.isArray(left) && Array.isArray(right)) {
479
- var toMerge = right;
480
- if (concatArrays === "preventDuplicates") {
481
- toMerge = right.reduce(function (result, value) {
482
- if (!left.includes(value)) {
483
- result.push(value);
484
- }
485
- return result;
486
- }, []);
487
- }
488
- acc[key] = left.concat(toMerge);
489
- } else {
490
- acc[key] = right;
491
- }
492
- return acc;
493
- }, Object.assign({}, obj1)); // Prevent mutation of source object.
494
- }
495
-
496
- /** This function checks if the given `schema` matches a single constant value. This happens when either the schema has
497
- * an `enum` array with a single value or there is a `const` defined.
498
- *
499
- * @param schema - The schema for a field
500
- * @returns - True if the `schema` has a single constant value, false otherwise
501
- */
502
- function isConstant(schema) {
503
- return Array.isArray(schema["enum"]) && schema["enum"].length === 1 || CONST_KEY in schema;
504
- }
505
-
506
438
  /** Recursively merge deeply nested schemas. The difference between `mergeSchemas` and `mergeObjects` is that
507
439
  * `mergeSchemas` only concats arrays for values under the 'required' keyword, and when it does, it doesn't include
508
440
  * duplicate values.
@@ -539,7 +471,7 @@ var _excluded$1 = ["if", "then", "else"],
539
471
  * @param validator - An implementation of the `ValidatorType<T, S>` interface that is used to detect valid schema conditions
540
472
  * @param schema - The schema for which resolving a condition is desired
541
473
  * @param rootSchema - The root schema that will be forwarded to all the APIs
542
- * @param formData - The current formData to assist retrieving a schema
474
+ * @param [formData] - The current formData to assist retrieving a schema
543
475
  * @returns - A schema with the appropriate condition resolved
544
476
  */
545
477
  function resolveCondition(validator, schema, rootSchema, formData) {
@@ -627,6 +559,10 @@ function stubExistingAdditionalProperties(validator, theSchema, rootSchema, aFor
627
559
  }, rootSchema, formData);
628
560
  } else if ("type" in schema.additionalProperties) {
629
561
  additionalProperties = _extends({}, schema.additionalProperties);
562
+ } else if (ANY_OF_KEY in schema.additionalProperties || ONE_OF_KEY in schema.additionalProperties) {
563
+ additionalProperties = _extends({
564
+ type: "object"
565
+ }, schema.additionalProperties);
630
566
  } else {
631
567
  additionalProperties = {
632
568
  type: guessType(get(formData, [key]))
@@ -698,9 +634,9 @@ function resolveDependencies(validator, schema, rootSchema, formData) {
698
634
  remainingSchema = _objectWithoutPropertiesLoose(schema, _excluded4);
699
635
  var resolvedSchema = remainingSchema;
700
636
  if (Array.isArray(resolvedSchema.oneOf)) {
701
- resolvedSchema = resolvedSchema.oneOf[getMatchingOption(validator, formData, resolvedSchema.oneOf, rootSchema)];
637
+ resolvedSchema = resolvedSchema.oneOf[getFirstMatchingOption(validator, formData, resolvedSchema.oneOf, rootSchema)];
702
638
  } else if (Array.isArray(resolvedSchema.anyOf)) {
703
- resolvedSchema = resolvedSchema.anyOf[getMatchingOption(validator, formData, resolvedSchema.anyOf, rootSchema)];
639
+ resolvedSchema = resolvedSchema.anyOf[getFirstMatchingOption(validator, formData, resolvedSchema.anyOf, rootSchema)];
704
640
  }
705
641
  return processDependencies(validator, dependencies, resolvedSchema, rootSchema, formData);
706
642
  }
@@ -821,6 +757,242 @@ function withExactlyOneSubschema(validator, schema, rootSchema, dependencyKey, o
821
757
  return mergeSchemas(schema, retrieveSchema(validator, dependentSchema, rootSchema, formData));
822
758
  }
823
759
 
760
+ /** A junk option used to determine when the getFirstMatchingOption call really matches an option rather than returning
761
+ * the first item
762
+ */
763
+ var JUNK_OPTION = {
764
+ type: "object",
765
+ properties: {
766
+ __not_really_there__: {
767
+ type: "number"
768
+ }
769
+ }
770
+ };
771
+ /** Recursive function that calculates the score of a `formData` against the given `schema`. The computation is fairly
772
+ * simple. Initially the total score is 0. When `schema.properties` object exists, then all the `key/value` pairs within
773
+ * the object are processed as follows after obtaining the formValue from `formData` using the `key`:
774
+ * - If the `value` contains a `$ref`, `calculateIndexScore()` is called recursively with the formValue and the new
775
+ * schema that is the result of the ref in the schema being resolved and that sub-schema's resulting score is added to
776
+ * the total.
777
+ * - If the `value` contains a `oneOf` and there is a formValue, then score based on the index returned from calling
778
+ * `getClosestMatchingOption()` of that oneOf.
779
+ * - If the type of the `value` is 'object', `calculateIndexScore()` is called recursively with the formValue and the
780
+ * `value` itself as the sub-schema, and the score is added to the total.
781
+ * - If the type of the `value` matches the guessed-type of the `formValue`, the score is incremented by 1, UNLESS the
782
+ * value has a `default` or `const`. In those case, if the `default` or `const` and the `formValue` match, the score
783
+ * is incremented by another 1 otherwise it is decremented by 1.
784
+ *
785
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
786
+ * @param rootSchema - The root JSON schema of the entire form
787
+ * @param schema - The schema for which the score is being calculated
788
+ * @param formData - The form data associated with the schema, used to calculate the score
789
+ * @returns - The score a schema against the formData
790
+ */
791
+ function calculateIndexScore(validator, rootSchema, schema, formData) {
792
+ if (formData === void 0) {
793
+ formData = {};
794
+ }
795
+ var totalScore = 0;
796
+ if (schema) {
797
+ if (isObject$1(schema.properties)) {
798
+ totalScore += reduce(schema.properties, function (score, value, key) {
799
+ var formValue = get(formData, key);
800
+ if (typeof value === "boolean") {
801
+ return score;
802
+ }
803
+ if (has(value, REF_KEY)) {
804
+ var newSchema = retrieveSchema(validator, value, rootSchema, formValue);
805
+ return score + calculateIndexScore(validator, rootSchema, newSchema, formValue || {});
806
+ }
807
+ if (has(value, ONE_OF_KEY) && formValue) {
808
+ return score + getClosestMatchingOption(validator, rootSchema, formValue, get(value, ONE_OF_KEY));
809
+ }
810
+ if (value.type === "object") {
811
+ return score + calculateIndexScore(validator, rootSchema, value, formValue || {});
812
+ }
813
+ if (value.type === guessType(formValue)) {
814
+ // If the types match, then we bump the score by one
815
+ var newScore = score + 1;
816
+ if (value["default"]) {
817
+ // If the schema contains a readonly default value score the value that matches the default higher and
818
+ // any non-matching value lower
819
+ newScore += formValue === value["default"] ? 1 : -1;
820
+ } else if (value["const"]) {
821
+ // If the schema contains a const value score the value that matches the default higher and
822
+ // any non-matching value lower
823
+ newScore += formValue === value["const"] ? 1 : -1;
824
+ }
825
+ // TODO eventually, deal with enums/arrays
826
+ return newScore;
827
+ }
828
+ return score;
829
+ }, 0);
830
+ } else if (isString(schema.type) && schema.type === guessType(formData)) {
831
+ totalScore += 1;
832
+ }
833
+ }
834
+ return totalScore;
835
+ }
836
+ /** Determines which of the given `options` provided most closely matches the `formData`. Using
837
+ * `getFirstMatchingOption()` to match two schemas that differ only by the readOnly, default or const value of a field
838
+ * based on the `formData` and returns 0 when there is no match. Rather than passing in all the `options` at once to
839
+ * this utility, instead an array of valid option indexes is created by iterating over the list of options, call
840
+ * `getFirstMatchingOptions` with a list of one junk option and one good option, seeing if the good option is considered
841
+ * matched.
842
+ *
843
+ * Once the list of valid indexes is created, if there is only one valid index, just return it. Otherwise, if there are
844
+ * no valid indexes, then fill the valid indexes array with the indexes of all the options. Next, the index of the
845
+ * option with the highest score is determined by iterating over the list of valid options, calling
846
+ * `calculateIndexScore()` on each, comparing it against the current best score, and returning the index of the one that
847
+ * eventually has the best score.
848
+ *
849
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
850
+ * @param rootSchema - The root JSON schema of the entire form
851
+ * @param formData - The form data associated with the schema
852
+ * @param options - The list of options that can be selected from
853
+ * @param [selectedOption=-1] - The index of the currently selected option, defaulted to -1 if not specified
854
+ * @returns - The index of the option that is the closest match to the `formData` or the `selectedOption` if no match
855
+ */
856
+ function getClosestMatchingOption(validator, rootSchema, formData, options, selectedOption) {
857
+ if (selectedOption === void 0) {
858
+ selectedOption = -1;
859
+ }
860
+ // Reduce the array of options down to a list of the indexes that are considered matching options
861
+ var allValidIndexes = options.reduce(function (validList, option, index) {
862
+ var testOptions = [JUNK_OPTION, option];
863
+ var match = getFirstMatchingOption(validator, formData, testOptions, rootSchema);
864
+ // The match is the real option, so add its index to list of valid indexes
865
+ if (match === 1) {
866
+ validList.push(index);
867
+ }
868
+ return validList;
869
+ }, []);
870
+ // There is only one valid index, so return it!
871
+ if (allValidIndexes.length === 1) {
872
+ return allValidIndexes[0];
873
+ }
874
+ if (!allValidIndexes.length) {
875
+ // No indexes were valid, so we'll score all the options, add all the indexes
876
+ times(options.length, function (i) {
877
+ return allValidIndexes.push(i);
878
+ });
879
+ }
880
+ // Score all the options in the list of valid indexes and return the index with the best score
881
+ var _allValidIndexes$redu = allValidIndexes.reduce(function (scoreData, index) {
882
+ var bestScore = scoreData.bestScore;
883
+ var option = options[index];
884
+ if (has(option, REF_KEY)) {
885
+ option = retrieveSchema(validator, option, rootSchema, formData);
886
+ }
887
+ var score = calculateIndexScore(validator, rootSchema, option, formData);
888
+ if (score > bestScore) {
889
+ return {
890
+ bestIndex: index,
891
+ bestScore: score
892
+ };
893
+ }
894
+ return scoreData;
895
+ }, {
896
+ bestIndex: selectedOption,
897
+ bestScore: 0
898
+ }),
899
+ bestIndex = _allValidIndexes$redu.bestIndex;
900
+ return bestIndex;
901
+ }
902
+
903
+ /** Detects whether the given `schema` contains fixed items. This is the case when `schema.items` is a non-empty array
904
+ * that only contains objects.
905
+ *
906
+ * @param schema - The schema in which to check for fixed items
907
+ * @returns - True if there are fixed items in the schema, false otherwise
908
+ */
909
+ function isFixedItems(schema) {
910
+ return Array.isArray(schema.items) && schema.items.length > 0 && schema.items.every(function (item) {
911
+ return isObject(item);
912
+ });
913
+ }
914
+
915
+ /** Merges the `defaults` object of type `T` into the `formData` of type `T`
916
+ *
917
+ * When merging defaults and form data, we want to merge in this specific way:
918
+ * - objects are deeply merged
919
+ * - arrays are merged in such a way that:
920
+ * - when the array is set in form data, only array entries set in form data
921
+ * are deeply merged; additional entries from the defaults are ignored
922
+ * - when the array is not set in form data, the default is copied over
923
+ * - scalars are overwritten/set by form data
924
+ *
925
+ * @param [defaults] - The defaults to merge
926
+ * @param [formData] - The form data into which the defaults will be merged
927
+ * @returns - The resulting merged form data with defaults
928
+ */
929
+ function mergeDefaultsWithFormData(defaults, formData) {
930
+ if (Array.isArray(formData)) {
931
+ var defaultsArray = Array.isArray(defaults) ? defaults : [];
932
+ var mapped = formData.map(function (value, idx) {
933
+ if (defaultsArray[idx]) {
934
+ return mergeDefaultsWithFormData(defaultsArray[idx], value);
935
+ }
936
+ return value;
937
+ });
938
+ return mapped;
939
+ }
940
+ if (isObject(formData)) {
941
+ var acc = Object.assign({}, defaults); // Prevent mutation of source object.
942
+ return Object.keys(formData).reduce(function (acc, key) {
943
+ acc[key] = mergeDefaultsWithFormData(defaults ? get(defaults, key) : {}, get(formData, key));
944
+ return acc;
945
+ }, acc);
946
+ }
947
+ return formData;
948
+ }
949
+
950
+ /** Recursively merge deeply nested objects.
951
+ *
952
+ * @param obj1 - The first object to merge
953
+ * @param obj2 - The second object to merge
954
+ * @param [concatArrays=false] - Optional flag that, when true, will cause arrays to be concatenated. Use
955
+ * "preventDuplicates" to merge arrays in a manner that prevents any duplicate entries from being merged.
956
+ * NOTE: Uses shallow comparison for the duplicate checking.
957
+ * @returns - A new object that is the merge of the two given objects
958
+ */
959
+ function mergeObjects(obj1, obj2, concatArrays) {
960
+ if (concatArrays === void 0) {
961
+ concatArrays = false;
962
+ }
963
+ return Object.keys(obj2).reduce(function (acc, key) {
964
+ var left = obj1 ? obj1[key] : {},
965
+ right = obj2[key];
966
+ if (obj1 && key in obj1 && isObject(right)) {
967
+ acc[key] = mergeObjects(left, right, concatArrays);
968
+ } else if (concatArrays && Array.isArray(left) && Array.isArray(right)) {
969
+ var toMerge = right;
970
+ if (concatArrays === "preventDuplicates") {
971
+ toMerge = right.reduce(function (result, value) {
972
+ if (!left.includes(value)) {
973
+ result.push(value);
974
+ }
975
+ return result;
976
+ }, []);
977
+ }
978
+ acc[key] = left.concat(toMerge);
979
+ } else {
980
+ acc[key] = right;
981
+ }
982
+ return acc;
983
+ }, Object.assign({}, obj1)); // Prevent mutation of source object.
984
+ }
985
+
986
+ /** This function checks if the given `schema` matches a single constant value. This happens when either the schema has
987
+ * an `enum` array with a single value or there is a `const` defined.
988
+ *
989
+ * @param schema - The schema for a field
990
+ * @returns - True if the `schema` has a single constant value, false otherwise
991
+ */
992
+ function isConstant(schema) {
993
+ return Array.isArray(schema["enum"]) && schema["enum"].length === 1 || CONST_KEY in schema;
994
+ }
995
+
824
996
  /** Checks to see if the `schema` combination represents a select
825
997
  *
826
998
  * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
@@ -946,9 +1118,9 @@ function computeDefaults(validator, rawSchema, parentDefaults, rootSchema, rawFo
946
1118
  return computeDefaults(validator, itemSchema, Array.isArray(parentDefaults) ? parentDefaults[idx] : undefined, rootSchema, formData, includeUndefinedValues);
947
1119
  });
948
1120
  } else if (ONE_OF_KEY in schema) {
949
- schema = schema.oneOf[getMatchingOption(validator, isEmpty(formData) ? undefined : formData, schema.oneOf, rootSchema)];
1121
+ schema = schema.oneOf[getClosestMatchingOption(validator, rootSchema, isEmpty(formData) ? undefined : formData, schema.oneOf, 0)];
950
1122
  } else if (ANY_OF_KEY in schema) {
951
- schema = schema.anyOf[getMatchingOption(validator, isEmpty(formData) ? undefined : formData, schema.anyOf, rootSchema)];
1123
+ schema = schema.anyOf[getClosestMatchingOption(validator, rootSchema, isEmpty(formData) ? undefined : formData, schema.anyOf, 0)];
952
1124
  }
953
1125
  // Not defaults defined for this node, fallback to generic typed ones.
954
1126
  if (typeof defaults === "undefined") {
@@ -1140,6 +1312,169 @@ function mergeValidationData(validator, validationData, additionalErrorSchema) {
1140
1312
  };
1141
1313
  }
1142
1314
 
1315
+ var NO_VALUE = /*#__PURE__*/Symbol("no Value");
1316
+ /** Sanitize the `data` associated with the `oldSchema` so it is considered appropriate for the `newSchema`. If the new
1317
+ * schema does not contain any properties, then `undefined` is returned to clear all the form data. Due to the nature
1318
+ * of schemas, this sanitization happens recursively for nested objects of data. Also, any properties in the old schema
1319
+ * that are non-existent in the new schema are set to `undefined`. The data sanitization process has the following flow:
1320
+ *
1321
+ * - If the new schema is an object that contains a `properties` object then:
1322
+ * - Create a `removeOldSchemaData` object, setting each key in the `oldSchema.properties` having `data` to undefined
1323
+ * - Create an empty `nestedData` object for use in the key filtering below:
1324
+ * - Iterate over each key in the `newSchema.properties` as follows:
1325
+ * - Get the `formValue` of the key from the `data`
1326
+ * - Get the `oldKeySchema` and `newKeyedSchema` for the key, defaulting to `{}` when it doesn't exist
1327
+ * - Retrieve the schema for any refs within each `oldKeySchema` and/or `newKeySchema`
1328
+ * - Get the types of the old and new keyed schemas and if the old doesn't exist or the old & new are the same then:
1329
+ * - If `removeOldSchemaData` has an entry for the key, delete it since the new schema has the same property
1330
+ * - If type of the key in the new schema is `object`:
1331
+ * - Store the value from the recursive `sanitizeDataForNewSchema` call in `nestedData[key]`
1332
+ * - Otherwise, check for default or const values:
1333
+ * - Get the old and new `default` values from the schema and check:
1334
+ * - If the new `default` value does not match the form value:
1335
+ * - If the old `default` value DOES match the form value, then:
1336
+ * - Replace `removeOldSchemaData[key]` with the new `default`
1337
+ * - Otherwise, if the new schema is `readOnly` then replace `removeOldSchemaData[key]` with undefined
1338
+ * - Get the old and new `const` values from the schema and check:
1339
+ * - If the new `const` value does not match the form value:
1340
+ * - If the old `const` value DOES match the form value, then:
1341
+ * - Replace `removeOldSchemaData[key]` with the new `const`
1342
+ * - Otherwise, replace `removeOldSchemaData[key]` with undefined
1343
+ * - Once all keys have been processed, return an object built as follows:
1344
+ * - `{ ...removeOldSchemaData, ...nestedData, ...pick(data, keysToKeep) }`
1345
+ * - If the new and old schema types are array and the `data` is an array then:
1346
+ * - If the type of the old and new schema `items` are a non-array objects:
1347
+ * - Retrieve the schema for any refs within each `oldKeySchema.items` and/or `newKeySchema.items`
1348
+ * - If the `type`s of both items are the same (or the old does not have a type):
1349
+ * - If the type is "object", then:
1350
+ * - For each element in the `data` recursively sanitize the data, stopping at `maxItems` if specified
1351
+ * - Otherwise, just return the `data` removing any values after `maxItems` if it is set
1352
+ * - If the type of the old and new schema `items` are booleans of the same value, return `data` as is
1353
+ * - Otherwise return `undefined`
1354
+ *
1355
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
1356
+ * @param rootSchema - The root JSON schema of the entire form
1357
+ * @param [newSchema] - The new schema for which the data is being sanitized
1358
+ * @param [oldSchema] - The old schema from which the data originated
1359
+ * @param [data={}] - The form data associated with the schema, defaulting to an empty object when undefined
1360
+ * @returns - The new form data, with all the fields uniquely associated with the old schema set
1361
+ * to `undefined`. Will return `undefined` if the new schema is not an object containing properties.
1362
+ */
1363
+ function sanitizeDataForNewSchema(validator, rootSchema, newSchema, oldSchema, data) {
1364
+ if (data === void 0) {
1365
+ data = {};
1366
+ }
1367
+ // By default, we will clear the form data
1368
+ var newFormData;
1369
+ // If the new schema is of type object and that object contains a list of properties
1370
+ if (has(newSchema, PROPERTIES_KEY)) {
1371
+ // Create an object containing root-level keys in the old schema, setting each key to undefined to remove the data
1372
+ var removeOldSchemaData = {};
1373
+ if (has(oldSchema, PROPERTIES_KEY)) {
1374
+ var properties = get(oldSchema, PROPERTIES_KEY, {});
1375
+ Object.keys(properties).forEach(function (key) {
1376
+ if (has(data, key)) {
1377
+ removeOldSchemaData[key] = undefined;
1378
+ }
1379
+ });
1380
+ }
1381
+ var keys = Object.keys(get(newSchema, PROPERTIES_KEY, {}));
1382
+ // Create a place to store nested data that will be a side-effect of the filter
1383
+ var nestedData = {};
1384
+ keys.forEach(function (key) {
1385
+ var formValue = get(data, key);
1386
+ var oldKeyedSchema = get(oldSchema, [PROPERTIES_KEY, key], {});
1387
+ var newKeyedSchema = get(newSchema, [PROPERTIES_KEY, key], {});
1388
+ // Resolve the refs if they exist
1389
+ if (has(oldKeyedSchema, REF_KEY)) {
1390
+ oldKeyedSchema = retrieveSchema(validator, oldKeyedSchema, rootSchema, formValue);
1391
+ }
1392
+ if (has(newKeyedSchema, REF_KEY)) {
1393
+ newKeyedSchema = retrieveSchema(validator, newKeyedSchema, rootSchema, formValue);
1394
+ }
1395
+ // Now get types and see if they are the same
1396
+ var oldSchemaTypeForKey = get(oldKeyedSchema, "type");
1397
+ var newSchemaTypeForKey = get(newKeyedSchema, "type");
1398
+ // Check if the old option has the same key with the same type
1399
+ if (!oldSchemaTypeForKey || oldSchemaTypeForKey === newSchemaTypeForKey) {
1400
+ if (has(removeOldSchemaData, key)) {
1401
+ // SIDE-EFFECT: remove the undefined value for a key that has the same type between the old and new schemas
1402
+ delete removeOldSchemaData[key];
1403
+ }
1404
+ // If it is an object, we'll recurse and store the resulting sanitized data for the key
1405
+ if (newSchemaTypeForKey === "object" || newSchemaTypeForKey === "array" && Array.isArray(formValue)) {
1406
+ // SIDE-EFFECT: process the new schema type of object recursively to save iterations
1407
+ var itemData = sanitizeDataForNewSchema(validator, rootSchema, newKeyedSchema, oldKeyedSchema, formValue);
1408
+ if (itemData !== undefined || newSchemaTypeForKey === "array") {
1409
+ // only put undefined values for the array type and not the object type
1410
+ nestedData[key] = itemData;
1411
+ }
1412
+ } else {
1413
+ // Ok, the non-object types match, let's make sure that a default or a const of a different value is replaced
1414
+ // with the new default or const. This allows the case where two schemas differ that only by the default/const
1415
+ // value to be properly selected
1416
+ var newOptionDefault = get(newKeyedSchema, "default", NO_VALUE);
1417
+ var oldOptionDefault = get(oldKeyedSchema, "default", NO_VALUE);
1418
+ if (newOptionDefault !== NO_VALUE && newOptionDefault !== formValue) {
1419
+ if (oldOptionDefault === formValue) {
1420
+ // If the old default matches the formValue, we'll update the new value to match the new default
1421
+ removeOldSchemaData[key] = newOptionDefault;
1422
+ } else if (get(newKeyedSchema, "readOnly") === true) {
1423
+ // If the new schema has the default set to read-only, treat it like a const and remove the value
1424
+ removeOldSchemaData[key] = undefined;
1425
+ }
1426
+ }
1427
+ var newOptionConst = get(newKeyedSchema, "const", NO_VALUE);
1428
+ var oldOptionConst = get(oldKeyedSchema, "const", NO_VALUE);
1429
+ if (newOptionConst !== NO_VALUE && newOptionConst !== formValue) {
1430
+ // Since this is a const, if the old value matches, replace the value with the new const otherwise clear it
1431
+ removeOldSchemaData[key] = oldOptionConst === formValue ? newOptionConst : undefined;
1432
+ }
1433
+ }
1434
+ }
1435
+ });
1436
+ newFormData = _extends({}, data, removeOldSchemaData, nestedData);
1437
+ // First apply removing the old schema data, then apply the nested data, then apply the old data keys to keep
1438
+ } else if (get(oldSchema, "type") === "array" && get(newSchema, "type") === "array" && Array.isArray(data)) {
1439
+ var oldSchemaItems = get(oldSchema, "items");
1440
+ var newSchemaItems = get(newSchema, "items");
1441
+ // If any of the array types `items` are arrays (remember arrays are objects) then we'll just drop the data
1442
+ // Eventually, we may want to deal with when either of the `items` are arrays since those tuple validations
1443
+ if (typeof oldSchemaItems === "object" && typeof newSchemaItems === "object" && !Array.isArray(oldSchemaItems) && !Array.isArray(newSchemaItems)) {
1444
+ if (has(oldSchemaItems, REF_KEY)) {
1445
+ oldSchemaItems = retrieveSchema(validator, oldSchemaItems, rootSchema, data);
1446
+ }
1447
+ if (has(newSchemaItems, REF_KEY)) {
1448
+ newSchemaItems = retrieveSchema(validator, newSchemaItems, rootSchema, data);
1449
+ }
1450
+ // Now get types and see if they are the same
1451
+ var oldSchemaType = get(oldSchemaItems, "type");
1452
+ var newSchemaType = get(newSchemaItems, "type");
1453
+ // Check if the old option has the same key with the same type
1454
+ if (!oldSchemaType || oldSchemaType === newSchemaType) {
1455
+ var maxItems = get(newSchema, "maxItems", -1);
1456
+ if (newSchemaType === "object") {
1457
+ newFormData = data.reduce(function (newValue, aValue) {
1458
+ var itemValue = sanitizeDataForNewSchema(validator, rootSchema, newSchemaItems, oldSchemaItems, aValue);
1459
+ if (itemValue !== undefined && (maxItems < 0 || newValue.length < maxItems)) {
1460
+ newValue.push(itemValue);
1461
+ }
1462
+ return newValue;
1463
+ }, []);
1464
+ } else {
1465
+ newFormData = maxItems > 0 && data.length > maxItems ? data.slice(0, maxItems) : data;
1466
+ }
1467
+ }
1468
+ } else if (typeof oldSchemaItems === "boolean" && typeof newSchemaItems === "boolean" && oldSchemaItems === newSchemaItems) {
1469
+ // If they are both booleans and have the same value just return the data as is otherwise fall-thru to undefined
1470
+ newFormData = data;
1471
+ }
1472
+ // Also probably want to deal with `prefixItems` as tuples with the latest 2020 draft
1473
+ }
1474
+
1475
+ return newFormData;
1476
+ }
1477
+
1143
1478
  /** Generates an `IdSchema` object for the `schema`, recursively
1144
1479
  *
1145
1480
  * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
@@ -1285,11 +1620,37 @@ var SchemaUtils = /*#__PURE__*/function () {
1285
1620
  _proto.getDisplayLabel = function getDisplayLabel$1(schema, uiSchema) {
1286
1621
  return getDisplayLabel(this.validator, schema, uiSchema, this.rootSchema);
1287
1622
  }
1623
+ /** Determines which of the given `options` provided most closely matches the `formData`.
1624
+ * Returns the index of the option that is valid and is the closest match, or 0 if there is no match.
1625
+ *
1626
+ * The closest match is determined using the number of matching properties, and more heavily favors options with
1627
+ * matching readOnly, default, or const values.
1628
+ *
1629
+ * @param formData - The form data associated with the schema
1630
+ * @param options - The list of options that can be selected from
1631
+ * @param [selectedOption] - The index of the currently selected option, defaulted to -1 if not specified
1632
+ * @returns - The index of the option that is the closest match to the `formData` or the `selectedOption` if no match
1633
+ */;
1634
+ _proto.getClosestMatchingOption = function getClosestMatchingOption$1(formData, options, selectedOption) {
1635
+ return getClosestMatchingOption(this.validator, this.rootSchema, formData, options, selectedOption);
1636
+ }
1637
+ /** Given the `formData` and list of `options`, attempts to find the index of the first option that matches the data.
1638
+ * Always returns the first option if there is nothing that matches.
1639
+ *
1640
+ * @param formData - The current formData, if any, used to figure out a match
1641
+ * @param options - The list of options to find a matching options from
1642
+ * @returns - The firstindex of the matched option or 0 if none is available
1643
+ */;
1644
+ _proto.getFirstMatchingOption = function getFirstMatchingOption$1(formData, options) {
1645
+ return getFirstMatchingOption(this.validator, formData, options, this.rootSchema);
1646
+ }
1288
1647
  /** Given the `formData` and list of `options`, attempts to find the index of the option that best matches the data.
1648
+ * Deprecated, use `getFirstMatchingOption()` instead.
1289
1649
  *
1290
1650
  * @param formData - The current formData, if any, onto which to provide any missing defaults
1291
1651
  * @param options - The list of options to find a matching options from
1292
1652
  * @returns - The index of the matched option or 0 if none is available
1653
+ * @deprecated
1293
1654
  */;
1294
1655
  _proto.getMatchingOption = function getMatchingOption$1(formData, options) {
1295
1656
  return getMatchingOption(this.validator, formData, options, this.rootSchema);
@@ -1342,6 +1703,20 @@ var SchemaUtils = /*#__PURE__*/function () {
1342
1703
  _proto.retrieveSchema = function retrieveSchema$1(schema, rawFormData) {
1343
1704
  return retrieveSchema(this.validator, schema, this.rootSchema, rawFormData);
1344
1705
  }
1706
+ /** Sanitize the `data` associated with the `oldSchema` so it is considered appropriate for the `newSchema`. If the
1707
+ * new schema does not contain any properties, then `undefined` is returned to clear all the form data. Due to the
1708
+ * nature of schemas, this sanitization happens recursively for nested objects of data. Also, any properties in the
1709
+ * old schemas that are non-existent in the new schema are set to `undefined`.
1710
+ *
1711
+ * @param [newSchema] - The new schema for which the data is being sanitized
1712
+ * @param [oldSchema] - The old schema from which the data originated
1713
+ * @param [data={}] - The form data associated with the schema, defaulting to an empty object when undefined
1714
+ * @returns - The new form data, with all the fields uniquely associated with the old schema set
1715
+ * to `undefined`. Will return `undefined` if the new schema is not an object containing properties.
1716
+ */;
1717
+ _proto.sanitizeDataForNewSchema = function sanitizeDataForNewSchema$1(newSchema, oldSchema, data) {
1718
+ return sanitizeDataForNewSchema(this.validator, this.rootSchema, newSchema, oldSchema, data);
1719
+ }
1345
1720
  /** Generates an `IdSchema` object for the `schema`, recursively
1346
1721
  *
1347
1722
  * @param schema - The schema for which the display label flag is desired
@@ -2196,5 +2571,5 @@ function utcToLocal(jsonDate) {
2196
2571
  return yyyy + "-" + MM + "-" + dd + "T" + hh + ":" + mm + ":" + ss + "." + SSS;
2197
2572
  }
2198
2573
 
2199
- export { ADDITIONAL_PROPERTIES_KEY, ADDITIONAL_PROPERTY_FLAG, ALL_OF_KEY, ANY_OF_KEY, CONST_KEY, DEFAULT_KEY, DEFINITIONS_KEY, DEPENDENCIES_KEY, ENUM_KEY, ERRORS_KEY, ErrorSchemaBuilder, ID_KEY, ITEMS_KEY, NAME_KEY, ONE_OF_KEY, PROPERTIES_KEY, REF_KEY, REQUIRED_KEY, RJSF_ADDITONAL_PROPERTIES_FLAG, SUBMIT_BTN_OPTIONS_KEY, UI_FIELD_KEY, UI_OPTIONS_KEY, UI_WIDGET_KEY, allowAdditionalItems, ariaDescribedByIds, asNumber, canExpand, createSchemaUtils, dataURItoBlob, deepEquals, descriptionId, enumOptionsDeselectValue, enumOptionsSelectValue, errorId, examplesId, findSchemaDefinition, getDefaultFormState, getDisplayLabel, getInputProps, getMatchingOption, getSchemaType, getSubmitButtonOptions, getTemplate, getUiOptions, getWidget, guessType, hasWidget, helpId, isConstant, isCustomWidget, isFilesArray, isFixedItems, isMultiSelect, isObject, isSelect, localToUTC, mergeDefaultsWithFormData, mergeObjects, mergeSchemas, mergeValidationData, optionId, optionsList, orderProperties, pad, parseDateString, processSelectValue, rangeSpec, retrieveSchema, schemaRequiresTrueValue, shouldRender, titleId, toConstant, toDateString, toIdSchema, toPathSchema, utcToLocal };
2574
+ export { ADDITIONAL_PROPERTIES_KEY, ADDITIONAL_PROPERTY_FLAG, ALL_OF_KEY, ANY_OF_KEY, CONST_KEY, DEFAULT_KEY, DEFINITIONS_KEY, DEPENDENCIES_KEY, ENUM_KEY, ERRORS_KEY, ErrorSchemaBuilder, ID_KEY, ITEMS_KEY, NAME_KEY, ONE_OF_KEY, PROPERTIES_KEY, REF_KEY, REQUIRED_KEY, RJSF_ADDITONAL_PROPERTIES_FLAG, SUBMIT_BTN_OPTIONS_KEY, UI_FIELD_KEY, UI_OPTIONS_KEY, UI_WIDGET_KEY, allowAdditionalItems, ariaDescribedByIds, asNumber, canExpand, createSchemaUtils, dataURItoBlob, deepEquals, descriptionId, enumOptionsDeselectValue, enumOptionsSelectValue, errorId, examplesId, findSchemaDefinition, getClosestMatchingOption, getDefaultFormState, getDisplayLabel, getFirstMatchingOption, getInputProps, getMatchingOption, getSchemaType, getSubmitButtonOptions, getTemplate, getUiOptions, getWidget, guessType, hasWidget, helpId, isConstant, isCustomWidget, isFilesArray, isFixedItems, isMultiSelect, isObject, isSelect, localToUTC, mergeDefaultsWithFormData, mergeObjects, mergeSchemas, mergeValidationData, optionId, optionsList, orderProperties, pad, parseDateString, processSelectValue, rangeSpec, retrieveSchema, sanitizeDataForNewSchema, schemaRequiresTrueValue, shouldRender, titleId, toConstant, toDateString, toIdSchema, toPathSchema, utcToLocal };
2200
2575
  //# sourceMappingURL=utils.esm.js.map