(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('lodash/isPlainObject'), require('lodash/isEqualWith'), require('lodash/get'), require('lodash/isEmpty'), require('jsonpointer'), require('lodash/omit'), require('lodash/has'), require('lodash/isNumber'), require('lodash/isObject'), require('lodash/isString'), require('lodash/reduce'), require('lodash/times'), require('lodash/set'), require('lodash/transform'), require('lodash/merge'), require('lodash/flattenDeep'), require('lodash/uniq'), require('json-schema-merge-allof'), require('lodash/union'), require('lodash/isNil'), require('lodash/cloneDeep'), require('lodash/setWith'), require('react'), require('react-is'), require('react/jsx-runtime'), require('lodash/toPath'), require('lodash/keys'), require('lodash/pickBy'), require('lodash/difference'), require('lodash/forEach')) :
  typeof define === 'function' && define.amd ? define(['exports', 'lodash/isPlainObject', 'lodash/isEqualWith', 'lodash/get', 'lodash/isEmpty', 'jsonpointer', 'lodash/omit', 'lodash/has', 'lodash/isNumber', 'lodash/isObject', 'lodash/isString', 'lodash/reduce', 'lodash/times', 'lodash/set', 'lodash/transform', 'lodash/merge', 'lodash/flattenDeep', 'lodash/uniq', 'json-schema-merge-allof', 'lodash/union', 'lodash/isNil', 'lodash/cloneDeep', 'lodash/setWith', 'react', 'react-is', 'react/jsx-runtime', 'lodash/toPath', 'lodash/keys', 'lodash/pickBy', 'lodash/difference', 'lodash/forEach'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@rjsf/utils"] = {}, global.isPlainObject4, global.isEqualWith, global.get8, global.isEmpty, global.jsonpointer, global.omit, global.has3, global.isNumber, global.isObject2, global.isString, global.reduce, global.times, global.set3, global.transform, global.merge, global.flattenDeep, global.uniq, global.mergeAllOf, global.union, global.isNil, global.cloneDeep, global.setWith, global.react, global.ReactIs, global.jsxRuntime, global.toPath, global.keys, global.pickBy, global.difference, global.forEach));
})(this, (function (exports, isPlainObject4, isEqualWith, get8, isEmpty, jsonpointer, omit, has3, isNumber, isObject2, isString, reduce, times, set3, transform, merge, flattenDeep, uniq, mergeAllOf, union, isNil, cloneDeep, setWith, react, ReactIs, jsxRuntime, toPath, keys, pickBy, difference, forEach) { 'use strict';

  // src/isObject.ts
  function isObject(thing) {
    if (typeof thing !== "object" || thing === null) {
      return false;
    }
    if (typeof thing.lastModified === "number" && typeof File !== "undefined" && thing instanceof File) {
      return false;
    }
    if (typeof thing.getMonth === "function" && typeof Date !== "undefined" && thing instanceof Date) {
      return false;
    }
    return !Array.isArray(thing);
  }

  // src/allowAdditionalItems.ts
  function allowAdditionalItems(schema) {
    if (schema.additionalItems === true) {
      console.warn("additionalItems=true is currently not supported");
    }
    return isObject(schema.additionalItems);
  }

  // src/asNumber.ts
  function asNumber(value) {
    if (value === "") {
      return void 0;
    }
    if (value === null) {
      return null;
    }
    if (/\.$/.test(value)) {
      return value;
    }
    if (/\.0$/.test(value)) {
      return value;
    }
    if (/\.\d*0$/.test(value)) {
      return value;
    }
    const n = Number(value);
    const valid = typeof n === "number" && !Number.isNaN(n);
    return valid ? n : value;
  }

  // src/constants.ts
  var ADDITIONAL_PROPERTY_FLAG = "__additional_property";
  var ADDITIONAL_PROPERTIES_KEY = "additionalProperties";
  var ALL_OF_KEY = "allOf";
  var ANY_OF_KEY = "anyOf";
  var CONST_KEY = "const";
  var DEFAULT_KEY = "default";
  var DEFINITIONS_KEY = "definitions";
  var DEPENDENCIES_KEY = "dependencies";
  var ENUM_KEY = "enum";
  var ERRORS_KEY = "__errors";
  var ID_KEY = "$id";
  var IF_KEY = "if";
  var ITEMS_KEY = "items";
  var JUNK_OPTION_ID = "_$junk_option_schema_id$_";
  var NAME_KEY = "$name";
  var ONE_OF_KEY = "oneOf";
  var PROPERTIES_KEY = "properties";
  var REQUIRED_KEY = "required";
  var SUBMIT_BTN_OPTIONS_KEY = "submitButtonOptions";
  var REF_KEY = "$ref";
  var RJSF_ADDITONAL_PROPERTIES_FLAG = "__rjsf_additionalProperties";
  var RJSF_ADDITIONAL_PROPERTIES_FLAG = "__rjsf_additionalProperties";
  var ROOT_SCHEMA_PREFIX = "__rjsf_rootSchema";
  var UI_FIELD_KEY = "ui:field";
  var UI_WIDGET_KEY = "ui:widget";
  var UI_OPTIONS_KEY = "ui:options";
  var UI_GLOBAL_OPTIONS_KEY = "ui:globalOptions";

  // src/getUiOptions.ts
  function getUiOptions(uiSchema = {}, globalOptions = {}) {
    return Object.keys(uiSchema).filter((key) => key.indexOf("ui:") === 0).reduce(
      (options, key) => {
        const value = uiSchema[key];
        if (key === UI_WIDGET_KEY && isObject(value)) {
          console.error("Setting options via ui:widget object is no longer supported, use ui:options instead");
          return options;
        }
        if (key === UI_OPTIONS_KEY && isObject(value)) {
          return { ...options, ...value };
        }
        return { ...options, [key.substring(3)]: value };
      },
      { ...globalOptions }
    );
  }

  // src/canExpand.ts
  function canExpand(schema, uiSchema = {}, formData) {
    if (!schema.additionalProperties) {
      return false;
    }
    const { expandable = true } = getUiOptions(uiSchema);
    if (expandable === false) {
      return expandable;
    }
    if (schema.maxProperties !== void 0 && formData) {
      return Object.keys(formData).length < schema.maxProperties;
    }
    return true;
  }
  function createErrorHandler(formData) {
    const handler = {
      // We store the list of errors for this node in a property named __errors
      // to avoid name collision with a possible sub schema field named
      // 'errors' (see `utils.toErrorSchema`).
      [ERRORS_KEY]: [],
      addError(message) {
        this[ERRORS_KEY].push(message);
      }
    };
    if (Array.isArray(formData)) {
      return formData.reduce((acc, value, key) => {
        return { ...acc, [key]: createErrorHandler(value) };
      }, handler);
    }
    if (isPlainObject4(formData)) {
      const formObject = formData;
      return Object.keys(formObject).reduce((acc, key) => {
        return { ...acc, [key]: createErrorHandler(formObject[key]) };
      }, handler);
    }
    return handler;
  }
  function deepEquals(a, b) {
    return isEqualWith(a, b, (obj, other) => {
      if (typeof obj === "function" && typeof other === "function") {
        return true;
      }
      return void 0;
    });
  }
  function splitKeyElementFromObject(key, object) {
    const value = object[key];
    const remaining = omit(object, [key]);
    return [remaining, value];
  }
  function findSchemaDefinitionRecursive($ref, rootSchema = {}, recurseList = []) {
    const ref = $ref || "";
    let decodedRef;
    if (ref.startsWith("#")) {
      decodedRef = decodeURIComponent(ref.substring(1));
    } else {
      throw new Error(`Could not find a definition for ${$ref}.`);
    }
    const current = jsonpointer.get(rootSchema, decodedRef);
    if (current === void 0) {
      throw new Error(`Could not find a definition for ${$ref}.`);
    }
    const nextRef = current[REF_KEY];
    if (nextRef) {
      if (recurseList.includes(nextRef)) {
        if (recurseList.length === 1) {
          throw new Error(`Definition for ${$ref} is a circular reference`);
        }
        const [firstRef, ...restRefs] = recurseList;
        const circularPath = [...restRefs, ref, firstRef].join(" -> ");
        throw new Error(`Definition for ${firstRef} contains a circular reference through ${circularPath}`);
      }
      const [remaining, theRef] = splitKeyElementFromObject(REF_KEY, current);
      const subSchema = findSchemaDefinitionRecursive(theRef, rootSchema, [...recurseList, ref]);
      if (Object.keys(remaining).length > 0) {
        return { ...remaining, ...subSchema };
      }
      return subSchema;
    }
    return current;
  }
  function findSchemaDefinition($ref, rootSchema = {}) {
    const recurseList = [];
    return findSchemaDefinitionRecursive($ref, rootSchema, recurseList);
  }
  function getOptionMatchingSimpleDiscriminator(formData, options, discriminatorField) {
    if (formData && discriminatorField) {
      const value = get8(formData, discriminatorField);
      if (value === void 0) {
        return;
      }
      for (let i = 0; i < options.length; i++) {
        const option = options[i];
        const discriminator = get8(option, [PROPERTIES_KEY, discriminatorField], {});
        if (discriminator.type === "object" || discriminator.type === "array") {
          continue;
        }
        if (discriminator.const === value) {
          return i;
        }
        if (discriminator.enum?.includes(value)) {
          return i;
        }
      }
    }
    return;
  }

  // src/schema/getMatchingOption.ts
  function getMatchingOption(validator, formData, options, rootSchema, discriminatorField) {
    if (formData === void 0) {
      return 0;
    }
    const simpleDiscriminatorMatch = getOptionMatchingSimpleDiscriminator(formData, options, discriminatorField);
    if (isNumber(simpleDiscriminatorMatch)) {
      return simpleDiscriminatorMatch;
    }
    for (let i = 0; i < options.length; i++) {
      const option = options[i];
      if (discriminatorField && has3(option, [PROPERTIES_KEY, discriminatorField])) {
        const value = get8(formData, discriminatorField);
        const discriminator = get8(option, [PROPERTIES_KEY, discriminatorField], {});
        if (validator.isValid(discriminator, value, rootSchema)) {
          return i;
        }
      } else if (option[PROPERTIES_KEY]) {
        const requiresAnyOf = {
          anyOf: Object.keys(option[PROPERTIES_KEY]).map((key) => ({
            required: [key]
          }))
        };
        let augmentedSchema;
        if (option.anyOf) {
          const { ...shallowClone } = option;
          if (!shallowClone.allOf) {
            shallowClone.allOf = [];
          } else {
            shallowClone.allOf = shallowClone.allOf.slice();
          }
          shallowClone.allOf.push(requiresAnyOf);
          augmentedSchema = shallowClone;
        } else {
          augmentedSchema = Object.assign({}, option, requiresAnyOf);
        }
        delete augmentedSchema.required;
        if (validator.isValid(augmentedSchema, formData, rootSchema)) {
          return i;
        }
      } else if (validator.isValid(option, formData, rootSchema)) {
        return i;
      }
    }
    return 0;
  }

  // src/schema/getFirstMatchingOption.ts
  function getFirstMatchingOption(validator, formData, options, rootSchema, discriminatorField) {
    return getMatchingOption(validator, formData, options, rootSchema, discriminatorField);
  }
  function getDiscriminatorFieldFromSchema(schema) {
    let discriminator;
    const maybeString = get8(schema, "discriminator.propertyName", void 0);
    if (isString(maybeString)) {
      discriminator = maybeString;
    } else if (maybeString !== void 0) {
      console.warn(`Expecting discriminator to be a string, got "${typeof maybeString}" instead`);
    }
    return discriminator;
  }

  // src/guessType.ts
  function guessType(value) {
    if (Array.isArray(value)) {
      return "array";
    }
    if (typeof value === "string") {
      return "string";
    }
    if (value == null) {
      return "null";
    }
    if (typeof value === "boolean") {
      return "boolean";
    }
    if (!isNaN(value)) {
      return "number";
    }
    if (typeof value === "object") {
      return "object";
    }
    return "string";
  }

  // src/getSchemaType.ts
  function getSchemaType(schema) {
    let { type } = schema;
    if (!type && schema.const) {
      return guessType(schema.const);
    }
    if (!type && schema.enum) {
      return "string";
    }
    if (!type && (schema.properties || schema.additionalProperties)) {
      return "object";
    }
    if (Array.isArray(type)) {
      if (type.length === 2 && type.includes("null")) {
        type = type.find((type2) => type2 !== "null");
      } else {
        type = type[0];
      }
    }
    return type;
  }

  // src/mergeSchemas.ts
  function mergeSchemas(obj1, obj2) {
    const acc = Object.assign({}, obj1);
    return Object.keys(obj2).reduce((acc2, key) => {
      const left = obj1 ? obj1[key] : {}, right = obj2[key];
      if (obj1 && key in obj1 && isObject(right)) {
        acc2[key] = mergeSchemas(left, right);
      } else if (obj1 && obj2 && (getSchemaType(obj1) === "object" || getSchemaType(obj2) === "object") && key === REQUIRED_KEY && Array.isArray(left) && Array.isArray(right)) {
        acc2[key] = union(left, right);
      } else {
        acc2[key] = right;
      }
      return acc2;
    }, acc);
  }

  // src/schema/retrieveSchema.ts
  function retrieveSchema(validator, schema, rootSchema = {}, rawFormData, experimental_customMergeAllOf) {
    return retrieveSchemaInternal(
      validator,
      schema,
      rootSchema,
      rawFormData,
      void 0,
      void 0,
      experimental_customMergeAllOf
    )[0];
  }
  function resolveCondition(validator, schema, rootSchema, expandAllBranches, recurseList, formData, experimental_customMergeAllOf) {
    const { if: expression, then, else: otherwise, ...resolvedSchemaLessConditional } = schema;
    const conditionValue = validator.isValid(expression, formData || {}, rootSchema);
    let resolvedSchemas = [resolvedSchemaLessConditional];
    let schemas = [];
    if (expandAllBranches) {
      if (then && typeof then !== "boolean") {
        schemas = schemas.concat(
          retrieveSchemaInternal(
            validator,
            then,
            rootSchema,
            formData,
            expandAllBranches,
            recurseList,
            experimental_customMergeAllOf
          )
        );
      }
      if (otherwise && typeof otherwise !== "boolean") {
        schemas = schemas.concat(
          retrieveSchemaInternal(
            validator,
            otherwise,
            rootSchema,
            formData,
            expandAllBranches,
            recurseList,
            experimental_customMergeAllOf
          )
        );
      }
    } else {
      const conditionalSchema = conditionValue ? then : otherwise;
      if (conditionalSchema && typeof conditionalSchema !== "boolean") {
        schemas = schemas.concat(
          retrieveSchemaInternal(
            validator,
            conditionalSchema,
            rootSchema,
            formData,
            expandAllBranches,
            recurseList,
            experimental_customMergeAllOf
          )
        );
      }
    }
    if (schemas.length) {
      resolvedSchemas = schemas.map((s) => mergeSchemas(resolvedSchemaLessConditional, s));
    }
    return resolvedSchemas.flatMap(
      (s) => retrieveSchemaInternal(
        validator,
        s,
        rootSchema,
        formData,
        expandAllBranches,
        recurseList,
        experimental_customMergeAllOf
      )
    );
  }
  function getAllPermutationsOfXxxOf(listOfLists) {
    const allPermutations = listOfLists.reduce(
      (permutations, list) => {
        if (list.length > 1) {
          return list.flatMap((element) => times(permutations.length, (i) => [...permutations[i]].concat(element)));
        }
        permutations.forEach((permutation) => permutation.push(list[0]));
        return permutations;
      },
      [[]]
      // Start with an empty list
    );
    return allPermutations;
  }
  function resolveSchema(validator, schema, rootSchema, expandAllBranches, recurseList, formData, experimental_customMergeAllOf) {
    const updatedSchemas = resolveReference(
      validator,
      schema,
      rootSchema,
      expandAllBranches,
      recurseList,
      formData
    );
    if (updatedSchemas.length > 1 || updatedSchemas[0] !== schema) {
      return updatedSchemas;
    }
    if (DEPENDENCIES_KEY in schema) {
      const resolvedSchemas = resolveDependencies(
        validator,
        schema,
        rootSchema,
        expandAllBranches,
        recurseList,
        formData
      );
      return resolvedSchemas.flatMap((s) => {
        return retrieveSchemaInternal(
          validator,
          s,
          rootSchema,
          formData,
          expandAllBranches,
          recurseList,
          experimental_customMergeAllOf
        );
      });
    }
    if (ALL_OF_KEY in schema && Array.isArray(schema.allOf)) {
      const allOfSchemaElements = schema.allOf.map(
        (allOfSubschema) => retrieveSchemaInternal(
          validator,
          allOfSubschema,
          rootSchema,
          formData,
          expandAllBranches,
          recurseList,
          experimental_customMergeAllOf
        )
      );
      const allPermutations = getAllPermutationsOfXxxOf(allOfSchemaElements);
      return allPermutations.map((permutation) => ({
        ...schema,
        allOf: permutation
      }));
    }
    return [schema];
  }
  function resolveReference(validator, schema, rootSchema, expandAllBranches, recurseList, formData, experimental_customMergeAllOf) {
    const updatedSchema = resolveAllReferences(schema, rootSchema, recurseList);
    if (updatedSchema !== schema) {
      return retrieveSchemaInternal(
        validator,
        updatedSchema,
        rootSchema,
        formData,
        expandAllBranches,
        recurseList,
        experimental_customMergeAllOf
      );
    }
    return [schema];
  }
  function resolveAllReferences(schema, rootSchema, recurseList) {
    if (!isObject(schema)) {
      return schema;
    }
    let resolvedSchema = schema;
    if (REF_KEY in resolvedSchema) {
      const { $ref, ...localSchema } = resolvedSchema;
      if (recurseList.includes($ref)) {
        return resolvedSchema;
      }
      recurseList.push($ref);
      const refSchema = findSchemaDefinition($ref, rootSchema);
      resolvedSchema = { ...refSchema, ...localSchema };
    }
    if (PROPERTIES_KEY in resolvedSchema) {
      const childrenLists = [];
      const updatedProps = transform(
        resolvedSchema[PROPERTIES_KEY],
        (result, value, key) => {
          const childList = [...recurseList];
          result[key] = resolveAllReferences(value, rootSchema, childList);
          childrenLists.push(childList);
        },
        {}
      );
      merge(recurseList, uniq(flattenDeep(childrenLists)));
      resolvedSchema = { ...resolvedSchema, [PROPERTIES_KEY]: updatedProps };
    }
    if (ITEMS_KEY in resolvedSchema && !Array.isArray(resolvedSchema.items) && typeof resolvedSchema.items !== "boolean") {
      resolvedSchema = {
        ...resolvedSchema,
        items: resolveAllReferences(resolvedSchema.items, rootSchema, recurseList)
      };
    }
    return deepEquals(schema, resolvedSchema) ? schema : resolvedSchema;
  }
  function stubExistingAdditionalProperties(validator, theSchema, rootSchema, aFormData, experimental_customMergeAllOf) {
    const schema = {
      ...theSchema,
      properties: { ...theSchema.properties }
    };
    const formData = aFormData && isObject(aFormData) ? aFormData : {};
    Object.keys(formData).forEach((key) => {
      if (key in schema.properties) {
        return;
      }
      let additionalProperties = {};
      if (typeof schema.additionalProperties !== "boolean") {
        if (REF_KEY in schema.additionalProperties) {
          additionalProperties = retrieveSchema(
            validator,
            { $ref: get8(schema.additionalProperties, [REF_KEY]) },
            rootSchema,
            formData,
            experimental_customMergeAllOf
          );
        } else if ("type" in schema.additionalProperties) {
          additionalProperties = { ...schema.additionalProperties };
        } else if (ANY_OF_KEY in schema.additionalProperties || ONE_OF_KEY in schema.additionalProperties) {
          additionalProperties = {
            type: "object",
            ...schema.additionalProperties
          };
        } else {
          additionalProperties = { type: guessType(get8(formData, [key])) };
        }
      } else {
        additionalProperties = { type: guessType(get8(formData, [key])) };
      }
      schema.properties[key] = additionalProperties;
      set3(schema.properties, [key, ADDITIONAL_PROPERTY_FLAG], true);
    });
    return schema;
  }
  function retrieveSchemaInternal(validator, schema, rootSchema, rawFormData, expandAllBranches = false, recurseList = [], experimental_customMergeAllOf) {
    if (!isObject(schema)) {
      return [{}];
    }
    const resolvedSchemas = resolveSchema(
      validator,
      schema,
      rootSchema,
      expandAllBranches,
      recurseList,
      rawFormData,
      experimental_customMergeAllOf
    );
    return resolvedSchemas.flatMap((s) => {
      let resolvedSchema = s;
      if (IF_KEY in resolvedSchema) {
        return resolveCondition(
          validator,
          resolvedSchema,
          rootSchema,
          expandAllBranches,
          recurseList,
          rawFormData,
          experimental_customMergeAllOf
        );
      }
      if (ALL_OF_KEY in resolvedSchema) {
        if (expandAllBranches) {
          const { allOf, ...restOfSchema } = resolvedSchema;
          return [...allOf, restOfSchema];
        }
        try {
          const withContainsSchemas = [];
          const withoutContainsSchemas = [];
          resolvedSchema.allOf?.forEach((s2) => {
            if (typeof s2 === "object" && s2.contains) {
              withContainsSchemas.push(s2);
            } else {
              withoutContainsSchemas.push(s2);
            }
          });
          if (withContainsSchemas.length) {
            resolvedSchema = { ...resolvedSchema, allOf: withoutContainsSchemas };
          }
          resolvedSchema = experimental_customMergeAllOf ? experimental_customMergeAllOf(resolvedSchema) : mergeAllOf(resolvedSchema, {
            deep: false
          });
          if (withContainsSchemas.length) {
            resolvedSchema.allOf = withContainsSchemas;
          }
        } catch (e) {
          console.warn("could not merge subschemas in allOf:\n", e);
          const { allOf, ...resolvedSchemaWithoutAllOf } = resolvedSchema;
          return resolvedSchemaWithoutAllOf;
        }
      }
      const hasAdditionalProperties = ADDITIONAL_PROPERTIES_KEY in resolvedSchema && resolvedSchema.additionalProperties !== false;
      if (hasAdditionalProperties) {
        return stubExistingAdditionalProperties(
          validator,
          resolvedSchema,
          rootSchema,
          rawFormData,
          experimental_customMergeAllOf
        );
      }
      return resolvedSchema;
    });
  }
  function resolveAnyOrOneOfSchemas(validator, schema, rootSchema, expandAllBranches, rawFormData) {
    let anyOrOneOf;
    const { oneOf, anyOf, ...remaining } = schema;
    if (Array.isArray(oneOf)) {
      anyOrOneOf = oneOf;
    } else if (Array.isArray(anyOf)) {
      anyOrOneOf = anyOf;
    }
    if (anyOrOneOf) {
      const formData = rawFormData === void 0 && expandAllBranches ? {} : rawFormData;
      const discriminator = getDiscriminatorFieldFromSchema(schema);
      anyOrOneOf = anyOrOneOf.map((s) => {
        return resolveAllReferences(s, rootSchema, []);
      });
      const option = getFirstMatchingOption(validator, formData, anyOrOneOf, rootSchema, discriminator);
      if (expandAllBranches) {
        return anyOrOneOf.map((item) => mergeSchemas(remaining, item));
      }
      schema = mergeSchemas(remaining, anyOrOneOf[option]);
    }
    return [schema];
  }
  function resolveDependencies(validator, schema, rootSchema, expandAllBranches, recurseList, formData, experimental_customMergeAllOf) {
    const { dependencies, ...remainingSchema } = schema;
    const resolvedSchemas = resolveAnyOrOneOfSchemas(
      validator,
      remainingSchema,
      rootSchema,
      expandAllBranches,
      formData
    );
    return resolvedSchemas.flatMap(
      (resolvedSchema) => processDependencies(
        validator,
        dependencies,
        resolvedSchema,
        rootSchema,
        expandAllBranches,
        recurseList,
        formData,
        experimental_customMergeAllOf
      )
    );
  }
  function processDependencies(validator, dependencies, resolvedSchema, rootSchema, expandAllBranches, recurseList, formData, experimental_customMergeAllOf) {
    let schemas = [resolvedSchema];
    for (const dependencyKey in dependencies) {
      if (!expandAllBranches && get8(formData, [dependencyKey]) === void 0) {
        continue;
      }
      if (resolvedSchema.properties && !(dependencyKey in resolvedSchema.properties)) {
        continue;
      }
      const [remainingDependencies, dependencyValue] = splitKeyElementFromObject(
        dependencyKey,
        dependencies
      );
      if (Array.isArray(dependencyValue)) {
        schemas[0] = withDependentProperties(resolvedSchema, dependencyValue);
      } else if (isObject(dependencyValue)) {
        schemas = withDependentSchema(
          validator,
          resolvedSchema,
          rootSchema,
          dependencyKey,
          dependencyValue,
          expandAllBranches,
          recurseList,
          formData,
          experimental_customMergeAllOf
        );
      }
      return schemas.flatMap(
        (schema) => processDependencies(
          validator,
          remainingDependencies,
          schema,
          rootSchema,
          expandAllBranches,
          recurseList,
          formData,
          experimental_customMergeAllOf
        )
      );
    }
    return schemas;
  }
  function withDependentProperties(schema, additionallyRequired) {
    if (!additionallyRequired) {
      return schema;
    }
    const required = Array.isArray(schema.required) ? Array.from(/* @__PURE__ */ new Set([...schema.required, ...additionallyRequired])) : additionallyRequired;
    return { ...schema, required };
  }
  function withDependentSchema(validator, schema, rootSchema, dependencyKey, dependencyValue, expandAllBranches, recurseList, formData, experimental_customMergeAllOf) {
    const dependentSchemas = retrieveSchemaInternal(
      validator,
      dependencyValue,
      rootSchema,
      formData,
      expandAllBranches,
      recurseList,
      experimental_customMergeAllOf
    );
    return dependentSchemas.flatMap((dependent) => {
      const { oneOf, ...dependentSchema } = dependent;
      schema = mergeSchemas(schema, dependentSchema);
      if (oneOf === void 0) {
        return schema;
      }
      const resolvedOneOfs = oneOf.map((subschema) => {
        if (typeof subschema === "boolean" || !(REF_KEY in subschema)) {
          return [subschema];
        }
        return resolveReference(validator, subschema, rootSchema, expandAllBranches, recurseList, formData);
      });
      const allPermutations = getAllPermutationsOfXxxOf(resolvedOneOfs);
      return allPermutations.flatMap(
        (resolvedOneOf) => withExactlyOneSubschema(
          validator,
          schema,
          rootSchema,
          dependencyKey,
          resolvedOneOf,
          expandAllBranches,
          recurseList,
          formData,
          experimental_customMergeAllOf
        )
      );
    });
  }
  function withExactlyOneSubschema(validator, schema, rootSchema, dependencyKey, oneOf, expandAllBranches, recurseList, formData, experimental_customMergeAllOf) {
    const validSubschemas = oneOf.filter((subschema) => {
      if (typeof subschema === "boolean" || !subschema || !subschema.properties) {
        return false;
      }
      const { [dependencyKey]: conditionPropertySchema } = subschema.properties;
      if (conditionPropertySchema) {
        const conditionSchema = {
          type: "object",
          properties: {
            [dependencyKey]: conditionPropertySchema
          }
        };
        return validator.isValid(conditionSchema, formData, rootSchema) || expandAllBranches;
      }
      return false;
    });
    if (!expandAllBranches && validSubschemas.length !== 1) {
      console.warn("ignoring oneOf in dependencies because there isn't exactly one subschema that is valid");
      return [schema];
    }
    return validSubschemas.flatMap((s) => {
      const subschema = s;
      const [dependentSubschema] = splitKeyElementFromObject(dependencyKey, subschema.properties);
      const dependentSchema = { ...subschema, properties: dependentSubschema };
      const schemas = retrieveSchemaInternal(
        validator,
        dependentSchema,
        rootSchema,
        formData,
        expandAllBranches,
        recurseList,
        experimental_customMergeAllOf
      );
      return schemas.map((s2) => mergeSchemas(schema, s2));
    });
  }

  // src/schema/getClosestMatchingOption.ts
  var JUNK_OPTION = {
    type: "object",
    $id: JUNK_OPTION_ID,
    properties: {
      __not_really_there__: {
        type: "number"
      }
    }
  };
  function calculateIndexScore(validator, rootSchema, schema, formData, experimental_customMergeAllOf) {
    let totalScore = 0;
    if (schema) {
      if (isObject2(schema.properties)) {
        totalScore += reduce(
          schema.properties,
          (score, value, key) => {
            const formValue = get8(formData, key);
            if (typeof value === "boolean") {
              return score;
            }
            if (has3(value, REF_KEY)) {
              const newSchema = retrieveSchema(
                validator,
                value,
                rootSchema,
                formValue,
                experimental_customMergeAllOf
              );
              return score + calculateIndexScore(
                validator,
                rootSchema,
                newSchema,
                formValue || {},
                experimental_customMergeAllOf
              );
            }
            if ((has3(value, ONE_OF_KEY) || has3(value, ANY_OF_KEY)) && formValue) {
              const key2 = has3(value, ONE_OF_KEY) ? ONE_OF_KEY : ANY_OF_KEY;
              const discriminator = getDiscriminatorFieldFromSchema(value);
              return score + getClosestMatchingOption(
                validator,
                rootSchema,
                formValue,
                get8(value, key2),
                -1,
                discriminator,
                experimental_customMergeAllOf
              );
            }
            if (value.type === "object") {
              if (isObject2(formValue)) {
                score += 1;
              }
              return score + calculateIndexScore(validator, rootSchema, value, formValue, experimental_customMergeAllOf);
            }
            if (value.type === guessType(formValue)) {
              let newScore = score + 1;
              if (value.default) {
                newScore += formValue === value.default ? 1 : -1;
              } else if (value.const) {
                newScore += formValue === value.const ? 1 : -1;
              }
              return newScore;
            }
            return score;
          },
          0
        );
      } else if (isString(schema.type) && schema.type === guessType(formData)) {
        totalScore += 1;
      }
    }
    return totalScore;
  }
  function getClosestMatchingOption(validator, rootSchema, formData, options, selectedOption = -1, discriminatorField, experimental_customMergeAllOf) {
    const resolvedOptions = options.map((option) => {
      return resolveAllReferences(option, rootSchema, []);
    });
    const simpleDiscriminatorMatch = getOptionMatchingSimpleDiscriminator(formData, options, discriminatorField);
    if (isNumber(simpleDiscriminatorMatch)) {
      return simpleDiscriminatorMatch;
    }
    const allValidIndexes = resolvedOptions.reduce((validList, option, index) => {
      const testOptions = [JUNK_OPTION, option];
      const match = getFirstMatchingOption(validator, formData, testOptions, rootSchema, discriminatorField);
      if (match === 1) {
        validList.push(index);
      }
      return validList;
    }, []);
    if (allValidIndexes.length === 1) {
      return allValidIndexes[0];
    }
    if (!allValidIndexes.length) {
      times(resolvedOptions.length, (i) => allValidIndexes.push(i));
    }
    const scoreCount = /* @__PURE__ */ new Set();
    const { bestIndex } = allValidIndexes.reduce(
      (scoreData, index) => {
        const { bestScore } = scoreData;
        const option = resolvedOptions[index];
        const score = calculateIndexScore(validator, rootSchema, option, formData, experimental_customMergeAllOf);
        scoreCount.add(score);
        if (score > bestScore) {
          return { bestIndex: index, bestScore: score };
        }
        return scoreData;
      },
      { bestIndex: selectedOption, bestScore: 0 }
    );
    if (scoreCount.size === 1 && selectedOption >= 0) {
      return selectedOption;
    }
    return bestIndex;
  }

  // src/isFixedItems.ts
  function isFixedItems(schema) {
    return Array.isArray(schema.items) && schema.items.length > 0 && schema.items.every((item) => isObject(item));
  }
  function mergeDefaultsWithFormData(defaults, formData, mergeExtraArrayDefaults = false, defaultSupercedesUndefined = false, overrideFormDataWithDefaults = false) {
    if (Array.isArray(formData)) {
      const defaultsArray = Array.isArray(defaults) ? defaults : [];
      const overrideArray = overrideFormDataWithDefaults ? defaultsArray : formData;
      const overrideOppositeArray = overrideFormDataWithDefaults ? formData : defaultsArray;
      const mapped = overrideArray.map((value, idx) => {
        if (overrideOppositeArray[idx]) {
          return mergeDefaultsWithFormData(
            defaultsArray[idx],
            formData[idx],
            mergeExtraArrayDefaults,
            defaultSupercedesUndefined,
            overrideFormDataWithDefaults
          );
        }
        return value;
      });
      if ((mergeExtraArrayDefaults || overrideFormDataWithDefaults) && mapped.length < overrideOppositeArray.length) {
        mapped.push(...overrideOppositeArray.slice(mapped.length));
      }
      return mapped;
    }
    if (isObject(formData)) {
      const acc = Object.assign({}, defaults);
      return Object.keys(formData).reduce((acc2, key) => {
        const keyValue = get8(formData, key);
        const keyExistsInDefaults = isObject(defaults) && key in defaults;
        const keyExistsInFormData = key in formData;
        acc2[key] = mergeDefaultsWithFormData(
          defaults ? get8(defaults, key) : {},
          keyValue,
          mergeExtraArrayDefaults,
          defaultSupercedesUndefined,
          // overrideFormDataWithDefaults can be true only when the key value exists in defaults
          // Or if the key value doesn't exist in formData
          overrideFormDataWithDefaults && (keyExistsInDefaults || !keyExistsInFormData)
        );
        return acc2;
      }, acc);
    }
    if (defaultSupercedesUndefined && (!isNil(defaults) && isNil(formData) || typeof formData === "number" && isNaN(formData)) || overrideFormDataWithDefaults && !isNil(formData)) {
      return defaults;
    }
    return formData;
  }

  // src/mergeObjects.ts
  function mergeObjects(obj1, obj2, concatArrays = false) {
    return Object.keys(obj2).reduce((acc, key) => {
      const left = obj1 ? obj1[key] : {}, right = obj2[key];
      if (obj1 && key in obj1 && isObject(right)) {
        acc[key] = mergeObjects(left, right, concatArrays);
      } else if (concatArrays && Array.isArray(left) && Array.isArray(right)) {
        let toMerge = right;
        if (concatArrays === "preventDuplicates") {
          toMerge = right.reduce((result, value) => {
            if (!left.includes(value)) {
              result.push(value);
            }
            return result;
          }, []);
        }
        acc[key] = left.concat(toMerge);
      } else {
        acc[key] = right;
      }
      return acc;
    }, Object.assign({}, obj1));
  }

  // src/isConstant.ts
  function isConstant(schema) {
    return Array.isArray(schema.enum) && schema.enum.length === 1 || CONST_KEY in schema;
  }

  // src/schema/isSelect.ts
  function isSelect(validator, theSchema, rootSchema = {}, experimental_customMergeAllOf) {
    const schema = retrieveSchema(validator, theSchema, rootSchema, void 0, experimental_customMergeAllOf);
    const altSchemas = schema.oneOf || schema.anyOf;
    if (Array.isArray(schema.enum)) {
      return true;
    }
    if (Array.isArray(altSchemas)) {
      return altSchemas.every((altSchemas2) => typeof altSchemas2 !== "boolean" && isConstant(altSchemas2));
    }
    return false;
  }

  // src/schema/isMultiSelect.ts
  function isMultiSelect(validator, schema, rootSchema, experimental_customMergeAllOf) {
    if (!schema.uniqueItems || !schema.items || typeof schema.items === "boolean") {
      return false;
    }
    return isSelect(validator, schema.items, rootSchema, experimental_customMergeAllOf);
  }
  function constIsAjvDataReference(schema) {
    const schemaConst = schema[CONST_KEY];
    const schemaType = getSchemaType(schema);
    return isObject(schemaConst) && isString(schemaConst?.$data) && schemaType !== "object" && schemaType !== "array";
  }

  // src/toConstant.ts
  function toConstant(schema) {
    if (ENUM_KEY in schema && Array.isArray(schema.enum) && schema.enum.length === 1) {
      return schema.enum[0];
    }
    if (CONST_KEY in schema) {
      return schema.const;
    }
    throw new Error("schema cannot be inferred as a constant");
  }

  // src/optionsList.ts
  function optionsList(schema, uiSchema) {
    const schemaWithEnumNames = schema;
    if (schema.enum) {
      let enumNames;
      if (uiSchema) {
        const { enumNames: uiEnumNames } = getUiOptions(uiSchema);
        enumNames = uiEnumNames;
      }
      if (!enumNames && schemaWithEnumNames.enumNames) {
        {
          console.warn(
            'The "enumNames" property in the schema is deprecated and will be removed in a future major release. Use the "ui:enumNames" property in the uiSchema instead.'
          );
        }
        enumNames = schemaWithEnumNames.enumNames;
      }
      return schema.enum.map((value, i) => {
        const label = enumNames?.[i] || String(value);
        return { label, value };
      });
    }
    let altSchemas = void 0;
    let altUiSchemas = void 0;
    if (schema.anyOf) {
      altSchemas = schema.anyOf;
      altUiSchemas = uiSchema?.anyOf;
    } else if (schema.oneOf) {
      altSchemas = schema.oneOf;
      altUiSchemas = uiSchema?.oneOf;
    }
    return altSchemas && altSchemas.map((aSchemaDef, index) => {
      const { title } = getUiOptions(altUiSchemas?.[index]);
      const aSchema = aSchemaDef;
      const value = toConstant(aSchema);
      const label = title || aSchema.title || String(value);
      return {
        schema: aSchema,
        label,
        value
      };
    });
  }

  // src/schema/getDefaultFormState.ts
  var PRIMITIVE_TYPES = ["string", "number", "integer", "boolean", "null"];
  function getInnerSchemaForArrayItem(schema, additionalItems = 0 /* Ignore */, idx = -1) {
    if (idx >= 0) {
      if (Array.isArray(schema.items) && idx < schema.items.length) {
        const item = schema.items[idx];
        if (typeof item !== "boolean") {
          return item;
        }
      }
    } else if (schema.items && !Array.isArray(schema.items) && typeof schema.items !== "boolean") {
      return schema.items;
    }
    if (additionalItems !== 0 /* Ignore */ && isObject(schema.additionalItems)) {
      return schema.additionalItems;
    }
    return {};
  }
  function maybeAddDefaultToObject(obj, key, computedDefault, includeUndefinedValues, isParentRequired, requiredFields = [], experimental_defaultFormStateBehavior = {}, isConst = false) {
    const { emptyObjectFields = "populateAllDefaults" } = experimental_defaultFormStateBehavior;
    if (includeUndefinedValues || isConst) {
      obj[key] = computedDefault;
    } else if (emptyObjectFields !== "skipDefaults") {
      const isSelfOrParentRequired = isParentRequired === void 0 ? requiredFields.includes(key) : isParentRequired;
      if (isObject(computedDefault)) {
        if (emptyObjectFields === "skipEmptyDefaults") {
          if (!isEmpty(computedDefault)) {
            obj[key] = computedDefault;
          }
        } else if ((!isEmpty(computedDefault) || requiredFields.includes(key)) && (isSelfOrParentRequired || emptyObjectFields !== "populateRequiredDefaults")) {
          obj[key] = computedDefault;
        }
      } else if (
        // Store computedDefault if it's a defined primitive (e.g., true) and satisfies certain conditions
        // Condition 1: computedDefault is not undefined
        // Condition 2: If emptyObjectFields is 'populateAllDefaults' or 'skipEmptyDefaults)
        // Or if isSelfOrParentRequired is 'true' and the key is a required field
        computedDefault !== void 0 && (emptyObjectFields === "populateAllDefaults" || emptyObjectFields === "skipEmptyDefaults" || isSelfOrParentRequired && requiredFields.includes(key))
      ) {
        obj[key] = computedDefault;
      }
    }
  }
  function computeDefaults(validator, rawSchema, computeDefaultsProps = {}) {
    const {
      parentDefaults,
      rawFormData,
      rootSchema = {},
      includeUndefinedValues = false,
      _recurseList = [],
      experimental_defaultFormStateBehavior = void 0,
      experimental_customMergeAllOf = void 0,
      required,
      shouldMergeDefaultsIntoFormData = false
    } = computeDefaultsProps;
    const formData = isObject(rawFormData) ? rawFormData : {};
    const schema = isObject(rawSchema) ? rawSchema : {};
    let defaults = parentDefaults;
    let schemaToCompute = null;
    let experimental_dfsb_to_compute = experimental_defaultFormStateBehavior;
    let updatedRecurseList = _recurseList;
    if (schema[CONST_KEY] && experimental_defaultFormStateBehavior?.constAsDefaults !== "never" && !constIsAjvDataReference(schema)) {
      defaults = schema[CONST_KEY];
    } else if (isObject(defaults) && isObject(schema.default)) {
      defaults = mergeObjects(defaults, schema.default);
    } else if (DEFAULT_KEY in schema) {
      defaults = schema.default;
    } else if (REF_KEY in schema) {
      const refName = schema[REF_KEY];
      if (!_recurseList.includes(refName)) {
        updatedRecurseList = _recurseList.concat(refName);
        schemaToCompute = findSchemaDefinition(refName, rootSchema);
      }
    } else if (DEPENDENCIES_KEY in schema) {
      const defaultFormData = {
        ...getDefaultBasedOnSchemaType(validator, schema, computeDefaultsProps, defaults),
        ...formData
      };
      const resolvedSchema = resolveDependencies(
        validator,
        schema,
        rootSchema,
        false,
        [],
        defaultFormData,
        experimental_customMergeAllOf
      );
      schemaToCompute = resolvedSchema[0];
    } else if (isFixedItems(schema)) {
      defaults = schema.items.map(
        (itemSchema, idx) => computeDefaults(validator, itemSchema, {
          rootSchema,
          includeUndefinedValues,
          _recurseList,
          experimental_defaultFormStateBehavior,
          experimental_customMergeAllOf,
          parentDefaults: Array.isArray(parentDefaults) ? parentDefaults[idx] : void 0,
          rawFormData: formData,
          required,
          shouldMergeDefaultsIntoFormData
        })
      );
    } else if (ONE_OF_KEY in schema) {
      const { oneOf, ...remaining } = schema;
      if (oneOf.length === 0) {
        return void 0;
      }
      const discriminator = getDiscriminatorFieldFromSchema(schema);
      const { type = "null" } = remaining;
      if (!Array.isArray(type) && PRIMITIVE_TYPES.includes(type) && experimental_dfsb_to_compute?.constAsDefaults === "skipOneOf") {
        experimental_dfsb_to_compute = {
          ...experimental_dfsb_to_compute,
          constAsDefaults: "never"
        };
      }
      schemaToCompute = oneOf[getClosestMatchingOption(
        validator,
        rootSchema,
        rawFormData,
        oneOf,
        0,
        discriminator,
        experimental_customMergeAllOf
      )];
      schemaToCompute = mergeSchemas(remaining, schemaToCompute);
    } else if (ANY_OF_KEY in schema) {
      const { anyOf, ...remaining } = schema;
      if (anyOf.length === 0) {
        return void 0;
      }
      const discriminator = getDiscriminatorFieldFromSchema(schema);
      schemaToCompute = anyOf[getClosestMatchingOption(
        validator,
        rootSchema,
        rawFormData,
        anyOf,
        0,
        discriminator,
        experimental_customMergeAllOf
      )];
      schemaToCompute = mergeSchemas(remaining, schemaToCompute);
    }
    if (schemaToCompute) {
      return computeDefaults(validator, schemaToCompute, {
        rootSchema,
        includeUndefinedValues,
        _recurseList: updatedRecurseList,
        experimental_defaultFormStateBehavior: experimental_dfsb_to_compute,
        experimental_customMergeAllOf,
        parentDefaults: defaults,
        rawFormData: formData,
        required,
        shouldMergeDefaultsIntoFormData
      });
    }
    if (defaults === void 0) {
      defaults = schema.default;
    }
    const defaultBasedOnSchemaType = getDefaultBasedOnSchemaType(validator, schema, computeDefaultsProps, defaults);
    let defaultsWithFormData = defaultBasedOnSchemaType ?? defaults;
    if (shouldMergeDefaultsIntoFormData) {
      const { arrayMinItems = {} } = experimental_defaultFormStateBehavior || {};
      const { mergeExtraDefaults } = arrayMinItems;
      const matchingFormData = ensureFormDataMatchingSchema(
        validator,
        schema,
        rootSchema,
        rawFormData,
        experimental_defaultFormStateBehavior
      );
      if (!isObject(rawFormData)) {
        defaultsWithFormData = mergeDefaultsWithFormData(
          defaultsWithFormData,
          matchingFormData,
          mergeExtraDefaults,
          true
        );
      }
    }
    return defaultsWithFormData;
  }
  function ensureFormDataMatchingSchema(validator, schema, rootSchema, formData, experimental_defaultFormStateBehavior) {
    const isSelectField = !isConstant(schema) && isSelect(validator, schema, rootSchema);
    let validFormData = formData;
    if (isSelectField) {
      const getOptionsList = optionsList(schema);
      const isValid = getOptionsList?.some((option) => deepEquals(option.value, formData));
      validFormData = isValid ? formData : void 0;
    }
    const constTakesPrecedence = schema[CONST_KEY] && experimental_defaultFormStateBehavior?.constAsDefaults === "always";
    if (constTakesPrecedence) {
      validFormData = schema.const;
    }
    return validFormData;
  }
  function getObjectDefaults(validator, rawSchema, {
    rawFormData,
    rootSchema = {},
    includeUndefinedValues = false,
    _recurseList = [],
    experimental_defaultFormStateBehavior = void 0,
    experimental_customMergeAllOf = void 0,
    required,
    shouldMergeDefaultsIntoFormData
  } = {}, defaults) {
    {
      const formData = isObject(rawFormData) ? rawFormData : {};
      const schema = rawSchema;
      const retrievedSchema = experimental_defaultFormStateBehavior?.allOf === "populateDefaults" && ALL_OF_KEY in schema ? retrieveSchema(validator, schema, rootSchema, formData, experimental_customMergeAllOf) : schema;
      const parentConst = retrievedSchema[CONST_KEY];
      const objectDefaults = Object.keys(retrievedSchema.properties || {}).reduce(
        (acc, key) => {
          const propertySchema = get8(retrievedSchema, [PROPERTIES_KEY, key]);
          const hasParentConst = isObject(parentConst) && parentConst[key] !== void 0;
          const hasConst = (isObject(propertySchema) && CONST_KEY in propertySchema || hasParentConst) && experimental_defaultFormStateBehavior?.constAsDefaults !== "never" && !constIsAjvDataReference(propertySchema);
          const computedDefault = computeDefaults(validator, propertySchema, {
            rootSchema,
            _recurseList,
            experimental_defaultFormStateBehavior,
            experimental_customMergeAllOf,
            includeUndefinedValues: includeUndefinedValues === true,
            parentDefaults: get8(defaults, [key]),
            rawFormData: get8(formData, [key]),
            required: retrievedSchema.required?.includes(key),
            shouldMergeDefaultsIntoFormData
          });
          maybeAddDefaultToObject(
            acc,
            key,
            computedDefault,
            includeUndefinedValues,
            required,
            retrievedSchema.required,
            experimental_defaultFormStateBehavior,
            hasConst
          );
          return acc;
        },
        {}
      );
      if (retrievedSchema.additionalProperties) {
        const additionalPropertiesSchema = isObject(retrievedSchema.additionalProperties) ? retrievedSchema.additionalProperties : {};
        const keys2 = /* @__PURE__ */ new Set();
        if (isObject(defaults)) {
          Object.keys(defaults).filter((key) => !retrievedSchema.properties || !retrievedSchema.properties[key]).forEach((key) => keys2.add(key));
        }
        const formDataRequired = [];
        Object.keys(formData).filter((key) => !retrievedSchema.properties || !retrievedSchema.properties[key]).forEach((key) => {
          keys2.add(key);
          formDataRequired.push(key);
        });
        keys2.forEach((key) => {
          const computedDefault = computeDefaults(validator, additionalPropertiesSchema, {
            rootSchema,
            _recurseList,
            experimental_defaultFormStateBehavior,
            experimental_customMergeAllOf,
            includeUndefinedValues: includeUndefinedValues === true,
            parentDefaults: get8(defaults, [key]),
            rawFormData: get8(formData, [key]),
            required: retrievedSchema.required?.includes(key),
            shouldMergeDefaultsIntoFormData
          });
          maybeAddDefaultToObject(
            objectDefaults,
            key,
            computedDefault,
            includeUndefinedValues,
            required,
            formDataRequired
          );
        });
      }
      return objectDefaults;
    }
  }
  function getArrayDefaults(validator, rawSchema, {
    rawFormData,
    rootSchema = {},
    _recurseList = [],
    experimental_defaultFormStateBehavior = void 0,
    experimental_customMergeAllOf = void 0,
    required,
    shouldMergeDefaultsIntoFormData
  } = {}, defaults) {
    const schema = rawSchema;
    const arrayMinItemsStateBehavior = experimental_defaultFormStateBehavior?.arrayMinItems ?? {};
    const { populate: arrayMinItemsPopulate, mergeExtraDefaults: arrayMergeExtraDefaults } = arrayMinItemsStateBehavior;
    const neverPopulate = arrayMinItemsPopulate === "never";
    const ignoreMinItemsFlagSet = arrayMinItemsPopulate === "requiredOnly";
    const isPopulateAll = arrayMinItemsPopulate === "all" || !neverPopulate && !ignoreMinItemsFlagSet;
    const computeSkipPopulate = arrayMinItemsStateBehavior?.computeSkipPopulate ?? (() => false);
    const isSkipEmptyDefaults = experimental_defaultFormStateBehavior?.emptyObjectFields === "skipEmptyDefaults";
    const emptyDefault = isSkipEmptyDefaults ? void 0 : [];
    if (Array.isArray(defaults)) {
      defaults = defaults.map((item, idx) => {
        const schemaItem = getInnerSchemaForArrayItem(schema, 2 /* Fallback */, idx);
        return computeDefaults(validator, schemaItem, {
          rootSchema,
          _recurseList,
          experimental_defaultFormStateBehavior,
          experimental_customMergeAllOf,
          parentDefaults: item,
          required,
          shouldMergeDefaultsIntoFormData
        });
      });
    }
    if (Array.isArray(rawFormData)) {
      const schemaItem = getInnerSchemaForArrayItem(schema);
      if (neverPopulate) {
        defaults = rawFormData;
      } else {
        const itemDefaults = rawFormData.map((item, idx) => {
          return computeDefaults(validator, schemaItem, {
            rootSchema,
            _recurseList,
            experimental_defaultFormStateBehavior,
            experimental_customMergeAllOf,
            rawFormData: item,
            parentDefaults: get8(defaults, [idx]),
            required,
            shouldMergeDefaultsIntoFormData
          });
        });
        const mergeExtraDefaults = (ignoreMinItemsFlagSet && required || isPopulateAll) && arrayMergeExtraDefaults;
        defaults = mergeDefaultsWithFormData(defaults, itemDefaults, mergeExtraDefaults);
      }
    }
    const hasConst = isObject(schema) && CONST_KEY in schema && experimental_defaultFormStateBehavior?.constAsDefaults !== "never";
    if (hasConst === false) {
      if (neverPopulate) {
        return defaults ?? emptyDefault;
      }
      if (ignoreMinItemsFlagSet && !required) {
        return defaults ? defaults : void 0;
      }
    }
    const defaultsLength = Array.isArray(defaults) ? defaults.length : 0;
    if (!schema.minItems || isMultiSelect(validator, schema, rootSchema, experimental_customMergeAllOf) || computeSkipPopulate(validator, schema, rootSchema) || schema.minItems <= defaultsLength) {
      return defaults ? defaults : emptyDefault;
    }
    const defaultEntries = defaults || [];
    const fillerSchema = getInnerSchemaForArrayItem(schema, 1 /* Invert */);
    const fillerDefault = fillerSchema.default;
    const fillerEntries = new Array(schema.minItems - defaultsLength).fill(
      computeDefaults(validator, fillerSchema, {
        parentDefaults: fillerDefault,
        rootSchema,
        _recurseList,
        experimental_defaultFormStateBehavior,
        experimental_customMergeAllOf,
        required,
        shouldMergeDefaultsIntoFormData
      })
    );
    return defaultEntries.concat(fillerEntries);
  }
  function getDefaultBasedOnSchemaType(validator, rawSchema, computeDefaultsProps = {}, defaults) {
    switch (getSchemaType(rawSchema)) {
      case "object": {
        return getObjectDefaults(validator, rawSchema, computeDefaultsProps, defaults);
      }
      case "array": {
        return getArrayDefaults(validator, rawSchema, computeDefaultsProps, defaults);
      }
    }
  }
  function getDefaultFormState(validator, theSchema, formData, rootSchema, includeUndefinedValues = false, experimental_defaultFormStateBehavior, experimental_customMergeAllOf) {
    if (!isObject(theSchema)) {
      throw new Error("Invalid schema: " + theSchema);
    }
    const schema = retrieveSchema(validator, theSchema, rootSchema, formData, experimental_customMergeAllOf);
    const defaults = computeDefaults(validator, schema, {
      rootSchema,
      includeUndefinedValues,
      experimental_defaultFormStateBehavior,
      experimental_customMergeAllOf,
      rawFormData: formData,
      shouldMergeDefaultsIntoFormData: true
    });
    if (isObject(formData) || Array.isArray(formData)) {
      const { mergeDefaultsIntoFormData } = experimental_defaultFormStateBehavior || {};
      const defaultSupercedesUndefined = mergeDefaultsIntoFormData === "useDefaultIfFormDataUndefined";
      const result = mergeDefaultsWithFormData(
        defaults,
        formData,
        true,
        // set to true to add any additional default array entries.
        defaultSupercedesUndefined,
        true
        // set to true to override formData with defaults if they exist.
      );
      return result;
    }
    return defaults;
  }

  // src/isCustomWidget.ts
  function isCustomWidget(uiSchema = {}) {
    return (
      // TODO: Remove the `&& uiSchema['ui:widget'] !== 'hidden'` once we support hidden widgets for arrays.
      // https://rjsf-team.github.io/react-jsonschema-form/docs/usage/widgets/#hidden-widgets
      "widget" in getUiOptions(uiSchema) && getUiOptions(uiSchema)["widget"] !== "hidden"
    );
  }

  // src/schema/isFilesArray.ts
  function isFilesArray(validator, schema, uiSchema = {}, rootSchema, experimental_customMergeAllOf) {
    if (uiSchema[UI_WIDGET_KEY] === "files") {
      return true;
    }
    if (schema.items) {
      const itemsSchema = retrieveSchema(
        validator,
        schema.items,
        rootSchema,
        void 0,
        experimental_customMergeAllOf
      );
      return itemsSchema.type === "string" && itemsSchema.format === "data-url";
    }
    return false;
  }

  // src/schema/getDisplayLabel.ts
  function getDisplayLabel(validator, schema, uiSchema = {}, rootSchema, globalOptions, experimental_customMergeAllOf) {
    const uiOptions = getUiOptions(uiSchema, globalOptions);
    const { label = true } = uiOptions;
    let displayLabel = !!label;
    const schemaType = getSchemaType(schema);
    if (schemaType === "array") {
      displayLabel = isMultiSelect(validator, schema, rootSchema, experimental_customMergeAllOf) || isFilesArray(validator, schema, uiSchema, rootSchema, experimental_customMergeAllOf) || isCustomWidget(uiSchema);
    }
    if (schemaType === "object") {
      displayLabel = false;
    }
    if (schemaType === "boolean" && !uiSchema[UI_WIDGET_KEY]) {
      displayLabel = false;
    }
    if (uiSchema[UI_FIELD_KEY]) {
      displayLabel = false;
    }
    return displayLabel;
  }
  function mergeValidationData(validator, validationData, additionalErrorSchema) {
    if (!additionalErrorSchema) {
      return validationData;
    }
    const { errors: oldErrors, errorSchema: oldErrorSchema } = validationData;
    let errors = validator.toErrorList(additionalErrorSchema);
    let errorSchema = additionalErrorSchema;
    if (!isEmpty(oldErrorSchema)) {
      errorSchema = mergeObjects(oldErrorSchema, additionalErrorSchema, true);
      errors = [...oldErrors].concat(errors);
    }
    return { errorSchema, errors };
  }
  var NO_VALUE = Symbol("no Value");
  function sanitizeDataForNewSchema(validator, rootSchema, newSchema, oldSchema, data = {}, experimental_customMergeAllOf) {
    let newFormData;
    if (has3(newSchema, PROPERTIES_KEY)) {
      const removeOldSchemaData = {};
      if (has3(oldSchema, PROPERTIES_KEY)) {
        const properties = get8(oldSchema, PROPERTIES_KEY, {});
        Object.keys(properties).forEach((key) => {
          if (has3(data, key)) {
            removeOldSchemaData[key] = void 0;
          }
        });
      }
      const keys2 = Object.keys(get8(newSchema, PROPERTIES_KEY, {}));
      const nestedData = {};
      keys2.forEach((key) => {
        const formValue = get8(data, key);
        let oldKeyedSchema = get8(oldSchema, [PROPERTIES_KEY, key], {});
        let newKeyedSchema = get8(newSchema, [PROPERTIES_KEY, key], {});
        if (has3(oldKeyedSchema, REF_KEY)) {
          oldKeyedSchema = retrieveSchema(
            validator,
            oldKeyedSchema,
            rootSchema,
            formValue,
            experimental_customMergeAllOf
          );
        }
        if (has3(newKeyedSchema, REF_KEY)) {
          newKeyedSchema = retrieveSchema(
            validator,
            newKeyedSchema,
            rootSchema,
            formValue,
            experimental_customMergeAllOf
          );
        }
        const oldSchemaTypeForKey = get8(oldKeyedSchema, "type");
        const newSchemaTypeForKey = get8(newKeyedSchema, "type");
        if (!oldSchemaTypeForKey || oldSchemaTypeForKey === newSchemaTypeForKey) {
          if (has3(removeOldSchemaData, key)) {
            delete removeOldSchemaData[key];
          }
          if (newSchemaTypeForKey === "object" || newSchemaTypeForKey === "array" && Array.isArray(formValue)) {
            const itemData = sanitizeDataForNewSchema(
              validator,
              rootSchema,
              newKeyedSchema,
              oldKeyedSchema,
              formValue,
              experimental_customMergeAllOf
            );
            if (itemData !== void 0 || newSchemaTypeForKey === "array") {
              nestedData[key] = itemData;
            }
          } else {
            const newOptionDefault = get8(newKeyedSchema, "default", NO_VALUE);
            const oldOptionDefault = get8(oldKeyedSchema, "default", NO_VALUE);
            if (newOptionDefault !== NO_VALUE && newOptionDefault !== formValue) {
              if (oldOptionDefault === formValue) {
                removeOldSchemaData[key] = newOptionDefault;
              } else if (get8(newKeyedSchema, "readOnly") === true) {
                removeOldSchemaData[key] = void 0;
              }
            }
            const newOptionConst = get8(newKeyedSchema, "const", NO_VALUE);
            const oldOptionConst = get8(oldKeyedSchema, "const", NO_VALUE);
            if (newOptionConst !== NO_VALUE && newOptionConst !== formValue) {
              removeOldSchemaData[key] = oldOptionConst === formValue ? newOptionConst : void 0;
            }
          }
        }
      });
      newFormData = {
        ...typeof data == "string" || Array.isArray(data) ? void 0 : data,
        ...removeOldSchemaData,
        ...nestedData
      };
    } else if (get8(oldSchema, "type") === "array" && get8(newSchema, "type") === "array" && Array.isArray(data)) {
      let oldSchemaItems = get8(oldSchema, "items");
      let newSchemaItems = get8(newSchema, "items");
      if (typeof oldSchemaItems === "object" && typeof newSchemaItems === "object" && !Array.isArray(oldSchemaItems) && !Array.isArray(newSchemaItems)) {
        if (has3(oldSchemaItems, REF_KEY)) {
          oldSchemaItems = retrieveSchema(
            validator,
            oldSchemaItems,
            rootSchema,
            data,
            experimental_customMergeAllOf
          );
        }
        if (has3(newSchemaItems, REF_KEY)) {
          newSchemaItems = retrieveSchema(
            validator,
            newSchemaItems,
            rootSchema,
            data,
            experimental_customMergeAllOf
          );
        }
        const oldSchemaType = get8(oldSchemaItems, "type");
        const newSchemaType = get8(newSchemaItems, "type");
        if (!oldSchemaType || oldSchemaType === newSchemaType) {
          const maxItems = get8(newSchema, "maxItems", -1);
          if (newSchemaType === "object") {
            newFormData = data.reduce((newValue, aValue) => {
              const itemValue = sanitizeDataForNewSchema(
                validator,
                rootSchema,
                newSchemaItems,
                oldSchemaItems,
                aValue,
                experimental_customMergeAllOf
              );
              if (itemValue !== void 0 && (maxItems < 0 || newValue.length < maxItems)) {
                newValue.push(itemValue);
              }
              return newValue;
            }, []);
          } else {
            newFormData = maxItems > 0 && data.length > maxItems ? data.slice(0, maxItems) : data;
          }
        }
      } else if (typeof oldSchemaItems === "boolean" && typeof newSchemaItems === "boolean" && oldSchemaItems === newSchemaItems) {
        newFormData = data;
      }
    }
    return newFormData;
  }
  function toIdSchemaInternal(validator, schema, idPrefix, idSeparator, id, rootSchema, formData, _recurseList = [], experimental_customMergeAllOf) {
    if (REF_KEY in schema || DEPENDENCIES_KEY in schema || ALL_OF_KEY in schema) {
      const _schema = retrieveSchema(validator, schema, rootSchema, formData, experimental_customMergeAllOf);
      const sameSchemaIndex = _recurseList.findIndex((item) => deepEquals(item, _schema));
      if (sameSchemaIndex === -1) {
        return toIdSchemaInternal(
          validator,
          _schema,
          idPrefix,
          idSeparator,
          id,
          rootSchema,
          formData,
          _recurseList.concat(_schema),
          experimental_customMergeAllOf
        );
      }
    }
    if (ITEMS_KEY in schema && !get8(schema, [ITEMS_KEY, REF_KEY])) {
      return toIdSchemaInternal(
        validator,
        get8(schema, ITEMS_KEY),
        idPrefix,
        idSeparator,
        id,
        rootSchema,
        formData,
        _recurseList,
        experimental_customMergeAllOf
      );
    }
    const $id = id || idPrefix;
    const idSchema = { $id };
    if (getSchemaType(schema) === "object" && PROPERTIES_KEY in schema) {
      for (const name in schema.properties) {
        const field = get8(schema, [PROPERTIES_KEY, name]);
        const fieldId = idSchema[ID_KEY] + idSeparator + name;
        idSchema[name] = toIdSchemaInternal(
          validator,
          isObject(field) ? field : {},
          idPrefix,
          idSeparator,
          fieldId,
          rootSchema,
          // It's possible that formData is not an object -- this can happen if an
          // array item has just been added, but not populated with data yet
          get8(formData, [name]),
          _recurseList,
          experimental_customMergeAllOf
        );
      }
    }
    return idSchema;
  }
  function toIdSchema(validator, schema, id, rootSchema, formData, idPrefix = "root", idSeparator = "_", experimental_customMergeAllOf) {
    return toIdSchemaInternal(
      validator,
      schema,
      idPrefix,
      idSeparator,
      id,
      rootSchema,
      formData,
      void 0,
      experimental_customMergeAllOf
    );
  }
  function toPathSchemaInternal(validator, schema, name, rootSchema, formData, _recurseList = [], experimental_customMergeAllOf) {
    if (REF_KEY in schema || DEPENDENCIES_KEY in schema || ALL_OF_KEY in schema) {
      const _schema = retrieveSchema(validator, schema, rootSchema, formData, experimental_customMergeAllOf);
      const sameSchemaIndex = _recurseList.findIndex((item) => deepEquals(item, _schema));
      if (sameSchemaIndex === -1) {
        return toPathSchemaInternal(
          validator,
          _schema,
          name,
          rootSchema,
          formData,
          _recurseList.concat(_schema),
          experimental_customMergeAllOf
        );
      }
    }
    let pathSchema = {
      [NAME_KEY]: name.replace(/^\./, "")
    };
    if (ONE_OF_KEY in schema || ANY_OF_KEY in schema) {
      const xxxOf = ONE_OF_KEY in schema ? schema.oneOf : schema.anyOf;
      const discriminator = getDiscriminatorFieldFromSchema(schema);
      const index = getClosestMatchingOption(
        validator,
        rootSchema,
        formData,
        xxxOf,
        0,
        discriminator,
        experimental_customMergeAllOf
      );
      const _schema = xxxOf[index];
      pathSchema = {
        ...pathSchema,
        ...toPathSchemaInternal(
          validator,
          _schema,
          name,
          rootSchema,
          formData,
          _recurseList,
          experimental_customMergeAllOf
        )
      };
    }
    if (ADDITIONAL_PROPERTIES_KEY in schema && schema[ADDITIONAL_PROPERTIES_KEY] !== false) {
      set3(pathSchema, RJSF_ADDITIONAL_PROPERTIES_FLAG, true);
    }
    if (ITEMS_KEY in schema && Array.isArray(formData)) {
      const { items: schemaItems, additionalItems: schemaAdditionalItems } = schema;
      if (Array.isArray(schemaItems)) {
        formData.forEach((element, i) => {
          if (schemaItems[i]) {
            pathSchema[i] = toPathSchemaInternal(
              validator,
              schemaItems[i],
              `${name}.${i}`,
              rootSchema,
              element,
              _recurseList,
              experimental_customMergeAllOf
            );
          } else if (schemaAdditionalItems) {
            pathSchema[i] = toPathSchemaInternal(
              validator,
              schemaAdditionalItems,
              `${name}.${i}`,
              rootSchema,
              element,
              _recurseList,
              experimental_customMergeAllOf
            );
          } else {
            console.warn(`Unable to generate path schema for "${name}.${i}". No schema defined for it`);
          }
        });
      } else {
        formData.forEach((element, i) => {
          pathSchema[i] = toPathSchemaInternal(
            validator,
            schemaItems,
            `${name}.${i}`,
            rootSchema,
            element,
            _recurseList,
            experimental_customMergeAllOf
          );
        });
      }
    } else if (PROPERTIES_KEY in schema) {
      for (const property in schema.properties) {
        const field = get8(schema, [PROPERTIES_KEY, property]);
        pathSchema[property] = toPathSchemaInternal(
          validator,
          field,
          `${name}.${property}`,
          rootSchema,
          // It's possible that formData is not an object -- this can happen if an
          // array item has just been added, but not populated with data yet
          get8(formData, [property]),
          _recurseList,
          experimental_customMergeAllOf
        );
      }
    }
    return pathSchema;
  }
  function toPathSchema(validator, schema, name = "", rootSchema, formData, experimental_customMergeAllOf) {
    return toPathSchemaInternal(validator, schema, name, rootSchema, formData, void 0, experimental_customMergeAllOf);
  }

  // src/createSchemaUtils.ts
  var SchemaUtils = class {
    /** Constructs the `SchemaUtils` instance with the given `validator` and `rootSchema` stored as instance variables
     *
     * @param validator - An implementation of the `ValidatorType` interface that will be forwarded to all the APIs
     * @param rootSchema - The root schema that will be forwarded to all the APIs
     * @param experimental_defaultFormStateBehavior - Configuration flags to allow users to override default form state behavior
     * @param [experimental_customMergeAllOf] - Optional function that allows for custom merging of `allOf` schemas
     */
    constructor(validator, rootSchema, experimental_defaultFormStateBehavior, experimental_customMergeAllOf) {
      this.rootSchema = rootSchema;
      this.validator = validator;
      this.experimental_defaultFormStateBehavior = experimental_defaultFormStateBehavior;
      this.experimental_customMergeAllOf = experimental_customMergeAllOf;
    }
    /** Returns the `ValidatorType` in the `SchemaUtilsType`
     *
     * @returns - The `ValidatorType`
     */
    getValidator() {
      return this.validator;
    }
    /** Determines whether either the `validator` and `rootSchema` differ from the ones associated with this instance of
     * the `SchemaUtilsType`. If either `validator` or `rootSchema` are falsy, then return false to prevent the creation
     * of a new `SchemaUtilsType` with incomplete properties.
     *
     * @param validator - An implementation of the `ValidatorType` interface that will be compared against the current one
     * @param rootSchema - The root schema that will be compared against the current one
     * @param [experimental_defaultFormStateBehavior] Optional configuration object, if provided, allows users to override default form state behavior
     * @param [experimental_customMergeAllOf] - Optional function that allows for custom merging of `allOf` schemas
     * @returns - True if the `SchemaUtilsType` differs from the given `validator` or `rootSchema`
     */
    doesSchemaUtilsDiffer(validator, rootSchema, experimental_defaultFormStateBehavior = {}, experimental_customMergeAllOf) {
      if (!validator || !rootSchema) {
        return false;
      }
      return this.validator !== validator || !deepEquals(this.rootSchema, rootSchema) || !deepEquals(this.experimental_defaultFormStateBehavior, experimental_defaultFormStateBehavior) || this.experimental_customMergeAllOf !== experimental_customMergeAllOf;
    }
    /** Returns the superset of `formData` that includes the given set updated to include any missing fields that have
     * computed to have defaults provided in the `schema`.
     *
     * @param schema - The schema for which the default state is desired
     * @param [formData] - The current formData, if any, onto which to provide any missing defaults
     * @param [includeUndefinedValues=false] - Optional flag, if true, cause undefined values to be added as defaults.
     *          If "excludeObjectChildren", pass `includeUndefinedValues` as false when computing defaults for any nested
     *          object properties.
     * @returns - The resulting `formData` with all the defaults provided
     */
    getDefaultFormState(schema, formData, includeUndefinedValues = false) {
      return getDefaultFormState(
        this.validator,
        schema,
        formData,
        this.rootSchema,
        includeUndefinedValues,
        this.experimental_defaultFormStateBehavior,
        this.experimental_customMergeAllOf
      );
    }
    /** Determines whether the combination of `schema` and `uiSchema` properties indicates that the label for the `schema`
     * should be displayed in a UI.
     *
     * @param schema - The schema for which the display label flag is desired
     * @param [uiSchema] - The UI schema from which to derive potentially displayable information
     * @param [globalOptions={}] - The optional Global UI Schema from which to get any fallback `xxx` options
     * @returns - True if the label should be displayed or false if it should not
     */
    getDisplayLabel(schema, uiSchema, globalOptions) {
      return getDisplayLabel(
        this.validator,
        schema,
        uiSchema,
        this.rootSchema,
        globalOptions,
        this.experimental_customMergeAllOf
      );
    }
    /** Determines which of the given `options` provided most closely matches the `formData`.
     * Returns the index of the option that is valid and is the closest match, or 0 if there is no match.
     *
     * The closest match is determined using the number of matching properties, and more heavily favors options with
     * matching readOnly, default, or const values.
     *
     * @param formData - The form data associated with the schema
     * @param options - The list of options that can be selected from
     * @param [selectedOption] - The index of the currently selected option, defaulted to -1 if not specified
     * @param [discriminatorField] - The optional name of the field within the options object whose value is used to
     *          determine which option is selected
     * @returns - The index of the option that is the closest match to the `formData` or the `selectedOption` if no match
     */
    getClosestMatchingOption(formData, options, selectedOption, discriminatorField) {
      return getClosestMatchingOption(
        this.validator,
        this.rootSchema,
        formData,
        options,
        selectedOption,
        discriminatorField,
        this.experimental_customMergeAllOf
      );
    }
    /** Given the `formData` and list of `options`, attempts to find the index of the first option that matches the data.
     * Always returns the first option if there is nothing that matches.
     *
     * @param formData - The current formData, if any, used to figure out a match
     * @param options - The list of options to find a matching options from
     * @param [discriminatorField] - The optional name of the field within the options object whose value is used to
     *          determine which option is selected
     * @returns - The firstindex of the matched option or 0 if none is available
     */
    getFirstMatchingOption(formData, options, discriminatorField) {
      return getFirstMatchingOption(this.validator, formData, options, this.rootSchema, discriminatorField);
    }
    /** Given the `formData` and list of `options`, attempts to find the index of the option that best matches the data.
     * Deprecated, use `getFirstMatchingOption()` instead.
     *
     * @param formData - The current formData, if any, onto which to provide any missing defaults
     * @param options - The list of options to find a matching options from
     * @param [discriminatorField] - The optional name of the field within the options object whose value is used to
     *          determine which option is selected
     * @returns - The index of the matched option or 0 if none is available
     * @deprecated
     */
    getMatchingOption(formData, options, discriminatorField) {
      return getMatchingOption(this.validator, formData, options, this.rootSchema, discriminatorField);
    }
    /** Checks to see if the `schema` and `uiSchema` combination represents an array of files
     *
     * @param schema - The schema for which check for array of files flag is desired
     * @param [uiSchema] - The UI schema from which to check the widget
     * @returns - True if schema/uiSchema contains an array of files, otherwise false
     */
    isFilesArray(schema, uiSchema) {
      return isFilesArray(this.validator, schema, uiSchema, this.rootSchema, this.experimental_customMergeAllOf);
    }
    /** Checks to see if the `schema` combination represents a multi-select
     *
     * @param schema - The schema for which check for a multi-select flag is desired
     * @returns - True if schema contains a multi-select, otherwise false
     */
    isMultiSelect(schema) {
      return isMultiSelect(this.validator, schema, this.rootSchema, this.experimental_customMergeAllOf);
    }
    /** Checks to see if the `schema` combination represents a select
     *
     * @param schema - The schema for which check for a select flag is desired
     * @returns - True if schema contains a select, otherwise false
     */
    isSelect(schema) {
      return isSelect(this.validator, schema, this.rootSchema, this.experimental_customMergeAllOf);
    }
    /** Merges the errors in `additionalErrorSchema` into the existing `validationData` by combining the hierarchies in
     * the two `ErrorSchema`s and then appending the error list from the `additionalErrorSchema` obtained by calling
     * `getValidator().toErrorList()` onto the `errors` in the `validationData`. If no `additionalErrorSchema` is passed,
     * then `validationData` is returned.
     *
     * @param validationData - The current `ValidationData` into which to merge the additional errors
     * @param [additionalErrorSchema] - The additional set of errors
     * @returns - The `validationData` with the additional errors from `additionalErrorSchema` merged into it, if provided.
     * @deprecated - Use the `validationDataMerge()` function exported from `@rjsf/utils` instead. This function will be
     *        removed in the next major release.
     */
    mergeValidationData(validationData, additionalErrorSchema) {
      return mergeValidationData(this.validator, validationData, additionalErrorSchema);
    }
    /** Retrieves an expanded schema that has had all of its conditions, additional properties, references and
     * dependencies resolved and merged into the `schema` given a `rawFormData` that is used to do the potentially
     * recursive resolution.
     *
     * @param schema - The schema for which retrieving a schema is desired
     * @param [rawFormData] - The current formData, if any, to assist retrieving a schema
     * @returns - The schema having its conditions, additional properties, references and dependencies resolved
     */
    retrieveSchema(schema, rawFormData) {
      return retrieveSchema(
        this.validator,
        schema,
        this.rootSchema,
        rawFormData,
        this.experimental_customMergeAllOf
      );
    }
    /** Sanitize the `data` associated with the `oldSchema` so it is considered appropriate for the `newSchema`. If the
     * new schema does not contain any properties, then `undefined` is returned to clear all the form data. Due to the
     * nature of schemas, this sanitization happens recursively for nested objects of data. Also, any properties in the
     * old schemas that are non-existent in the new schema are set to `undefined`.
     *
     * @param [newSchema] - The new schema for which the data is being sanitized
     * @param [oldSchema] - The old schema from which the data originated
     * @param [data={}] - The form data associated with the schema, defaulting to an empty object when undefined
     * @returns - The new form data, with all the fields uniquely associated with the old schema set
     *      to `undefined`. Will return `undefined` if the new schema is not an object containing properties.
     */
    sanitizeDataForNewSchema(newSchema, oldSchema, data) {
      return sanitizeDataForNewSchema(
        this.validator,
        this.rootSchema,
        newSchema,
        oldSchema,
        data,
        this.experimental_customMergeAllOf
      );
    }
    /** Generates an `IdSchema` object for the `schema`, recursively
     *
     * @param schema - The schema for which the display label flag is desired
     * @param [id] - The base id for the schema
     * @param [formData] - The current formData, if any, onto which to provide any missing defaults
     * @param [idPrefix='root'] - The prefix to use for the id
     * @param [idSeparator='_'] - The separator to use for the path segments in the id
     * @returns - The `IdSchema` object for the `schema`
     */
    toIdSchema(schema, id, formData, idPrefix = "root", idSeparator = "_") {
      return toIdSchema(
        this.validator,
        schema,
        id,
        this.rootSchema,
        formData,
        idPrefix,
        idSeparator,
        this.experimental_customMergeAllOf
      );
    }
    /** Generates an `PathSchema` object for the `schema`, recursively
     *
     * @param schema - The schema for which the display label flag is desired
     * @param [name] - The base name for the schema
     * @param [formData] - The current formData, if any, onto which to provide any missing defaults
     * @returns - The `PathSchema` object for the `schema`
     */
    toPathSchema(schema, name, formData) {
      return toPathSchema(
        this.validator,
        schema,
        name,
        this.rootSchema,
        formData,
        this.experimental_customMergeAllOf
      );
    }
  };
  function createSchemaUtils(validator, rootSchema, experimental_defaultFormStateBehavior = {}, experimental_customMergeAllOf) {
    return new SchemaUtils(
      validator,
      rootSchema,
      experimental_defaultFormStateBehavior,
      experimental_customMergeAllOf
    );
  }

  // src/dataURItoBlob.ts
  function dataURItoBlob(dataURILike) {
    if (dataURILike.indexOf("data:") === -1) {
      throw new Error("File is invalid: URI must be a dataURI");
    }
    const dataURI = dataURILike.slice(5);
    const splitted = dataURI.split(";base64,");
    if (splitted.length !== 2) {
      throw new Error("File is invalid: dataURI must be base64");
    }
    const [media, base64] = splitted;
    const [mime, ...mediaparams] = media.split(";");
    const type = mime || "";
    const name = decodeURI(
      // parse the parameters into key-value pairs, find a key, and extract a value
      // if no key is found, then the name is unknown
      mediaparams.map((param) => param.split("=")).find(([key]) => key === "name")?.[1] || "unknown"
    );
    try {
      const binary = atob(base64);
      const array = new Array(binary.length);
      for (let i = 0; i < binary.length; i++) {
        array[i] = binary.charCodeAt(i);
      }
      const blob = new window.Blob([new Uint8Array(array)], { type });
      return { blob, name };
    } catch (error) {
      throw new Error("File is invalid: " + error.message);
    }
  }

  // src/pad.ts
  function pad(num, width) {
    let s = String(num);
    while (s.length < width) {
      s = "0" + s;
    }
    return s;
  }

  // src/dateRangeOptions.ts
  function dateRangeOptions(start, stop) {
    if (start <= 0 && stop <= 0) {
      start = (/* @__PURE__ */ new Date()).getFullYear() + start;
      stop = (/* @__PURE__ */ new Date()).getFullYear() + stop;
    } else if (start < 0 || stop < 0) {
      throw new Error(`Both start (${start}) and stop (${stop}) must both be <= 0 or > 0, got one of each`);
    }
    if (start > stop) {
      return dateRangeOptions(stop, start).reverse();
    }
    const options = [];
    for (let i = start; i <= stop; i++) {
      options.push({ value: i, label: pad(i, 2) });
    }
    return options;
  }

  // src/replaceStringParameters.ts
  function replaceStringParameters(inputString, params) {
    let output = inputString;
    if (Array.isArray(params)) {
      const parts = output.split(/(%\d)/);
      params.forEach((param, index) => {
        const partIndex = parts.findIndex((part) => part === `%${index + 1}`);
        if (partIndex >= 0) {
          parts[partIndex] = param;
        }
      });
      output = parts.join("");
    }
    return output;
  }

  // src/englishStringTranslator.ts
  function englishStringTranslator(stringToTranslate, params) {
    return replaceStringParameters(stringToTranslate, params);
  }

  // src/enumOptionsValueForIndex.ts
  function enumOptionsValueForIndex(valueIndex, allEnumOptions = [], emptyValue) {
    if (Array.isArray(valueIndex)) {
      return valueIndex.map((index2) => enumOptionsValueForIndex(index2, allEnumOptions)).filter((val) => val !== emptyValue);
    }
    const index = valueIndex === "" || valueIndex === null ? -1 : Number(valueIndex);
    const option = allEnumOptions[index];
    return option ? option.value : emptyValue;
  }

  // src/enumOptionsDeselectValue.ts
  function enumOptionsDeselectValue(valueIndex, selected, allEnumOptions = []) {
    const value = enumOptionsValueForIndex(valueIndex, allEnumOptions);
    if (Array.isArray(selected)) {
      return selected.filter((v) => !deepEquals(v, value));
    }
    return deepEquals(value, selected) ? void 0 : selected;
  }

  // src/enumOptionsIsSelected.ts
  function enumOptionsIsSelected(value, selected) {
    if (Array.isArray(selected)) {
      return selected.some((sel) => deepEquals(sel, value));
    }
    return deepEquals(selected, value);
  }

  // src/enumOptionsIndexForValue.ts
  function enumOptionsIndexForValue(value, allEnumOptions = [], multiple = false) {
    const selectedIndexes = allEnumOptions.map((opt, index) => enumOptionsIsSelected(opt.value, value) ? String(index) : void 0).filter((opt) => typeof opt !== "undefined");
    if (!multiple) {
      return selectedIndexes[0];
    }
    return selectedIndexes;
  }
  function enumOptionsSelectValue(valueIndex, selected, allEnumOptions = []) {
    const value = enumOptionsValueForIndex(valueIndex, allEnumOptions);
    if (!isNil(value)) {
      const index = allEnumOptions.findIndex((opt) => value === opt.value);
      const all = allEnumOptions.map(({ value: val }) => val);
      const updated = selected.slice(0, index).concat(value, selected.slice(index));
      return updated.sort((a, b) => Number(all.indexOf(a) > all.indexOf(b)));
    }
    return selected;
  }
  var ErrorSchemaBuilder = class {
    /** Construct an `ErrorSchemaBuilder` with an optional initial set of errors in an `ErrorSchema`.
     *
     * @param [initialSchema] - The optional set of initial errors, that will be cloned into the class
     */
    constructor(initialSchema) {
      /** The error schema being built
       *
       * @private
       */
      this.errorSchema = {};
      this.resetAllErrors(initialSchema);
    }
    /** Returns the `ErrorSchema` that has been updated by the methods of the `ErrorSchemaBuilder`
     */
    get ErrorSchema() {
      return this.errorSchema;
    }
    /** Will get an existing `ErrorSchema` at the specified `pathOfError` or create and return one.
     *
     * @param [pathOfError] - The optional path into the `ErrorSchema` at which to add the error(s)
     * @returns - The error block for the given `pathOfError` or the root if not provided
     * @private
     */
    getOrCreateErrorBlock(pathOfError) {
      const hasPath = Array.isArray(pathOfError) && pathOfError.length > 0 || typeof pathOfError === "string";
      let errorBlock = hasPath ? get8(this.errorSchema, pathOfError) : this.errorSchema;
      if (!errorBlock && pathOfError) {
        errorBlock = {};
        setWith(this.errorSchema, pathOfError, errorBlock, Object);
      }
      return errorBlock;
    }
    /** Resets all errors in the `ErrorSchemaBuilder` back to the `initialSchema` if provided, otherwise an empty set.
     *
     * @param [initialSchema] - The optional set of initial errors, that will be cloned into the class
     * @returns - The `ErrorSchemaBuilder` object for chaining purposes
     */
    resetAllErrors(initialSchema) {
      this.errorSchema = initialSchema ? cloneDeep(initialSchema) : {};
      return this;
    }
    /** Adds the `errorOrList` to the list of errors in the `ErrorSchema` at either the root level or the location within
     * the schema described by the `pathOfError`. For more information about how to specify the path see the
     * [eslint lodash plugin docs](https://github.com/wix/eslint-plugin-lodash/blob/master/docs/rules/path-style.md).
     *
     * @param errorOrList - The error or list of errors to add into the `ErrorSchema`
     * @param [pathOfError] - The optional path into the `ErrorSchema` at which to add the error(s)
     * @returns - The `ErrorSchemaBuilder` object for chaining purposes
     */
    addErrors(errorOrList, pathOfError) {
      const errorBlock = this.getOrCreateErrorBlock(pathOfError);
      let errorsList = get8(errorBlock, ERRORS_KEY);
      if (!Array.isArray(errorsList)) {
        errorsList = [];
        errorBlock[ERRORS_KEY] = errorsList;
      }
      if (Array.isArray(errorOrList)) {
        set3(errorBlock, ERRORS_KEY, [.../* @__PURE__ */ new Set([...errorsList, ...errorOrList])]);
      } else {
        set3(errorBlock, ERRORS_KEY, [.../* @__PURE__ */ new Set([...errorsList, errorOrList])]);
      }
      return this;
    }
    /** Sets/replaces the `errorOrList` as the error(s) in the `ErrorSchema` at either the root level or the location
     * within the schema described by the `pathOfError`. For more information about how to specify the path see the
     * [eslint lodash plugin docs](https://github.com/wix/eslint-plugin-lodash/blob/master/docs/rules/path-style.md).
     *
     * @param errorOrList - The error or list of errors to set into the `ErrorSchema`
     * @param [pathOfError] - The optional path into the `ErrorSchema` at which to set the error(s)
     * @returns - The `ErrorSchemaBuilder` object for chaining purposes
     */
    setErrors(errorOrList, pathOfError) {
      const errorBlock = this.getOrCreateErrorBlock(pathOfError);
      const listToAdd = Array.isArray(errorOrList) ? [.../* @__PURE__ */ new Set([...errorOrList])] : [errorOrList];
      set3(errorBlock, ERRORS_KEY, listToAdd);
      return this;
    }
    /** Clears the error(s) in the `ErrorSchema` at either the root level or the location within the schema described by
     * the `pathOfError`. For more information about how to specify the path see the
     * [eslint lodash plugin docs](https://github.com/wix/eslint-plugin-lodash/blob/master/docs/rules/path-style.md).
     *
     * @param [pathOfError] - The optional path into the `ErrorSchema` at which to clear the error(s)
     * @returns - The `ErrorSchemaBuilder` object for chaining purposes
     */
    clearErrors(pathOfError) {
      const errorBlock = this.getOrCreateErrorBlock(pathOfError);
      set3(errorBlock, ERRORS_KEY, []);
      return this;
    }
  };

  // src/getDateElementProps.ts
  function getDateElementProps(date, time, yearRange = [1900, (/* @__PURE__ */ new Date()).getFullYear() + 2], format = "YMD") {
    const { day, month, year, hour, minute, second } = date;
    const dayObj = { type: "day", range: [1, 31], value: day };
    const monthObj = { type: "month", range: [1, 12], value: month };
    const yearObj = { type: "year", range: yearRange, value: year };
    const dateElementProp = [];
    switch (format) {
      case "MDY":
        dateElementProp.push(monthObj, dayObj, yearObj);
        break;
      case "DMY":
        dateElementProp.push(dayObj, monthObj, yearObj);
        break;
      case "YMD":
      default:
        dateElementProp.push(yearObj, monthObj, dayObj);
    }
    if (time) {
      dateElementProp.push(
        { type: "hour", range: [0, 23], value: hour },
        { type: "minute", range: [0, 59], value: minute },
        { type: "second", range: [0, 59], value: second }
      );
    }
    return dateElementProp;
  }

  // src/rangeSpec.ts
  function rangeSpec(schema) {
    const spec = {};
    if (schema.multipleOf) {
      spec.step = schema.multipleOf;
    }
    if (schema.minimum || schema.minimum === 0) {
      spec.min = schema.minimum;
    }
    if (schema.maximum || schema.maximum === 0) {
      spec.max = schema.maximum;
    }
    return spec;
  }

  // src/getInputProps.ts
  function getInputProps(schema, defaultType, options = {}, autoDefaultStepAny = true) {
    const inputProps = {
      type: defaultType || "text",
      ...rangeSpec(schema)
    };
    if (options.inputType) {
      inputProps.type = options.inputType;
    } else if (!defaultType) {
      if (schema.type === "number") {
        inputProps.type = "number";
        if (autoDefaultStepAny && inputProps.step === void 0) {
          inputProps.step = "any";
        }
      } else if (schema.type === "integer") {
        inputProps.type = "number";
        if (inputProps.step === void 0) {
          inputProps.step = 1;
        }
      }
    }
    if (options.autocomplete) {
      inputProps.autoComplete = options.autocomplete;
    }
    return inputProps;
  }

  // src/getSubmitButtonOptions.ts
  var DEFAULT_OPTIONS = {
    props: {
      disabled: false
    },
    submitText: "Submit",
    norender: false
  };
  function getSubmitButtonOptions(uiSchema = {}) {
    const uiOptions = getUiOptions(uiSchema);
    if (uiOptions && uiOptions[SUBMIT_BTN_OPTIONS_KEY]) {
      const options = uiOptions[SUBMIT_BTN_OPTIONS_KEY];
      return { ...DEFAULT_OPTIONS, ...options };
    }
    return DEFAULT_OPTIONS;
  }

  // src/getTemplate.ts
  function getTemplate(name, registry, uiOptions = {}) {
    const { templates } = registry;
    if (name === "ButtonTemplates") {
      return templates[name];
    }
    return (
      // Evaluating uiOptions[name] results in TS2590: Expression produces a union type that is too complex to represent
      // To avoid that, we cast uiOptions to `any` before accessing the name field
      uiOptions[name] || templates[name]
    );
  }
  var widgetMap = {
    boolean: {
      checkbox: "CheckboxWidget",
      radio: "RadioWidget",
      select: "SelectWidget",
      hidden: "HiddenWidget"
    },
    string: {
      text: "TextWidget",
      password: "PasswordWidget",
      email: "EmailWidget",
      hostname: "TextWidget",
      ipv4: "TextWidget",
      ipv6: "TextWidget",
      uri: "URLWidget",
      "data-url": "FileWidget",
      radio: "RadioWidget",
      select: "SelectWidget",
      textarea: "TextareaWidget",
      hidden: "HiddenWidget",
      date: "DateWidget",
      datetime: "DateTimeWidget",
      "date-time": "DateTimeWidget",
      "alt-date": "AltDateWidget",
      "alt-datetime": "AltDateTimeWidget",
      time: "TimeWidget",
      color: "ColorWidget",
      file: "FileWidget"
    },
    number: {
      text: "TextWidget",
      select: "SelectWidget",
      updown: "UpDownWidget",
      range: "RangeWidget",
      radio: "RadioWidget",
      hidden: "HiddenWidget"
    },
    integer: {
      text: "TextWidget",
      select: "SelectWidget",
      updown: "UpDownWidget",
      range: "RangeWidget",
      radio: "RadioWidget",
      hidden: "HiddenWidget"
    },
    array: {
      select: "SelectWidget",
      checkboxes: "CheckboxesWidget",
      files: "FileWidget",
      hidden: "HiddenWidget"
    }
  };
  function mergeWidgetOptions(AWidget) {
    let MergedWidget = get8(AWidget, "MergedWidget");
    if (!MergedWidget) {
      const defaultOptions = AWidget.defaultProps && AWidget.defaultProps.options || {};
      MergedWidget = ({ options, ...props }) => {
        return /* @__PURE__ */ jsxRuntime.jsx(AWidget, { options: { ...defaultOptions, ...options }, ...props });
      };
      set3(AWidget, "MergedWidget", MergedWidget);
    }
    return MergedWidget;
  }
  function getWidget(schema, widget, registeredWidgets = {}) {
    const type = getSchemaType(schema);
    if (typeof widget === "function" || widget && ReactIs.isForwardRef(react.createElement(widget)) || ReactIs.isMemo(widget)) {
      return mergeWidgetOptions(widget);
    }
    if (typeof widget !== "string") {
      throw new Error(`Unsupported widget definition: ${typeof widget}`);
    }
    if (widget in registeredWidgets) {
      const registeredWidget = registeredWidgets[widget];
      return getWidget(schema, registeredWidget, registeredWidgets);
    }
    if (typeof type === "string") {
      if (!(type in widgetMap)) {
        throw new Error(`No widget for type '${type}'`);
      }
      if (widget in widgetMap[type]) {
        const registeredWidget = registeredWidgets[widgetMap[type][widget]];
        return getWidget(schema, registeredWidget, registeredWidgets);
      }
    }
    throw new Error(`No widget '${widget}' for type '${type}'`);
  }

  // src/hashForSchema.ts
  function hashString(string) {
    let hash = 0;
    for (let i = 0; i < string.length; i += 1) {
      const chr = string.charCodeAt(i);
      hash = (hash << 5) - hash + chr;
      hash = hash & hash;
    }
    return hash.toString(16);
  }
  function hashForSchema(schema) {
    const allKeys = /* @__PURE__ */ new Set();
    JSON.stringify(schema, (key, value) => (allKeys.add(key), value));
    return hashString(JSON.stringify(schema, Array.from(allKeys).sort()));
  }

  // src/hasWidget.ts
  function hasWidget(schema, widget, registeredWidgets = {}) {
    try {
      getWidget(schema, widget, registeredWidgets);
      return true;
    } catch (e) {
      const err = e;
      if (err.message && (err.message.startsWith("No widget") || err.message.startsWith("Unsupported widget"))) {
        return false;
      }
      throw e;
    }
  }
  function idGenerator(id, suffix) {
    const theId = isString(id) ? id : id[ID_KEY];
    return `${theId}__${suffix}`;
  }
  function descriptionId(id) {
    return idGenerator(id, "description");
  }
  function errorId(id) {
    return idGenerator(id, "error");
  }
  function examplesId(id) {
    return idGenerator(id, "examples");
  }
  function helpId(id) {
    return idGenerator(id, "help");
  }
  function titleId(id) {
    return idGenerator(id, "title");
  }
  function ariaDescribedByIds(id, includeExamples = false) {
    const examples = includeExamples ? ` ${examplesId(id)}` : "";
    return `${errorId(id)} ${descriptionId(id)} ${helpId(id)}${examples}`;
  }
  function optionId(id, optionIndex) {
    return `${id}-${optionIndex}`;
  }

  // src/labelValue.ts
  function labelValue(label, hideLabel, fallback) {
    return hideLabel ? fallback : label;
  }

  // src/localToUTC.ts
  function localToUTC(dateString) {
    return dateString ? new Date(dateString).toJSON() : void 0;
  }

  // src/orderProperties.ts
  function orderProperties(properties, order) {
    if (!Array.isArray(order)) {
      return properties;
    }
    const arrayToHash = (arr) => arr.reduce((prev, curr) => {
      prev[curr] = true;
      return prev;
    }, {});
    const errorPropList = (arr) => arr.length > 1 ? `properties '${arr.join("', '")}'` : `property '${arr[0]}'`;
    const propertyHash = arrayToHash(properties);
    const orderFiltered = order.filter((prop) => prop === "*" || propertyHash[prop]);
    const orderHash = arrayToHash(orderFiltered);
    const rest = properties.filter((prop) => !orderHash[prop]);
    const restIndex = orderFiltered.indexOf("*");
    if (restIndex === -1) {
      if (rest.length) {
        throw new Error(`uiSchema order list does not contain ${errorPropList(rest)}`);
      }
      return orderFiltered;
    }
    if (restIndex !== orderFiltered.lastIndexOf("*")) {
      throw new Error("uiSchema order list contains more than one wildcard item");
    }
    const complete = [...orderFiltered];
    complete.splice(restIndex, 1, ...rest);
    return complete;
  }

  // src/parseDateString.ts
  function parseDateString(dateString, includeTime = true) {
    if (!dateString) {
      return {
        year: -1,
        month: -1,
        day: -1,
        hour: includeTime ? -1 : 0,
        minute: includeTime ? -1 : 0,
        second: includeTime ? -1 : 0
      };
    }
    const date = new Date(dateString);
    if (Number.isNaN(date.getTime())) {
      throw new Error("Unable to parse date " + dateString);
    }
    return {
      year: date.getUTCFullYear(),
      month: date.getUTCMonth() + 1,
      // oh you, javascript.
      day: date.getUTCDate(),
      hour: includeTime ? date.getUTCHours() : 0,
      minute: includeTime ? date.getUTCMinutes() : 0,
      second: includeTime ? date.getUTCSeconds() : 0
    };
  }

  // src/schemaRequiresTrueValue.ts
  function schemaRequiresTrueValue(schema) {
    if (schema.const) {
      return true;
    }
    if (schema.enum && schema.enum.length === 1 && schema.enum[0] === true) {
      return true;
    }
    if (schema.anyOf && schema.anyOf.length === 1) {
      return schemaRequiresTrueValue(schema.anyOf[0]);
    }
    if (schema.oneOf && schema.oneOf.length === 1) {
      return schemaRequiresTrueValue(schema.oneOf[0]);
    }
    if (schema.allOf) {
      const schemaSome = (subSchema) => schemaRequiresTrueValue(subSchema);
      return schema.allOf.some(schemaSome);
    }
    return false;
  }

  // src/shouldRender.ts
  function shouldRender(component, nextProps, nextState) {
    const { props, state } = component;
    return !deepEquals(props, nextProps) || !deepEquals(state, nextState);
  }

  // src/toDateString.ts
  function toDateString(dateObject, time = true) {
    const { year, month, day, hour = 0, minute = 0, second = 0 } = dateObject;
    const utcTime = Date.UTC(year, month - 1, day, hour, minute, second);
    const datetime = new Date(utcTime).toJSON();
    return time ? datetime : datetime.slice(0, 10);
  }
  function toErrorList(errorSchema, fieldPath = []) {
    if (!errorSchema) {
      return [];
    }
    let errorList = [];
    if (ERRORS_KEY in errorSchema) {
      errorList = errorList.concat(
        errorSchema[ERRORS_KEY].map((message) => {
          const property = `.${fieldPath.join(".")}`;
          return {
            property,
            message,
            stack: `${property} ${message}`
          };
        })
      );
    }
    return Object.keys(errorSchema).reduce((acc, key) => {
      if (key !== ERRORS_KEY) {
        const childSchema = errorSchema[key];
        if (isPlainObject4(childSchema)) {
          acc = acc.concat(toErrorList(childSchema, [...fieldPath, key]));
        }
      }
      return acc;
    }, errorList);
  }
  function toErrorSchema(errors) {
    const builder = new ErrorSchemaBuilder();
    if (errors.length) {
      errors.forEach((error) => {
        const { property, message } = error;
        const path = property === "." ? [] : toPath(property);
        if (path.length > 0 && path[0] === "") {
          path.splice(0, 1);
        }
        if (message) {
          builder.addErrors(message, path);
        }
      });
    }
    return builder.ErrorSchema;
  }
  function unwrapErrorHandler(errorHandler) {
    return Object.keys(errorHandler).reduce((acc, key) => {
      if (key === "addError") {
        return acc;
      } else {
        const childSchema = errorHandler[key];
        if (isPlainObject4(childSchema)) {
          return {
            ...acc,
            [key]: unwrapErrorHandler(childSchema)
          };
        }
        return { ...acc, [key]: childSchema };
      }
    }, {});
  }

  // src/utcToLocal.ts
  function utcToLocal(jsonDate) {
    if (!jsonDate) {
      return "";
    }
    const date = new Date(jsonDate);
    const yyyy = pad(date.getFullYear(), 4);
    const MM = pad(date.getMonth() + 1, 2);
    const dd = pad(date.getDate(), 2);
    const hh = pad(date.getHours(), 2);
    const mm = pad(date.getMinutes(), 2);
    const ss = pad(date.getSeconds(), 2);
    const SSS = pad(date.getMilliseconds(), 3);
    return `${yyyy}-${MM}-${dd}T${hh}:${mm}:${ss}.${SSS}`;
  }
  function validationDataMerge(validationData, additionalErrorSchema) {
    if (!additionalErrorSchema) {
      return validationData;
    }
    const { errors: oldErrors, errorSchema: oldErrorSchema } = validationData;
    let errors = toErrorList(additionalErrorSchema);
    let errorSchema = additionalErrorSchema;
    if (!isEmpty(oldErrorSchema)) {
      errorSchema = mergeObjects(oldErrorSchema, additionalErrorSchema, true);
      errors = [...oldErrors].concat(errors);
    }
    return { errorSchema, errors };
  }
  function withIdRefPrefixObject(node) {
    for (const key in node) {
      const realObj = node;
      const value = realObj[key];
      if (key === REF_KEY && typeof value === "string" && value.startsWith("#")) {
        realObj[key] = ROOT_SCHEMA_PREFIX + value;
      } else {
        realObj[key] = withIdRefPrefix(value);
      }
    }
    return node;
  }
  function withIdRefPrefixArray(node) {
    for (let i = 0; i < node.length; i++) {
      node[i] = withIdRefPrefix(node[i]);
    }
    return node;
  }
  function withIdRefPrefix(schemaNode) {
    if (Array.isArray(schemaNode)) {
      return withIdRefPrefixArray([...schemaNode]);
    }
    if (isObject2(schemaNode)) {
      return withIdRefPrefixObject({ ...schemaNode });
    }
    return schemaNode;
  }
  function getChangedFields(a, b) {
    const aIsPlainObject = isPlainObject4(a);
    const bIsPlainObject = isPlainObject4(b);
    if (a === b || !aIsPlainObject && !bIsPlainObject) {
      return [];
    }
    if (aIsPlainObject && !bIsPlainObject) {
      return keys(a);
    } else if (!aIsPlainObject && bIsPlainObject) {
      return keys(b);
    } else {
      const unequalFields = keys(pickBy(a, (value, key) => !deepEquals(value, get8(b, key))));
      const diffFields = difference(keys(b), keys(a));
      return [...unequalFields, ...diffFields];
    }
  }

  // src/enums.ts
  var TranslatableString = /* @__PURE__ */ ((TranslatableString2) => {
    TranslatableString2["ArrayItemTitle"] = "Item";
    TranslatableString2["MissingItems"] = "Missing items definition";
    TranslatableString2["YesLabel"] = "Yes";
    TranslatableString2["NoLabel"] = "No";
    TranslatableString2["CloseLabel"] = "Close";
    TranslatableString2["ErrorsLabel"] = "Errors";
    TranslatableString2["NewStringDefault"] = "New Value";
    TranslatableString2["AddButton"] = "Add";
    TranslatableString2["AddItemButton"] = "Add Item";
    TranslatableString2["CopyButton"] = "Copy";
    TranslatableString2["MoveDownButton"] = "Move down";
    TranslatableString2["MoveUpButton"] = "Move up";
    TranslatableString2["RemoveButton"] = "Remove";
    TranslatableString2["NowLabel"] = "Now";
    TranslatableString2["ClearLabel"] = "Clear";
    TranslatableString2["AriaDateLabel"] = "Select a date";
    TranslatableString2["PreviewLabel"] = "Preview";
    TranslatableString2["DecrementAriaLabel"] = "Decrease value by 1";
    TranslatableString2["IncrementAriaLabel"] = "Increase value by 1";
    TranslatableString2["UnknownFieldType"] = "Unknown field type %1";
    TranslatableString2["OptionPrefix"] = "Option %1";
    TranslatableString2["TitleOptionPrefix"] = "%1 option %2";
    TranslatableString2["KeyLabel"] = "%1 Key";
    TranslatableString2["InvalidObjectField"] = 'Invalid "%1" object field configuration: _%2_.';
    TranslatableString2["UnsupportedField"] = "Unsupported field schema.";
    TranslatableString2["UnsupportedFieldWithId"] = "Unsupported field schema for field `%1`.";
    TranslatableString2["UnsupportedFieldWithReason"] = "Unsupported field schema: _%1_.";
    TranslatableString2["UnsupportedFieldWithIdAndReason"] = "Unsupported field schema for field `%1`: _%2_.";
    TranslatableString2["FilesInfo"] = "**%1** (%2, %3 bytes)";
    return TranslatableString2;
  })(TranslatableString || {});
  var ParserValidator = class {
    /** Construct the ParserValidator for the given `rootSchema`. This `rootSchema` will be stashed in the `schemaMap`
     * first.
     *
     * @param rootSchema - The root schema against which this validator will be executed
     */
    constructor(rootSchema) {
      /** The map of schemas encountered by the ParserValidator */
      this.schemaMap = {};
      this.rootSchema = rootSchema;
      this.addSchema(rootSchema, hashForSchema(rootSchema));
    }
    /** Resets the internal AJV validator to clear schemas from it. Can be helpful for resetting the validator for tests.
     */
    reset() {
      this.schemaMap = {};
    }
    /** Adds the given `schema` to the `schemaMap` keyed by the `hash` or `ID_KEY` if present on the `schema`. If the
     * schema does not have an `ID_KEY`, then the `hash` will be added as the `ID_KEY` to allow the schema to be
     * associated with it's `hash` for future use (by a schema compiler).
     *
     * @param schema - The schema which is to be added to the map
     * @param hash - The hash value at which to map the schema
     */
    addSchema(schema, hash) {
      const key = get8(schema, ID_KEY, hash);
      const identifiedSchema = { ...schema, [ID_KEY]: key };
      const existing = this.schemaMap[key];
      if (!existing) {
        this.schemaMap[key] = identifiedSchema;
      } else if (!deepEquals(existing, identifiedSchema)) {
        console.error("existing schema:", JSON.stringify(existing, null, 2));
        console.error("new schema:", JSON.stringify(identifiedSchema, null, 2));
        throw new Error(
          `Two different schemas exist with the same key ${key}! What a bad coincidence. If possible, try adding an $id to one of the schemas`
        );
      }
    }
    /** Returns the current `schemaMap` to the caller
     */
    getSchemaMap() {
      return this.schemaMap;
    }
    /** Implements the `ValidatorType` `isValid()` method to capture the `schema` in the `schemaMap`. Throws an error when
     * the `rootSchema` is not the same as the root schema provided during construction.
     *
     * @param schema - The schema to record in the `schemaMap`
     * @param _formData - The formData parameter that is ignored
     * @param rootSchema - The root schema associated with the schema
     * @throws - Error when the given `rootSchema` differs from the root schema provided during construction
     */
    isValid(schema, _formData, rootSchema) {
      if (!deepEquals(rootSchema, this.rootSchema)) {
        throw new Error("Unexpectedly calling isValid() with a rootSchema that differs from the construction rootSchema");
      }
      this.addSchema(schema, hashForSchema(schema));
      return false;
    }
    /** Implements the `ValidatorType` `rawValidation()` method to throw an error since it is never supposed to be called
     *
     * @param _schema - The schema parameter that is ignored
     * @param _formData - The formData parameter that is ignored
     */
    rawValidation(_schema, _formData) {
      throw new Error("Unexpectedly calling the `rawValidation()` method during schema parsing");
    }
    /** Implements the `ValidatorType` `toErrorList()` method to throw an error since it is never supposed to be called
     *
     * @param _errorSchema - The error schema parameter that is ignored
     * @param _fieldPath - The field path parameter that is ignored
     */
    toErrorList(_errorSchema, _fieldPath) {
      throw new Error("Unexpectedly calling the `toErrorList()` method during schema parsing");
    }
    /** Implements the `ValidatorType` `validateFormData()` method to throw an error since it is never supposed to be
     * called
     *
     * @param _formData - The formData parameter that is ignored
     * @param _schema - The schema parameter that is ignored
     * @param _customValidate - The customValidate parameter that is ignored
     * @param _transformErrors - The transformErrors parameter that is ignored
     * @param _uiSchema - The uiSchema parameter that is ignored
     */
    validateFormData(_formData, _schema, _customValidate, _transformErrors, _uiSchema) {
      throw new Error("Unexpectedly calling the `validateFormData()` method during schema parsing");
    }
  };

  // src/parser/schemaParser.ts
  function parseSchema(validator, recurseList, rootSchema, schema) {
    const schemas = retrieveSchemaInternal(validator, schema, rootSchema, void 0, true);
    schemas.forEach((schema2) => {
      const sameSchemaIndex = recurseList.findIndex((item) => deepEquals(item, schema2));
      if (sameSchemaIndex === -1) {
        recurseList.push(schema2);
        const allOptions = resolveAnyOrOneOfSchemas(validator, schema2, rootSchema, true);
        allOptions.forEach((s) => {
          if (PROPERTIES_KEY in s && s[PROPERTIES_KEY]) {
            forEach(schema2[PROPERTIES_KEY], (value) => {
              parseSchema(validator, recurseList, rootSchema, value);
            });
          }
        });
        if (ITEMS_KEY in schema2 && !Array.isArray(schema2.items) && typeof schema2.items !== "boolean") {
          parseSchema(validator, recurseList, rootSchema, schema2.items);
        }
      }
    });
  }
  function schemaParser(rootSchema) {
    const validator = new ParserValidator(rootSchema);
    const recurseList = [];
    parseSchema(validator, recurseList, rootSchema, rootSchema);
    return validator.getSchemaMap();
  }

  exports.ADDITIONAL_PROPERTIES_KEY = ADDITIONAL_PROPERTIES_KEY;
  exports.ADDITIONAL_PROPERTY_FLAG = ADDITIONAL_PROPERTY_FLAG;
  exports.ALL_OF_KEY = ALL_OF_KEY;
  exports.ANY_OF_KEY = ANY_OF_KEY;
  exports.CONST_KEY = CONST_KEY;
  exports.DEFAULT_KEY = DEFAULT_KEY;
  exports.DEFINITIONS_KEY = DEFINITIONS_KEY;
  exports.DEPENDENCIES_KEY = DEPENDENCIES_KEY;
  exports.ENUM_KEY = ENUM_KEY;
  exports.ERRORS_KEY = ERRORS_KEY;
  exports.ErrorSchemaBuilder = ErrorSchemaBuilder;
  exports.ID_KEY = ID_KEY;
  exports.IF_KEY = IF_KEY;
  exports.ITEMS_KEY = ITEMS_KEY;
  exports.JUNK_OPTION_ID = JUNK_OPTION_ID;
  exports.NAME_KEY = NAME_KEY;
  exports.ONE_OF_KEY = ONE_OF_KEY;
  exports.PROPERTIES_KEY = PROPERTIES_KEY;
  exports.REF_KEY = REF_KEY;
  exports.REQUIRED_KEY = REQUIRED_KEY;
  exports.RJSF_ADDITIONAL_PROPERTIES_FLAG = RJSF_ADDITIONAL_PROPERTIES_FLAG;
  exports.RJSF_ADDITONAL_PROPERTIES_FLAG = RJSF_ADDITONAL_PROPERTIES_FLAG;
  exports.ROOT_SCHEMA_PREFIX = ROOT_SCHEMA_PREFIX;
  exports.SUBMIT_BTN_OPTIONS_KEY = SUBMIT_BTN_OPTIONS_KEY;
  exports.TranslatableString = TranslatableString;
  exports.UI_FIELD_KEY = UI_FIELD_KEY;
  exports.UI_GLOBAL_OPTIONS_KEY = UI_GLOBAL_OPTIONS_KEY;
  exports.UI_OPTIONS_KEY = UI_OPTIONS_KEY;
  exports.UI_WIDGET_KEY = UI_WIDGET_KEY;
  exports.allowAdditionalItems = allowAdditionalItems;
  exports.ariaDescribedByIds = ariaDescribedByIds;
  exports.asNumber = asNumber;
  exports.canExpand = canExpand;
  exports.createErrorHandler = createErrorHandler;
  exports.createSchemaUtils = createSchemaUtils;
  exports.dataURItoBlob = dataURItoBlob;
  exports.dateRangeOptions = dateRangeOptions;
  exports.deepEquals = deepEquals;
  exports.descriptionId = descriptionId;
  exports.englishStringTranslator = englishStringTranslator;
  exports.enumOptionsDeselectValue = enumOptionsDeselectValue;
  exports.enumOptionsIndexForValue = enumOptionsIndexForValue;
  exports.enumOptionsIsSelected = enumOptionsIsSelected;
  exports.enumOptionsSelectValue = enumOptionsSelectValue;
  exports.enumOptionsValueForIndex = enumOptionsValueForIndex;
  exports.errorId = errorId;
  exports.examplesId = examplesId;
  exports.findSchemaDefinition = findSchemaDefinition;
  exports.getChangedFields = getChangedFields;
  exports.getClosestMatchingOption = getClosestMatchingOption;
  exports.getDateElementProps = getDateElementProps;
  exports.getDefaultFormState = getDefaultFormState;
  exports.getDiscriminatorFieldFromSchema = getDiscriminatorFieldFromSchema;
  exports.getDisplayLabel = getDisplayLabel;
  exports.getFirstMatchingOption = getFirstMatchingOption;
  exports.getInputProps = getInputProps;
  exports.getMatchingOption = getMatchingOption;
  exports.getOptionMatchingSimpleDiscriminator = getOptionMatchingSimpleDiscriminator;
  exports.getSchemaType = getSchemaType;
  exports.getSubmitButtonOptions = getSubmitButtonOptions;
  exports.getTemplate = getTemplate;
  exports.getUiOptions = getUiOptions;
  exports.getWidget = getWidget;
  exports.guessType = guessType;
  exports.hasWidget = hasWidget;
  exports.hashForSchema = hashForSchema;
  exports.helpId = helpId;
  exports.isConstant = isConstant;
  exports.isCustomWidget = isCustomWidget;
  exports.isFilesArray = isFilesArray;
  exports.isFixedItems = isFixedItems;
  exports.isMultiSelect = isMultiSelect;
  exports.isObject = isObject;
  exports.isSelect = isSelect;
  exports.labelValue = labelValue;
  exports.localToUTC = localToUTC;
  exports.mergeDefaultsWithFormData = mergeDefaultsWithFormData;
  exports.mergeObjects = mergeObjects;
  exports.mergeSchemas = mergeSchemas;
  exports.mergeValidationData = mergeValidationData;
  exports.optionId = optionId;
  exports.optionsList = optionsList;
  exports.orderProperties = orderProperties;
  exports.pad = pad;
  exports.parseDateString = parseDateString;
  exports.rangeSpec = rangeSpec;
  exports.replaceStringParameters = replaceStringParameters;
  exports.retrieveSchema = retrieveSchema;
  exports.sanitizeDataForNewSchema = sanitizeDataForNewSchema;
  exports.schemaParser = schemaParser;
  exports.schemaRequiresTrueValue = schemaRequiresTrueValue;
  exports.shouldRender = shouldRender;
  exports.titleId = titleId;
  exports.toConstant = toConstant;
  exports.toDateString = toDateString;
  exports.toErrorList = toErrorList;
  exports.toErrorSchema = toErrorSchema;
  exports.toIdSchema = toIdSchema;
  exports.toPathSchema = toPathSchema;
  exports.unwrapErrorHandler = unwrapErrorHandler;
  exports.utcToLocal = utcToLocal;
  exports.validationDataMerge = validationDataMerge;
  exports.withIdRefPrefix = withIdRefPrefix;

}));
