@rjsf/utils 5.11.2 → 5.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/dist/index.js +2544 -5
  2. package/dist/index.js.map +7 -0
  3. package/dist/utils.esm.js +1228 -2113
  4. package/dist/utils.esm.js.map +7 -1
  5. package/dist/utils.umd.js +2414 -0
  6. package/lib/ErrorSchemaBuilder.d.ts +60 -0
  7. package/lib/ErrorSchemaBuilder.js +103 -0
  8. package/lib/ErrorSchemaBuilder.js.map +1 -0
  9. package/lib/allowAdditionalItems.d.ts +8 -0
  10. package/lib/allowAdditionalItems.js +14 -0
  11. package/lib/allowAdditionalItems.js.map +1 -0
  12. package/lib/asNumber.d.ts +10 -0
  13. package/lib/asNumber.js +36 -0
  14. package/lib/asNumber.js.map +1 -0
  15. package/lib/canExpand.d.ts +11 -0
  16. package/lib/canExpand.js +26 -0
  17. package/lib/canExpand.js.map +1 -0
  18. package/lib/constants.d.ts +31 -0
  19. package/lib/constants.js +32 -0
  20. package/lib/constants.js.map +1 -0
  21. package/lib/createErrorHandler.d.ts +7 -0
  22. package/lib/createErrorHandler.js +31 -0
  23. package/lib/createErrorHandler.js.map +1 -0
  24. package/lib/createSchemaUtils.d.ts +10 -0
  25. package/lib/createSchemaUtils.js +207 -0
  26. package/lib/createSchemaUtils.js.map +1 -0
  27. package/lib/dataURItoBlob.d.ts +16 -0
  28. package/lib/dataURItoBlob.js +43 -0
  29. package/lib/dataURItoBlob.js.map +1 -0
  30. package/lib/deepEquals.d.ts +8 -0
  31. package/lib/deepEquals.js +19 -0
  32. package/lib/deepEquals.js.map +1 -0
  33. package/lib/englishStringTranslator.d.ts +10 -0
  34. package/lib/englishStringTranslator.js +13 -0
  35. package/lib/englishStringTranslator.js.map +1 -0
  36. package/lib/enumOptionsDeselectValue.d.ts +14 -0
  37. package/lib/enumOptionsDeselectValue.js +22 -0
  38. package/lib/enumOptionsDeselectValue.js.map +1 -0
  39. package/lib/enumOptionsIndexForValue.d.ts +13 -0
  40. package/lib/enumOptionsIndexForValue.js +22 -0
  41. package/lib/enumOptionsIndexForValue.js.map +1 -0
  42. package/lib/enumOptionsIsSelected.d.ts +8 -0
  43. package/lib/enumOptionsIsSelected.js +14 -0
  44. package/lib/enumOptionsIsSelected.js.map +1 -0
  45. package/lib/enumOptionsSelectValue.d.ts +10 -0
  46. package/lib/enumOptionsSelectValue.js +23 -0
  47. package/lib/enumOptionsSelectValue.js.map +1 -0
  48. package/lib/enumOptionsValueForIndex.d.ts +13 -0
  49. package/lib/enumOptionsValueForIndex.js +21 -0
  50. package/lib/enumOptionsValueForIndex.js.map +1 -0
  51. package/lib/enums.d.ts +72 -0
  52. package/lib/enums.js +76 -0
  53. package/lib/enums.js.map +1 -0
  54. package/lib/findSchemaDefinition.d.ts +20 -0
  55. package/lib/findSchemaDefinition.js +49 -0
  56. package/lib/findSchemaDefinition.js.map +1 -0
  57. package/lib/getDiscriminatorFieldFromSchema.d.ts +8 -0
  58. package/lib/getDiscriminatorFieldFromSchema.js +20 -0
  59. package/lib/getDiscriminatorFieldFromSchema.js.map +1 -0
  60. package/lib/getInputProps.d.ts +10 -0
  61. package/lib/getInputProps.js +41 -0
  62. package/lib/getInputProps.js.map +1 -0
  63. package/lib/getSchemaType.d.ts +13 -0
  64. package/lib/getSchemaType.js +29 -0
  65. package/lib/getSchemaType.js.map +1 -0
  66. package/lib/getSubmitButtonOptions.d.ts +10 -0
  67. package/lib/getSubmitButtonOptions.js +25 -0
  68. package/lib/getSubmitButtonOptions.js.map +1 -0
  69. package/lib/getTemplate.d.ts +10 -0
  70. package/lib/getTemplate.js +19 -0
  71. package/lib/getTemplate.js.map +1 -0
  72. package/lib/getUiOptions.d.ts +9 -0
  73. package/lib/getUiOptions.js +25 -0
  74. package/lib/getUiOptions.js.map +1 -0
  75. package/lib/getWidget.d.ts +13 -0
  76. package/lib/getWidget.js +118 -0
  77. package/lib/getWidget.js.map +1 -0
  78. package/lib/guessType.d.ts +7 -0
  79. package/lib/guessType.js +29 -0
  80. package/lib/guessType.js.map +1 -0
  81. package/lib/hasWidget.d.ts +10 -0
  82. package/lib/hasWidget.js +23 -0
  83. package/lib/hasWidget.js.map +1 -0
  84. package/lib/hashForSchema.d.ts +8 -0
  85. package/lib/hashForSchema.js +29 -0
  86. package/lib/hashForSchema.js.map +1 -0
  87. package/lib/idGenerators.d.ts +47 -0
  88. package/lib/idGenerators.js +73 -0
  89. package/lib/idGenerators.js.map +1 -0
  90. package/lib/index.d.ts +57 -0
  91. package/lib/index.js +58 -0
  92. package/lib/index.js.map +1 -0
  93. package/lib/isConstant.d.ts +8 -0
  94. package/lib/isConstant.js +11 -0
  95. package/lib/isConstant.js.map +1 -0
  96. package/lib/isCustomWidget.d.ts +7 -0
  97. package/lib/isCustomWidget.js +13 -0
  98. package/lib/isCustomWidget.js.map +1 -0
  99. package/lib/isFixedItems.d.ts +8 -0
  100. package/lib/isFixedItems.js +11 -0
  101. package/lib/isFixedItems.js.map +1 -0
  102. package/lib/isObject.d.ts +7 -0
  103. package/lib/isObject.js +16 -0
  104. package/lib/isObject.js.map +1 -0
  105. package/lib/labelValue.d.ts +13 -0
  106. package/lib/labelValue.js +4 -0
  107. package/lib/labelValue.js.map +1 -0
  108. package/lib/localToUTC.d.ts +6 -0
  109. package/lib/localToUTC.js +9 -0
  110. package/lib/localToUTC.js.map +1 -0
  111. package/lib/mergeDefaultsWithFormData.d.ts +17 -0
  112. package/lib/mergeDefaultsWithFormData.js +43 -0
  113. package/lib/mergeDefaultsWithFormData.js.map +1 -0
  114. package/lib/mergeObjects.d.ts +11 -0
  115. package/lib/mergeObjects.js +35 -0
  116. package/lib/mergeObjects.js.map +1 -0
  117. package/lib/mergeSchemas.d.ts +10 -0
  118. package/lib/mergeSchemas.js +35 -0
  119. package/lib/mergeSchemas.js.map +1 -0
  120. package/lib/optionsList.d.ts +10 -0
  121. package/lib/optionsList.js +36 -0
  122. package/lib/optionsList.js.map +1 -0
  123. package/lib/orderProperties.d.ts +11 -0
  124. package/lib/orderProperties.js +38 -0
  125. package/lib/orderProperties.js.map +1 -0
  126. package/lib/pad.d.ts +7 -0
  127. package/lib/pad.js +14 -0
  128. package/lib/pad.js.map +1 -0
  129. package/lib/parseDateString.d.ts +9 -0
  130. package/lib/parseDateString.js +32 -0
  131. package/lib/parseDateString.js.map +1 -0
  132. package/lib/parser/ParserValidator.d.ts +70 -0
  133. package/lib/parser/ParserValidator.js +93 -0
  134. package/lib/parser/ParserValidator.js.map +1 -0
  135. package/lib/parser/index.d.ts +4 -0
  136. package/lib/parser/index.js +3 -0
  137. package/lib/parser/index.js.map +1 -0
  138. package/lib/parser/schemaParser.d.ts +9 -0
  139. package/lib/parser/schemaParser.js +48 -0
  140. package/lib/parser/schemaParser.js.map +1 -0
  141. package/lib/rangeSpec.d.ts +9 -0
  142. package/lib/rangeSpec.js +20 -0
  143. package/lib/rangeSpec.js.map +1 -0
  144. package/lib/replaceStringParameters.d.ts +9 -0
  145. package/lib/replaceStringParameters.js +23 -0
  146. package/lib/replaceStringParameters.js.map +1 -0
  147. package/lib/schema/getClosestMatchingOption.d.ts +49 -0
  148. package/lib/schema/getClosestMatchingOption.js +154 -0
  149. package/lib/schema/getClosestMatchingOption.js.map +1 -0
  150. package/lib/schema/getDefaultFormState.d.ts +66 -0
  151. package/lib/schema/getDefaultFormState.js +351 -0
  152. package/lib/schema/getDefaultFormState.js.map +1 -0
  153. package/lib/schema/getDisplayLabel.d.ts +12 -0
  154. package/lib/schema/getDisplayLabel.js +39 -0
  155. package/lib/schema/getDisplayLabel.js.map +1 -0
  156. package/lib/schema/getFirstMatchingOption.d.ts +13 -0
  157. package/lib/schema/getFirstMatchingOption.js +16 -0
  158. package/lib/schema/getFirstMatchingOption.js.map +1 -0
  159. package/lib/schema/getMatchingOption.d.ts +14 -0
  160. package/lib/schema/getMatchingOption.js +80 -0
  161. package/lib/schema/getMatchingOption.js.map +1 -0
  162. package/lib/schema/index.d.ts +14 -0
  163. package/lib/schema/index.js +15 -0
  164. package/lib/schema/index.js.map +1 -0
  165. package/lib/schema/isFilesArray.d.ts +10 -0
  166. package/lib/schema/isFilesArray.js +21 -0
  167. package/lib/schema/isFilesArray.js.map +1 -0
  168. package/lib/schema/isMultiSelect.d.ts +9 -0
  169. package/lib/schema/isMultiSelect.js +15 -0
  170. package/lib/schema/isMultiSelect.js.map +1 -0
  171. package/lib/schema/isSelect.d.ts +9 -0
  172. package/lib/schema/isSelect.js +21 -0
  173. package/lib/schema/isSelect.js.map +1 -0
  174. package/lib/schema/mergeValidationData.d.ts +14 -0
  175. package/lib/schema/mergeValidationData.js +28 -0
  176. package/lib/schema/mergeValidationData.js.map +1 -0
  177. package/lib/schema/retrieveSchema.d.ts +170 -0
  178. package/lib/schema/retrieveSchema.js +437 -0
  179. package/lib/schema/retrieveSchema.js.map +1 -0
  180. package/lib/schema/sanitizeDataForNewSchema.d.ts +49 -0
  181. package/lib/schema/sanitizeDataForNewSchema.js +173 -0
  182. package/lib/schema/sanitizeDataForNewSchema.js.map +1 -0
  183. package/lib/schema/toIdSchema.d.ts +13 -0
  184. package/lib/schema/toIdSchema.js +59 -0
  185. package/lib/schema/toIdSchema.js.map +1 -0
  186. package/lib/schema/toPathSchema.d.ts +11 -0
  187. package/lib/schema/toPathSchema.js +68 -0
  188. package/lib/schema/toPathSchema.js.map +1 -0
  189. package/lib/schemaRequiresTrueValue.d.ts +11 -0
  190. package/lib/schemaRequiresTrueValue.js +34 -0
  191. package/lib/schemaRequiresTrueValue.js.map +1 -0
  192. package/lib/shouldRender.d.ts +10 -0
  193. package/lib/shouldRender.js +14 -0
  194. package/lib/shouldRender.js.map +1 -0
  195. package/lib/toConstant.d.ts +9 -0
  196. package/lib/toConstant.js +18 -0
  197. package/lib/toConstant.js.map +1 -0
  198. package/lib/toDateString.d.ts +9 -0
  199. package/lib/toDateString.js +14 -0
  200. package/lib/toDateString.js.map +1 -0
  201. package/lib/toErrorList.d.ts +8 -0
  202. package/lib/toErrorList.js +34 -0
  203. package/lib/toErrorList.js.map +1 -0
  204. package/lib/toErrorSchema.d.ts +21 -0
  205. package/lib/toErrorSchema.js +41 -0
  206. package/lib/toErrorSchema.js.map +1 -0
  207. package/lib/types.d.ts +982 -0
  208. package/lib/types.js +2 -0
  209. package/lib/types.js.map +1 -0
  210. package/lib/unwrapErrorHandler.d.ts +7 -0
  211. package/lib/unwrapErrorHandler.js +21 -0
  212. package/lib/unwrapErrorHandler.js.map +1 -0
  213. package/lib/utcToLocal.d.ts +6 -0
  214. package/lib/utcToLocal.js +26 -0
  215. package/lib/utcToLocal.js.map +1 -0
  216. package/lib/validationDataMerge.d.ts +11 -0
  217. package/lib/validationDataMerge.js +26 -0
  218. package/lib/validationDataMerge.js.map +1 -0
  219. package/lib/withIdRefPrefix.d.ts +8 -0
  220. package/lib/withIdRefPrefix.js +47 -0
  221. package/lib/withIdRefPrefix.js.map +1 -0
  222. package/package.json +20 -13
  223. package/src/ErrorSchemaBuilder.ts +112 -0
  224. package/src/allowAdditionalItems.ts +15 -0
  225. package/src/asNumber.ts +38 -0
  226. package/src/canExpand.ts +31 -0
  227. package/src/constants.ts +31 -0
  228. package/src/createErrorHandler.ts +33 -0
  229. package/src/createSchemaUtils.ts +298 -0
  230. package/src/dataURItoBlob.ts +42 -0
  231. package/src/deepEquals.ts +19 -0
  232. package/src/englishStringTranslator.ts +14 -0
  233. package/src/enumOptionsDeselectValue.ts +28 -0
  234. package/src/enumOptionsIndexForValue.ts +27 -0
  235. package/src/enumOptionsIsSelected.ts +19 -0
  236. package/src/enumOptionsSelectValue.ts +28 -0
  237. package/src/enumOptionsValueForIndex.ts +26 -0
  238. package/src/enums.ts +74 -0
  239. package/src/findSchemaDefinition.ts +54 -0
  240. package/src/getDiscriminatorFieldFromSchema.ts +21 -0
  241. package/src/getInputProps.ts +55 -0
  242. package/src/getSchemaType.ts +37 -0
  243. package/src/getSubmitButtonOptions.ts +32 -0
  244. package/src/getTemplate.ts +26 -0
  245. package/src/getUiOptions.ts +32 -0
  246. package/src/getWidget.tsx +133 -0
  247. package/src/guessType.ts +28 -0
  248. package/src/hasWidget.ts +27 -0
  249. package/src/hashForSchema.ts +31 -0
  250. package/src/idGenerators.ts +81 -0
  251. package/src/index.ts +118 -0
  252. package/src/isConstant.ts +12 -0
  253. package/src/isCustomWidget.ts +19 -0
  254. package/src/isFixedItems.ts +12 -0
  255. package/src/isObject.ts +15 -0
  256. package/src/labelValue.ts +16 -0
  257. package/src/localToUTC.ts +8 -0
  258. package/src/mergeDefaultsWithFormData.ts +53 -0
  259. package/src/mergeObjects.ts +39 -0
  260. package/src/mergeSchemas.ts +38 -0
  261. package/src/optionsList.ts +41 -0
  262. package/src/orderProperties.ts +44 -0
  263. package/src/pad.ts +13 -0
  264. package/src/parseDateString.ts +33 -0
  265. package/src/parser/ParserValidator.ts +132 -0
  266. package/src/parser/index.ts +6 -0
  267. package/src/parser/schemaParser.ts +60 -0
  268. package/src/rangeSpec.ts +22 -0
  269. package/src/replaceStringParameters.ts +22 -0
  270. package/src/schema/getClosestMatchingOption.ts +191 -0
  271. package/src/schema/getDefaultFormState.ts +447 -0
  272. package/src/schema/getDisplayLabel.ts +59 -0
  273. package/src/schema/getFirstMatchingOption.ts +27 -0
  274. package/src/schema/getMatchingOption.ts +95 -0
  275. package/src/schema/index.ts +29 -0
  276. package/src/schema/isFilesArray.ts +27 -0
  277. package/src/schema/isMultiSelect.ts +21 -0
  278. package/src/schema/isSelect.ts +26 -0
  279. package/src/schema/mergeValidationData.ts +38 -0
  280. package/src/schema/retrieveSchema.ts +614 -0
  281. package/src/schema/sanitizeDataForNewSchema.ts +197 -0
  282. package/src/schema/toIdSchema.ts +105 -0
  283. package/src/schema/toPathSchema.ts +121 -0
  284. package/src/schemaRequiresTrueValue.ts +40 -0
  285. package/src/shouldRender.ts +16 -0
  286. package/src/toConstant.ts +19 -0
  287. package/src/toDateString.ts +15 -0
  288. package/src/toErrorList.ts +41 -0
  289. package/src/toErrorSchema.ts +43 -0
  290. package/src/types.ts +1139 -0
  291. package/src/unwrapErrorHandler.ts +25 -0
  292. package/src/utcToLocal.ts +30 -0
  293. package/src/validationDataMerge.ts +31 -0
  294. package/src/withIdRefPrefix.ts +49 -0
  295. package/dist/index.d.ts +0 -1911
  296. package/dist/utils.cjs.development.js +0 -3522
  297. package/dist/utils.cjs.development.js.map +0 -1
  298. package/dist/utils.cjs.production.min.js +0 -2
  299. package/dist/utils.cjs.production.min.js.map +0 -1
  300. package/dist/utils.umd.development.js +0 -3504
  301. package/dist/utils.umd.development.js.map +0 -1
  302. package/dist/utils.umd.production.min.js +0 -2
  303. package/dist/utils.umd.production.min.js.map +0 -1
@@ -0,0 +1,32 @@
1
+ /** Parses the `dateString` into a `DateObject`, including the time information when `includeTime` is true
2
+ *
3
+ * @param dateString - The date string to parse into a DateObject
4
+ * @param [includeTime=true] - Optional flag, if false, will not include the time data into the object
5
+ * @returns - The date string converted to a `DateObject`
6
+ * @throws - Error when the date cannot be parsed from the string
7
+ */
8
+ export default function parseDateString(dateString, includeTime = true) {
9
+ if (!dateString) {
10
+ return {
11
+ year: -1,
12
+ month: -1,
13
+ day: -1,
14
+ hour: includeTime ? -1 : 0,
15
+ minute: includeTime ? -1 : 0,
16
+ second: includeTime ? -1 : 0,
17
+ };
18
+ }
19
+ const date = new Date(dateString);
20
+ if (Number.isNaN(date.getTime())) {
21
+ throw new Error('Unable to parse date ' + dateString);
22
+ }
23
+ return {
24
+ year: date.getUTCFullYear(),
25
+ month: date.getUTCMonth() + 1,
26
+ day: date.getUTCDate(),
27
+ hour: includeTime ? date.getUTCHours() : 0,
28
+ minute: includeTime ? date.getUTCMinutes() : 0,
29
+ second: includeTime ? date.getUTCSeconds() : 0,
30
+ };
31
+ }
32
+ //# sourceMappingURL=parseDateString.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parseDateString.js","sourceRoot":"","sources":["../src/parseDateString.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,UAAmB,EAAE,WAAW,GAAG,IAAI;IAC7E,IAAI,CAAC,UAAU,EAAE;QACf,OAAO;YACL,IAAI,EAAE,CAAC,CAAC;YACR,KAAK,EAAE,CAAC,CAAC;YACT,GAAG,EAAE,CAAC,CAAC;YACP,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5B,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAC7B,CAAC;KACH;IACD,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,UAAU,CAAC,CAAC;IAClC,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,EAAE;QAChC,MAAM,IAAI,KAAK,CAAC,uBAAuB,GAAG,UAAU,CAAC,CAAC;KACvD;IACD,OAAO;QACL,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE;QAC3B,KAAK,EAAE,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC;QAC7B,GAAG,EAAE,IAAI,CAAC,UAAU,EAAE;QACtB,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC;QAC1C,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,CAAC;QAC9C,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,CAAC;KAC/C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,70 @@
1
+ import { CustomValidator, ErrorSchema, ErrorTransformer, FormContextType, RJSFSchema, RJSFValidationError, StrictRJSFSchema, UiSchema, ValidationData, ValidatorType } from '../types';
2
+ /** The type of the map of schema hash to schema
3
+ */
4
+ export type SchemaMap<S extends StrictRJSFSchema = RJSFSchema> = {
5
+ [hash: string]: S;
6
+ };
7
+ /** An implementation of the `ValidatorType` interface that is designed for use in capturing schemas used by the
8
+ * `isValid()` function. The rest of the implementation of the interface throws errors when it is attempted to be used.
9
+ * An instance of the object allows the caller to capture the schemas used in calls to the `isValid()` function. These
10
+ * captured schema, along with the root schema used to construct the object are stored in the map of schemas keyed by
11
+ * the hashed value of the schema. NOTE: After hashing the schema, an $id with the hash value is added to the
12
+ * schema IF that schema doesn't already have an $id, prior to putting the schema into the map.
13
+ */
14
+ export default class ParserValidator<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> implements ValidatorType<T, S, F> {
15
+ /** The rootSchema provided during construction of the class */
16
+ readonly rootSchema: S;
17
+ /** The map of schemas encountered by the ParserValidator */
18
+ schemaMap: SchemaMap<S>;
19
+ /** Construct the ParserValidator for the given `rootSchema`. This `rootSchema` will be stashed in the `schemaMap`
20
+ * first.
21
+ *
22
+ * @param rootSchema - The root schema against which this validator will be executed
23
+ */
24
+ constructor(rootSchema: S);
25
+ /** Adds the given `schema` to the `schemaMap` keyed by the `hash` or `ID_KEY` if present on the `schema`. If the
26
+ * schema does not have an `ID_KEY`, then the `hash` will be added as the `ID_KEY` to allow the schema to be
27
+ * associated with it's `hash` for future use (by a schema compiler).
28
+ *
29
+ * @param schema - The schema which is to be added to the map
30
+ * @param hash - The hash value at which to map the schema
31
+ */
32
+ addSchema(schema: S, hash: string): void;
33
+ /** Returns the current `schemaMap` to the caller
34
+ */
35
+ getSchemaMap(): SchemaMap<S>;
36
+ /** Implements the `ValidatorType` `isValid()` method to capture the `schema` in the `schemaMap`. Throws an error when
37
+ * the `rootSchema` is not the same as the root schema provided during construction.
38
+ *
39
+ * @param schema - The schema to record in the `schemaMap`
40
+ * @param _formData - The formData parameter that is ignored
41
+ * @param rootSchema - The root schema associated with the schema
42
+ * @throws - Error when the given `rootSchema` differs from the root schema provided during construction
43
+ */
44
+ isValid(schema: S, _formData: T, rootSchema: S): boolean;
45
+ /** Implements the `ValidatorType` `rawValidation()` method to throw an error since it is never supposed to be called
46
+ *
47
+ * @param _schema - The schema parameter that is ignored
48
+ * @param _formData - The formData parameter that is ignored
49
+ */
50
+ rawValidation<Result = any>(_schema: S, _formData?: T): {
51
+ errors?: Result[];
52
+ validationError?: Error;
53
+ };
54
+ /** Implements the `ValidatorType` `toErrorList()` method to throw an error since it is never supposed to be called
55
+ *
56
+ * @param _errorSchema - The error schema parameter that is ignored
57
+ * @param _fieldPath - The field path parameter that is ignored
58
+ */
59
+ toErrorList(_errorSchema?: ErrorSchema<T>, _fieldPath?: string[]): RJSFValidationError[];
60
+ /** Implements the `ValidatorType` `validateFormData()` method to throw an error since it is never supposed to be
61
+ * called
62
+ *
63
+ * @param _formData - The formData parameter that is ignored
64
+ * @param _schema - The schema parameter that is ignored
65
+ * @param _customValidate - The customValidate parameter that is ignored
66
+ * @param _transformErrors - The transformErrors parameter that is ignored
67
+ * @param _uiSchema - The uiSchema parameter that is ignored
68
+ */
69
+ validateFormData(_formData: T, _schema: S, _customValidate?: CustomValidator<T, S, F>, _transformErrors?: ErrorTransformer<T, S, F>, _uiSchema?: UiSchema<T, S, F>): ValidationData<T>;
70
+ }
@@ -0,0 +1,93 @@
1
+ import get from 'lodash/get';
2
+ import isEqual from 'lodash/isEqual';
3
+ import { ID_KEY } from '../constants';
4
+ import hashForSchema from '../hashForSchema';
5
+ /** An implementation of the `ValidatorType` interface that is designed for use in capturing schemas used by the
6
+ * `isValid()` function. The rest of the implementation of the interface throws errors when it is attempted to be used.
7
+ * An instance of the object allows the caller to capture the schemas used in calls to the `isValid()` function. These
8
+ * captured schema, along with the root schema used to construct the object are stored in the map of schemas keyed by
9
+ * the hashed value of the schema. NOTE: After hashing the schema, an $id with the hash value is added to the
10
+ * schema IF that schema doesn't already have an $id, prior to putting the schema into the map.
11
+ */
12
+ export default class ParserValidator {
13
+ /** Construct the ParserValidator for the given `rootSchema`. This `rootSchema` will be stashed in the `schemaMap`
14
+ * first.
15
+ *
16
+ * @param rootSchema - The root schema against which this validator will be executed
17
+ */
18
+ constructor(rootSchema) {
19
+ /** The map of schemas encountered by the ParserValidator */
20
+ this.schemaMap = {};
21
+ this.rootSchema = rootSchema;
22
+ this.addSchema(rootSchema, hashForSchema(rootSchema));
23
+ }
24
+ /** Adds the given `schema` to the `schemaMap` keyed by the `hash` or `ID_KEY` if present on the `schema`. If the
25
+ * schema does not have an `ID_KEY`, then the `hash` will be added as the `ID_KEY` to allow the schema to be
26
+ * associated with it's `hash` for future use (by a schema compiler).
27
+ *
28
+ * @param schema - The schema which is to be added to the map
29
+ * @param hash - The hash value at which to map the schema
30
+ */
31
+ addSchema(schema, hash) {
32
+ const key = get(schema, ID_KEY, hash);
33
+ const identifiedSchema = Object.assign(Object.assign({}, schema), { [ID_KEY]: key });
34
+ const existing = this.schemaMap[key];
35
+ if (!existing) {
36
+ this.schemaMap[key] = identifiedSchema;
37
+ }
38
+ else if (!isEqual(existing, identifiedSchema)) {
39
+ console.error('existing schema:', JSON.stringify(existing, null, 2));
40
+ console.error('new schema:', JSON.stringify(identifiedSchema, null, 2));
41
+ 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`);
42
+ }
43
+ }
44
+ /** Returns the current `schemaMap` to the caller
45
+ */
46
+ getSchemaMap() {
47
+ return this.schemaMap;
48
+ }
49
+ /** Implements the `ValidatorType` `isValid()` method to capture the `schema` in the `schemaMap`. Throws an error when
50
+ * the `rootSchema` is not the same as the root schema provided during construction.
51
+ *
52
+ * @param schema - The schema to record in the `schemaMap`
53
+ * @param _formData - The formData parameter that is ignored
54
+ * @param rootSchema - The root schema associated with the schema
55
+ * @throws - Error when the given `rootSchema` differs from the root schema provided during construction
56
+ */
57
+ isValid(schema, _formData, rootSchema) {
58
+ if (!isEqual(rootSchema, this.rootSchema)) {
59
+ throw new Error('Unexpectedly calling isValid() with a rootSchema that differs from the construction rootSchema');
60
+ }
61
+ this.addSchema(schema, hashForSchema(schema));
62
+ return false;
63
+ }
64
+ /** Implements the `ValidatorType` `rawValidation()` method to throw an error since it is never supposed to be called
65
+ *
66
+ * @param _schema - The schema parameter that is ignored
67
+ * @param _formData - The formData parameter that is ignored
68
+ */
69
+ rawValidation(_schema, _formData) {
70
+ throw new Error('Unexpectedly calling the `rawValidation()` method during schema parsing');
71
+ }
72
+ /** Implements the `ValidatorType` `toErrorList()` method to throw an error since it is never supposed to be called
73
+ *
74
+ * @param _errorSchema - The error schema parameter that is ignored
75
+ * @param _fieldPath - The field path parameter that is ignored
76
+ */
77
+ toErrorList(_errorSchema, _fieldPath) {
78
+ throw new Error('Unexpectedly calling the `toErrorList()` method during schema parsing');
79
+ }
80
+ /** Implements the `ValidatorType` `validateFormData()` method to throw an error since it is never supposed to be
81
+ * called
82
+ *
83
+ * @param _formData - The formData parameter that is ignored
84
+ * @param _schema - The schema parameter that is ignored
85
+ * @param _customValidate - The customValidate parameter that is ignored
86
+ * @param _transformErrors - The transformErrors parameter that is ignored
87
+ * @param _uiSchema - The uiSchema parameter that is ignored
88
+ */
89
+ validateFormData(_formData, _schema, _customValidate, _transformErrors, _uiSchema) {
90
+ throw new Error('Unexpectedly calling the `validateFormData()` method during schema parsing');
91
+ }
92
+ }
93
+ //# sourceMappingURL=ParserValidator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ParserValidator.js","sourceRoot":"","sources":["../../src/parser/ParserValidator.ts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,YAAY,CAAC;AAC7B,OAAO,OAAO,MAAM,gBAAgB,CAAC;AAErC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,aAAa,MAAM,kBAAkB,CAAC;AAoB7C;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,OAAO,eAAe;IASlC;;;;OAIG;IACH,YAAY,UAAa;QARzB,4DAA4D;QAC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a,CAAI,MAAM,CAAC,CAAC,CAAC;QAEjD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;OAIG;IACH,aAAa,CAAe,OAAU,EAAE,SAAa;QACnD,MAAM,IAAI,KAAK,CAAC,yEAAyE,CAAC,CAAC;IAC7F,CAAC;IAED;;;;OAIG;IACH,WAAW,CAAC,YAA6B,EAAE,UAAqB;QAC9D,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;IAC3F,CAAC;IAED;;;;;;;;OAQG;IACH,gBAAgB,CACd,SAAY,EACZ,OAAU,EACV,eAA0C,EAC1C,gBAA4C,EAC5C,SAA6B;QAE7B,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;IAChG,CAAC;CACF"}
@@ -0,0 +1,4 @@
1
+ import schemaParser from './schemaParser';
2
+ import { SchemaMap } from './ParserValidator';
3
+ export type { SchemaMap };
4
+ export { schemaParser };
@@ -0,0 +1,3 @@
1
+ import schemaParser from './schemaParser';
2
+ export { schemaParser };
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/parser/index.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,gBAAgB,CAAC;AAK1C,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { FormContextType, RJSFSchema, StrictRJSFSchema } from '../types';
2
+ import { SchemaMap } from './ParserValidator';
3
+ /** Parses the given `rootSchema` to extract out all the sub-schemas that maybe contained within it. Returns a map of
4
+ * the hash of the schema to schema/sub-schema.
5
+ *
6
+ * @param rootSchema - The root schema to parse for sub-schemas used by `isValid()` calls
7
+ * @returns - The `SchemaMap` of all schemas that were parsed
8
+ */
9
+ export default function schemaParser<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(rootSchema: S): SchemaMap<S>;
@@ -0,0 +1,48 @@
1
+ import forEach from 'lodash/forEach';
2
+ import isEqual from 'lodash/isEqual';
3
+ import { PROPERTIES_KEY, ITEMS_KEY } from '../constants';
4
+ import ParserValidator from './ParserValidator';
5
+ import { retrieveSchemaInternal, resolveAnyOrOneOfSchemas } from '../schema/retrieveSchema';
6
+ /** Recursive function used to parse the given `schema` belonging to the `rootSchema`. The `validator` is used to
7
+ * capture the sub-schemas that the `isValid()` function is called with. For each schema returned by the
8
+ * `retrieveSchemaInternal()`, the `resolveAnyOrOneOfSchemas()` function is called. For each of the schemas returned
9
+ * from THAT call have `properties`, then each of the sub-schema property objects are then recursively parsed.
10
+ *
11
+ * @param validator - The `ParserValidator` implementation used to capture `isValid()` calls during parsing
12
+ * @param recurseList - The list of schemas returned from the `retrieveSchemaInternal`, preventing infinite recursion
13
+ * @param rootSchema - The root schema from which the schema parsing began
14
+ * @param schema - The current schema element being parsed
15
+ */
16
+ function parseSchema(validator, recurseList, rootSchema, schema) {
17
+ const schemas = retrieveSchemaInternal(validator, schema, rootSchema, undefined, true);
18
+ schemas.forEach((schema) => {
19
+ const sameSchemaIndex = recurseList.findIndex((item) => isEqual(item, schema));
20
+ if (sameSchemaIndex === -1) {
21
+ recurseList.push(schema);
22
+ const allOptions = resolveAnyOrOneOfSchemas(validator, schema, rootSchema, true);
23
+ allOptions.forEach((s) => {
24
+ if (PROPERTIES_KEY in s && s[PROPERTIES_KEY]) {
25
+ forEach(schema[PROPERTIES_KEY], (value) => {
26
+ parseSchema(validator, recurseList, rootSchema, value);
27
+ });
28
+ }
29
+ });
30
+ if (ITEMS_KEY in schema && !Array.isArray(schema.items) && typeof schema.items !== 'boolean') {
31
+ parseSchema(validator, recurseList, rootSchema, schema.items);
32
+ }
33
+ }
34
+ });
35
+ }
36
+ /** Parses the given `rootSchema` to extract out all the sub-schemas that maybe contained within it. Returns a map of
37
+ * the hash of the schema to schema/sub-schema.
38
+ *
39
+ * @param rootSchema - The root schema to parse for sub-schemas used by `isValid()` calls
40
+ * @returns - The `SchemaMap` of all schemas that were parsed
41
+ */
42
+ export default function schemaParser(rootSchema) {
43
+ const validator = new ParserValidator(rootSchema);
44
+ const recurseList = [];
45
+ parseSchema(validator, recurseList, rootSchema, rootSchema);
46
+ return validator.getSchemaMap();
47
+ }
48
+ //# sourceMappingURL=schemaParser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaParser.js","sourceRoot":"","sources":["../../src/parser/schemaParser.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,gBAAgB,CAAC;AACrC,OAAO,OAAO,MAAM,gBAAgB,CAAC;AAGrC,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,eAA8B,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAE5F;;;;;;;;;GASG;AACH,SAAS,WAAW,CAClB,SAAmC,EACnC,WAAgB,EAChB,UAAa,EACb,MAAS;IAET,MAAM,OAAO,GAAG,sBAAsB,CAAU,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IAChG,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QACzB,MAAM,eAAe,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;QAC/E,IAAI,eAAe,KAAK,CAAC,CAAC,EAAE;YAC1B,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACzB,MAAM,UAAU,GAAG,wBAAwB,CAAU,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;YAC1F,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;gBACvB,IAAI,cAAc,IAAI,CAAC,IAAI,CAAC,CAAC,cAAc,CAAC,EAAE;oBAC5C,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;wBACxC,WAAW,CAAU,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,KAAU,CAAC,CAAC;oBACvE,CAAC,CAAC,CAAC;iBACJ;YACH,CAAC,CAAC,CAAC;YACH,IAAI,SAAS,IAAI,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,SAAS,EAAE;gBAC5F,WAAW,CAAU,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,CAAC,KAAU,CAAC,CAAC;aAC7E;SACF;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,UAAa;IAEb,MAAM,SAAS,GAAG,IAAI,eAAe,CAAU,UAAU,CAAC,CAAC;IAC3D,MAAM,WAAW,GAAQ,EAAE,CAAC;IAE5B,WAAW,CAAC,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC;IAE5D,OAAO,SAAS,CAAC,YAAY,EAAE,CAAC;AAClC,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { RangeSpecType, StrictRJSFSchema } from './types';
2
+ import { RJSFSchema } from './types';
3
+ /** Extracts the range spec information `{ step?: number, min?: number, max?: number }` that can be spread onto an HTML
4
+ * input from the range analog in the schema `{ multipleOf?: number, minimum?: number, maximum?: number }`.
5
+ *
6
+ * @param schema - The schema from which to extract the range spec
7
+ * @returns - A range specification from the schema
8
+ */
9
+ export default function rangeSpec<S extends StrictRJSFSchema = RJSFSchema>(schema: S): RangeSpecType;
@@ -0,0 +1,20 @@
1
+ /** Extracts the range spec information `{ step?: number, min?: number, max?: number }` that can be spread onto an HTML
2
+ * input from the range analog in the schema `{ multipleOf?: number, minimum?: number, maximum?: number }`.
3
+ *
4
+ * @param schema - The schema from which to extract the range spec
5
+ * @returns - A range specification from the schema
6
+ */
7
+ export default function rangeSpec(schema) {
8
+ const spec = {};
9
+ if (schema.multipleOf) {
10
+ spec.step = schema.multipleOf;
11
+ }
12
+ if (schema.minimum || schema.minimum === 0) {
13
+ spec.min = schema.minimum;
14
+ }
15
+ if (schema.maximum || schema.maximum === 0) {
16
+ spec.max = schema.maximum;
17
+ }
18
+ return spec;
19
+ }
20
+ //# sourceMappingURL=rangeSpec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rangeSpec.js","sourceRoot":"","sources":["../src/rangeSpec.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AACH,MAAM,CAAC,OAAO,UAAU,SAAS,CAA0C,MAAS;IAClF,MAAM,IAAI,GAAkB,EAAE,CAAC;IAC/B,IAAI,MAAM,CAAC,UAAU,EAAE;QACrB,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC;KAC/B;IACD,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,KAAK,CAAC,EAAE;QAC1C,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC;KAC3B;IACD,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,KAAK,CAAC,EAAE;QAC1C,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC;KAC3B;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,9 @@
1
+ /** Potentially substitutes all replaceable parameters with the associated value(s) from the `params` if available. When
2
+ * a `params` array is provided, each value in the array is used to replace any of the replaceable parameters in the
3
+ * `inputString` using the `%1`, `%2`, etc. replacement specifiers.
4
+ *
5
+ * @param inputString - The string which will be potentially updated with replacement parameters
6
+ * @param params - The optional list of replaceable parameter values to substitute into the english string
7
+ * @returns - The updated string with any replacement specifiers replaced
8
+ */
9
+ export default function replaceStringParameters(inputString: string, params?: string[]): string;
@@ -0,0 +1,23 @@
1
+ /** Potentially substitutes all replaceable parameters with the associated value(s) from the `params` if available. When
2
+ * a `params` array is provided, each value in the array is used to replace any of the replaceable parameters in the
3
+ * `inputString` using the `%1`, `%2`, etc. replacement specifiers.
4
+ *
5
+ * @param inputString - The string which will be potentially updated with replacement parameters
6
+ * @param params - The optional list of replaceable parameter values to substitute into the english string
7
+ * @returns - The updated string with any replacement specifiers replaced
8
+ */
9
+ export default function replaceStringParameters(inputString, params) {
10
+ let output = inputString;
11
+ if (Array.isArray(params)) {
12
+ const parts = output.split(/(%\d)/);
13
+ params.forEach((param, index) => {
14
+ const partIndex = parts.findIndex((part) => part === `%${index + 1}`);
15
+ if (partIndex >= 0) {
16
+ parts[partIndex] = param;
17
+ }
18
+ });
19
+ output = parts.join('');
20
+ }
21
+ return output;
22
+ }
23
+ //# sourceMappingURL=replaceStringParameters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replaceStringParameters.js","sourceRoot":"","sources":["../src/replaceStringParameters.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,CAAC,OAAO,UAAU,uBAAuB,CAAC,WAAmB,EAAE,MAAiB;IACpF,IAAI,MAAM,GAAG,WAAW,CAAC;IACzB,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACzB,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACpC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;YAC9B,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC;YACtE,IAAI,SAAS,IAAI,CAAC,EAAE;gBAClB,KAAK,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC;aAC1B;QACH,CAAC,CAAC,CAAC;QACH,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;KACzB;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,49 @@
1
+ import { FormContextType, RJSFSchema, StrictRJSFSchema, ValidatorType } from '../types';
2
+ /** A junk option used to determine when the getFirstMatchingOption call really matches an option rather than returning
3
+ * the first item
4
+ */
5
+ export declare const JUNK_OPTION: StrictRJSFSchema;
6
+ /** Recursive function that calculates the score of a `formData` against the given `schema`. The computation is fairly
7
+ * simple. Initially the total score is 0. When `schema.properties` object exists, then all the `key/value` pairs within
8
+ * the object are processed as follows after obtaining the formValue from `formData` using the `key`:
9
+ * - If the `value` contains a `$ref`, `calculateIndexScore()` is called recursively with the formValue and the new
10
+ * schema that is the result of the ref in the schema being resolved and that sub-schema's resulting score is added to
11
+ * the total.
12
+ * - If the `value` contains a `oneOf` and there is a formValue, then score based on the index returned from calling
13
+ * `getClosestMatchingOption()` of that oneOf.
14
+ * - If the type of the `value` is 'object', `calculateIndexScore()` is called recursively with the formValue and the
15
+ * `value` itself as the sub-schema, and the score is added to the total.
16
+ * - If the type of the `value` matches the guessed-type of the `formValue`, the score is incremented by 1, UNLESS the
17
+ * value has a `default` or `const`. In those case, if the `default` or `const` and the `formValue` match, the score
18
+ * is incremented by another 1 otherwise it is decremented by 1.
19
+ *
20
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
21
+ * @param rootSchema - The root JSON schema of the entire form
22
+ * @param schema - The schema for which the score is being calculated
23
+ * @param formData - The form data associated with the schema, used to calculate the score
24
+ * @returns - The score a schema against the formData
25
+ */
26
+ export declare function calculateIndexScore<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(validator: ValidatorType<T, S, F>, rootSchema: S, schema?: S, formData?: any): number;
27
+ /** Determines which of the given `options` provided most closely matches the `formData`. Using
28
+ * `getFirstMatchingOption()` to match two schemas that differ only by the readOnly, default or const value of a field
29
+ * based on the `formData` and returns 0 when there is no match. Rather than passing in all the `options` at once to
30
+ * this utility, instead an array of valid option indexes is created by iterating over the list of options, call
31
+ * `getFirstMatchingOptions` with a list of one junk option and one good option, seeing if the good option is considered
32
+ * matched.
33
+ *
34
+ * Once the list of valid indexes is created, if there is only one valid index, just return it. Otherwise, if there are
35
+ * no valid indexes, then fill the valid indexes array with the indexes of all the options. Next, the index of the
36
+ * option with the highest score is determined by iterating over the list of valid options, calling
37
+ * `calculateIndexScore()` on each, comparing it against the current best score, and returning the index of the one that
38
+ * eventually has the best score.
39
+ *
40
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
41
+ * @param rootSchema - The root JSON schema of the entire form
42
+ * @param formData - The form data associated with the schema
43
+ * @param options - The list of options that can be selected from
44
+ * @param [selectedOption=-1] - The index of the currently selected option, defaulted to -1 if not specified
45
+ * @param [discriminatorField] - The optional name of the field within the options object whose value is used to
46
+ * determine which option is selected
47
+ * @returns - The index of the option that is the closest match to the `formData` or the `selectedOption` if no match
48
+ */
49
+ export default function getClosestMatchingOption<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(validator: ValidatorType<T, S, F>, rootSchema: S, formData: T | undefined, options: S[], selectedOption?: number, discriminatorField?: string): number;
@@ -0,0 +1,154 @@
1
+ import get from 'lodash/get';
2
+ import has from 'lodash/has';
3
+ import isObject from 'lodash/isObject';
4
+ import isString from 'lodash/isString';
5
+ import reduce from 'lodash/reduce';
6
+ import times from 'lodash/times';
7
+ import getFirstMatchingOption from './getFirstMatchingOption';
8
+ import retrieveSchema, { resolveAllReferences } from './retrieveSchema';
9
+ import { ONE_OF_KEY, REF_KEY, JUNK_OPTION_ID, ANY_OF_KEY } from '../constants';
10
+ import guessType from '../guessType';
11
+ import getDiscriminatorFieldFromSchema from '../getDiscriminatorFieldFromSchema';
12
+ /** A junk option used to determine when the getFirstMatchingOption call really matches an option rather than returning
13
+ * the first item
14
+ */
15
+ export const JUNK_OPTION = {
16
+ type: 'object',
17
+ $id: JUNK_OPTION_ID,
18
+ properties: {
19
+ __not_really_there__: {
20
+ type: 'number',
21
+ },
22
+ },
23
+ };
24
+ /** Recursive function that calculates the score of a `formData` against the given `schema`. The computation is fairly
25
+ * simple. Initially the total score is 0. When `schema.properties` object exists, then all the `key/value` pairs within
26
+ * the object are processed as follows after obtaining the formValue from `formData` using the `key`:
27
+ * - If the `value` contains a `$ref`, `calculateIndexScore()` is called recursively with the formValue and the new
28
+ * schema that is the result of the ref in the schema being resolved and that sub-schema's resulting score is added to
29
+ * the total.
30
+ * - If the `value` contains a `oneOf` and there is a formValue, then score based on the index returned from calling
31
+ * `getClosestMatchingOption()` of that oneOf.
32
+ * - If the type of the `value` is 'object', `calculateIndexScore()` is called recursively with the formValue and the
33
+ * `value` itself as the sub-schema, and the score is added to the total.
34
+ * - If the type of the `value` matches the guessed-type of the `formValue`, the score is incremented by 1, UNLESS the
35
+ * value has a `default` or `const`. In those case, if the `default` or `const` and the `formValue` match, the score
36
+ * is incremented by another 1 otherwise it is decremented by 1.
37
+ *
38
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
39
+ * @param rootSchema - The root JSON schema of the entire form
40
+ * @param schema - The schema for which the score is being calculated
41
+ * @param formData - The form data associated with the schema, used to calculate the score
42
+ * @returns - The score a schema against the formData
43
+ */
44
+ export function calculateIndexScore(validator, rootSchema, schema, formData = {}) {
45
+ let totalScore = 0;
46
+ if (schema) {
47
+ if (isObject(schema.properties)) {
48
+ totalScore += reduce(schema.properties, (score, value, key) => {
49
+ const formValue = get(formData, key);
50
+ if (typeof value === 'boolean') {
51
+ return score;
52
+ }
53
+ if (has(value, REF_KEY)) {
54
+ const newSchema = retrieveSchema(validator, value, rootSchema, formValue);
55
+ return score + calculateIndexScore(validator, rootSchema, newSchema, formValue || {});
56
+ }
57
+ if ((has(value, ONE_OF_KEY) || has(value, ANY_OF_KEY)) && formValue) {
58
+ const key = has(value, ONE_OF_KEY) ? ONE_OF_KEY : ANY_OF_KEY;
59
+ const discriminator = getDiscriminatorFieldFromSchema(value);
60
+ return (score +
61
+ getClosestMatchingOption(validator, rootSchema, formValue, get(value, key), -1, discriminator));
62
+ }
63
+ if (value.type === 'object') {
64
+ return score + calculateIndexScore(validator, rootSchema, value, formValue || {});
65
+ }
66
+ if (value.type === guessType(formValue)) {
67
+ // If the types match, then we bump the score by one
68
+ let newScore = score + 1;
69
+ if (value.default) {
70
+ // If the schema contains a readonly default value score the value that matches the default higher and
71
+ // any non-matching value lower
72
+ newScore += formValue === value.default ? 1 : -1;
73
+ }
74
+ else if (value.const) {
75
+ // If the schema contains a const value score the value that matches the default higher and
76
+ // any non-matching value lower
77
+ newScore += formValue === value.const ? 1 : -1;
78
+ }
79
+ // TODO eventually, deal with enums/arrays
80
+ return newScore;
81
+ }
82
+ return score;
83
+ }, 0);
84
+ }
85
+ else if (isString(schema.type) && schema.type === guessType(formData)) {
86
+ totalScore += 1;
87
+ }
88
+ }
89
+ return totalScore;
90
+ }
91
+ /** Determines which of the given `options` provided most closely matches the `formData`. Using
92
+ * `getFirstMatchingOption()` to match two schemas that differ only by the readOnly, default or const value of a field
93
+ * based on the `formData` and returns 0 when there is no match. Rather than passing in all the `options` at once to
94
+ * this utility, instead an array of valid option indexes is created by iterating over the list of options, call
95
+ * `getFirstMatchingOptions` with a list of one junk option and one good option, seeing if the good option is considered
96
+ * matched.
97
+ *
98
+ * Once the list of valid indexes is created, if there is only one valid index, just return it. Otherwise, if there are
99
+ * no valid indexes, then fill the valid indexes array with the indexes of all the options. Next, the index of the
100
+ * option with the highest score is determined by iterating over the list of valid options, calling
101
+ * `calculateIndexScore()` on each, comparing it against the current best score, and returning the index of the one that
102
+ * eventually has the best score.
103
+ *
104
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
105
+ * @param rootSchema - The root JSON schema of the entire form
106
+ * @param formData - The form data associated with the schema
107
+ * @param options - The list of options that can be selected from
108
+ * @param [selectedOption=-1] - The index of the currently selected option, defaulted to -1 if not specified
109
+ * @param [discriminatorField] - The optional name of the field within the options object whose value is used to
110
+ * determine which option is selected
111
+ * @returns - The index of the option that is the closest match to the `formData` or the `selectedOption` if no match
112
+ */
113
+ export default function getClosestMatchingOption(validator, rootSchema, formData, options, selectedOption = -1, discriminatorField) {
114
+ // First resolve any refs in the options
115
+ const resolvedOptions = options.map((option) => {
116
+ return resolveAllReferences(option, rootSchema);
117
+ });
118
+ // Reduce the array of options down to a list of the indexes that are considered matching options
119
+ const allValidIndexes = resolvedOptions.reduce((validList, option, index) => {
120
+ const testOptions = [JUNK_OPTION, option];
121
+ const match = getFirstMatchingOption(validator, formData, testOptions, rootSchema, discriminatorField);
122
+ // The match is the real option, so add its index to list of valid indexes
123
+ if (match === 1) {
124
+ validList.push(index);
125
+ }
126
+ return validList;
127
+ }, []);
128
+ // There is only one valid index, so return it!
129
+ if (allValidIndexes.length === 1) {
130
+ return allValidIndexes[0];
131
+ }
132
+ if (!allValidIndexes.length) {
133
+ // No indexes were valid, so we'll score all the options, add all the indexes
134
+ times(resolvedOptions.length, (i) => allValidIndexes.push(i));
135
+ }
136
+ const scoreCount = new Set();
137
+ // Score all the options in the list of valid indexes and return the index with the best score
138
+ const { bestIndex } = allValidIndexes.reduce((scoreData, index) => {
139
+ const { bestScore } = scoreData;
140
+ const option = resolvedOptions[index];
141
+ const score = calculateIndexScore(validator, rootSchema, option, formData);
142
+ scoreCount.add(score);
143
+ if (score > bestScore) {
144
+ return { bestIndex: index, bestScore: score };
145
+ }
146
+ return scoreData;
147
+ }, { bestIndex: selectedOption, bestScore: 0 });
148
+ // if all scores are the same go with selectedOption
149
+ if (scoreCount.size === 1 && selectedOption >= 0) {
150
+ return selectedOption;
151
+ }
152
+ return bestIndex;
153
+ }
154
+ //# sourceMappingURL=getClosestMatchingOption.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getClosestMatchingOption.js","sourceRoot":"","sources":["../../src/schema/getClosestMatchingOption.ts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,YAAY,CAAC;AAC7B,OAAO,GAAG,MAAM,YAAY,CAAC;AAC7B,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,MAAM,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