@hookform/resolvers 1.3.4 → 1.3.8

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 (153) hide show
  1. package/README.md +13 -5
  2. package/dist/convertArrayToPathName.d.ts +1 -0
  3. package/dist/ie11/joi/index.d.ts +1 -0
  4. package/dist/ie11/{joi.d.ts → joi/joi.d.ts} +0 -0
  5. package/dist/ie11/joi/joi.js +2 -0
  6. package/dist/ie11/joi/joi.js.map +1 -0
  7. package/dist/ie11/superstruct/index.d.ts +1 -0
  8. package/dist/ie11/{superstruct.d.ts → superstruct/superstruct.d.ts} +0 -0
  9. package/dist/ie11/superstruct/superstruct.js +2 -0
  10. package/dist/ie11/superstruct/superstruct.js.map +1 -0
  11. package/dist/ie11/vest/index.d.ts +1 -0
  12. package/dist/ie11/{vest.d.ts → vest/vest.d.ts} +0 -0
  13. package/dist/ie11/vest/vest.js +2 -0
  14. package/dist/ie11/vest/vest.js.map +1 -0
  15. package/dist/ie11/yup/index.d.ts +1 -0
  16. package/dist/{yup.d.ts → ie11/yup/yup.d.ts} +6 -5
  17. package/dist/ie11/yup/yup.js +2 -0
  18. package/dist/ie11/yup/yup.js.map +1 -0
  19. package/dist/ie11/zod/index.d.ts +1 -0
  20. package/dist/ie11/{zod.d.ts → zod/zod.d.ts} +0 -0
  21. package/dist/ie11/zod/zod.js +2 -0
  22. package/dist/ie11/zod/zod.js.map +1 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/resolvers.js +2 -0
  25. package/dist/resolvers.js.map +1 -0
  26. package/dist/resolvers.mjs +2 -0
  27. package/dist/resolvers.modern.js +2 -0
  28. package/dist/resolvers.modern.js.map +1 -0
  29. package/dist/resolvers.module.js +2 -0
  30. package/dist/resolvers.module.js.map +1 -0
  31. package/dist/resolvers.umd.js +2 -0
  32. package/dist/resolvers.umd.js.map +1 -0
  33. package/joi/dist/index.d.ts +1 -0
  34. package/{dist → joi/dist}/joi.d.ts +3 -3
  35. package/joi/dist/joi.js +2 -0
  36. package/joi/dist/joi.js.map +1 -0
  37. package/joi/dist/joi.mjs +2 -0
  38. package/joi/dist/joi.modern.js +2 -0
  39. package/joi/dist/joi.modern.js.map +1 -0
  40. package/joi/dist/joi.module.js +2 -0
  41. package/joi/dist/joi.module.js.map +1 -0
  42. package/joi/dist/joi.umd.js +2 -0
  43. package/joi/dist/joi.umd.js.map +1 -0
  44. package/joi/package.json +17 -0
  45. package/joi/src/__tests__/__snapshots__/joi.ts.snap +13 -0
  46. package/joi/src/__tests__/joi.ts +49 -0
  47. package/joi/src/index.ts +1 -0
  48. package/joi/src/joi.ts +76 -0
  49. package/package.json +83 -39
  50. package/superstruct/dist/index.d.ts +1 -0
  51. package/{dist → superstruct/dist}/superstruct.d.ts +5 -5
  52. package/superstruct/dist/superstruct.js +2 -0
  53. package/superstruct/dist/superstruct.js.map +1 -0
  54. package/superstruct/dist/superstruct.mjs +2 -0
  55. package/superstruct/dist/superstruct.modern.js +2 -0
  56. package/superstruct/dist/superstruct.modern.js.map +1 -0
  57. package/superstruct/dist/superstruct.module.js +2 -0
  58. package/superstruct/dist/superstruct.module.js.map +1 -0
  59. package/superstruct/dist/superstruct.umd.js +2 -0
  60. package/superstruct/dist/superstruct.umd.js.map +1 -0
  61. package/superstruct/package.json +17 -0
  62. package/superstruct/src/__tests__/__snapshots__/superstruct.ts.snap +33 -0
  63. package/superstruct/src/__tests__/superstruct.ts +45 -0
  64. package/superstruct/src/index.ts +1 -0
  65. package/superstruct/src/superstruct.ts +68 -0
  66. package/vest/dist/index.d.ts +1 -0
  67. package/{dist → vest/dist}/vest.d.ts +5 -5
  68. package/vest/dist/vest.js +2 -0
  69. package/vest/dist/vest.js.map +1 -0
  70. package/vest/dist/vest.mjs +2 -0
  71. package/vest/dist/vest.modern.js +2 -0
  72. package/vest/dist/vest.modern.js.map +1 -0
  73. package/vest/dist/vest.module.js +2 -0
  74. package/vest/dist/vest.module.js.map +1 -0
  75. package/vest/dist/vest.umd.js +2 -0
  76. package/vest/dist/vest.umd.js.map +1 -0
  77. package/vest/package.json +17 -0
  78. package/vest/src/__tests__/vest.ts +120 -0
  79. package/vest/src/index.ts +1 -0
  80. package/vest/src/vest.ts +59 -0
  81. package/yup/dist/index.d.ts +1 -0
  82. package/{dist/ie11 → yup/dist}/yup.d.ts +2 -1
  83. package/yup/dist/yup.js +2 -0
  84. package/yup/dist/yup.js.map +1 -0
  85. package/yup/dist/yup.mjs +2 -0
  86. package/yup/dist/yup.modern.js +2 -0
  87. package/yup/dist/yup.modern.js.map +1 -0
  88. package/yup/dist/yup.module.js +2 -0
  89. package/yup/dist/yup.module.js.map +1 -0
  90. package/yup/dist/yup.umd.js +2 -0
  91. package/yup/dist/yup.umd.js.map +1 -0
  92. package/yup/package.json +17 -0
  93. package/yup/src/__tests__/__snapshots__/yup.ts.snap +119 -0
  94. package/yup/src/__tests__/yup.ts +311 -0
  95. package/yup/src/index.ts +1 -0
  96. package/yup/src/yup.ts +96 -0
  97. package/zod/dist/index.d.ts +1 -0
  98. package/{dist → zod/dist}/zod.d.ts +4 -4
  99. package/zod/dist/zod.js +2 -0
  100. package/zod/dist/zod.js.map +1 -0
  101. package/zod/dist/zod.mjs +2 -0
  102. package/zod/dist/zod.modern.js +2 -0
  103. package/zod/dist/zod.modern.js.map +1 -0
  104. package/zod/dist/zod.module.js +2 -0
  105. package/zod/dist/zod.module.js.map +1 -0
  106. package/zod/dist/zod.umd.js +2 -0
  107. package/zod/dist/zod.umd.js.map +1 -0
  108. package/zod/package.json +17 -0
  109. package/zod/src/__tests__/__snapshots__/zod.ts.snap +194 -0
  110. package/zod/src/__tests__/zod.ts +131 -0
  111. package/zod/src/index.ts +1 -0
  112. package/zod/src/zod.ts +84 -0
  113. package/CHANGELOG.md +0 -7
  114. package/dist/ie11/_virtual/_tslib.js +0 -2
  115. package/dist/ie11/_virtual/_tslib.js.map +0 -1
  116. package/dist/ie11/joi.js +0 -2
  117. package/dist/ie11/joi.js.map +0 -1
  118. package/dist/ie11/superstruct.js +0 -2
  119. package/dist/ie11/superstruct.js.map +0 -1
  120. package/dist/ie11/utils/convertArrayToPathName.d.ts +0 -2
  121. package/dist/ie11/utils/convertArrayToPathName.js +0 -2
  122. package/dist/ie11/utils/convertArrayToPathName.js.map +0 -1
  123. package/dist/ie11/vest.js +0 -2
  124. package/dist/ie11/vest.js.map +0 -1
  125. package/dist/ie11/yup.js +0 -2
  126. package/dist/ie11/yup.js.map +0 -1
  127. package/dist/ie11/zod.js +0 -2
  128. package/dist/ie11/zod.js.map +0 -1
  129. package/dist/joi.js +0 -38
  130. package/dist/joi.js.map +0 -1
  131. package/dist/superstruct.js +0 -36
  132. package/dist/superstruct.js.map +0 -1
  133. package/dist/umd/index.js +0 -2
  134. package/dist/umd/index.js.map +0 -1
  135. package/dist/utils/convertArrayToPathName.d.ts +0 -2
  136. package/dist/utils/convertArrayToPathName.js +0 -6
  137. package/dist/utils/convertArrayToPathName.js.map +0 -1
  138. package/dist/vest.js +0 -26
  139. package/dist/vest.js.map +0 -1
  140. package/dist/yup.js +0 -59
  141. package/dist/yup.js.map +0 -1
  142. package/dist/zod.js +0 -44
  143. package/dist/zod.js.map +0 -1
  144. package/joi.d.ts +0 -1
  145. package/joi.js +0 -1
  146. package/superstruct.d.ts +0 -1
  147. package/superstruct.js +0 -1
  148. package/vest.d.ts +0 -1
  149. package/vest.js +0 -1
  150. package/yup.d.ts +0 -1
  151. package/yup.js +0 -1
  152. package/zod.d.ts +0 -1
  153. package/zod.js +0 -1
@@ -0,0 +1,45 @@
1
+ import { object, number, string, boolean, array, optional } from 'superstruct';
2
+ import { superstructResolver } from '..';
3
+
4
+ const Article = object({
5
+ id: number(),
6
+ title: string(),
7
+ isPublished: optional(boolean()),
8
+ tags: array(string()),
9
+ author: object({
10
+ id: number(),
11
+ }),
12
+ });
13
+
14
+ describe('superstructResolver', () => {
15
+ it('should return correct value', async () => {
16
+ const data = {
17
+ id: 2,
18
+ title: 'test',
19
+ tags: ['news', 'features'],
20
+ author: {
21
+ id: 1,
22
+ },
23
+ };
24
+
25
+ expect(await superstructResolver(Article)(data)).toEqual({
26
+ values: data,
27
+ errors: {},
28
+ });
29
+ });
30
+
31
+ it('should return errors', async () => {
32
+ const data = {
33
+ id: '2',
34
+ title: 2,
35
+ tags: [2, 3],
36
+ author: {
37
+ id: 'test',
38
+ },
39
+ };
40
+
41
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
42
+ // @ts-expect-error - For testing purpose `id`'s type is wrong
43
+ expect(await superstructResolver(Article)(data)).toMatchSnapshot();
44
+ });
45
+ });
@@ -0,0 +1 @@
1
+ export * from './superstruct';
@@ -0,0 +1,68 @@
1
+ import {
2
+ appendErrors,
3
+ transformToNestObject,
4
+ Resolver,
5
+ ResolverSuccess,
6
+ ResolverError,
7
+ } from 'react-hook-form';
8
+ import { StructError, validate, Struct, Infer } from 'superstruct';
9
+ import { convertArrayToPathName } from '@hookform/resolvers';
10
+
11
+ const parseErrorSchema = (
12
+ error: StructError,
13
+ validateAllFieldCriteria: boolean,
14
+ ) =>
15
+ error
16
+ .failures()
17
+ .reduce((previous: Record<string, any>, { path, message = '', type }) => {
18
+ const currentPath = convertArrayToPathName(path);
19
+ return {
20
+ ...previous,
21
+ ...(path
22
+ ? previous[currentPath] && validateAllFieldCriteria
23
+ ? {
24
+ [currentPath]: appendErrors(
25
+ currentPath,
26
+ validateAllFieldCriteria,
27
+ previous,
28
+ type || '',
29
+ message,
30
+ ),
31
+ }
32
+ : {
33
+ [currentPath]: previous[currentPath] || {
34
+ message,
35
+ type,
36
+ ...(validateAllFieldCriteria
37
+ ? {
38
+ types: { [type || '']: message || true },
39
+ }
40
+ : {}),
41
+ },
42
+ }
43
+ : {}),
44
+ };
45
+ }, {});
46
+
47
+ type Options = Parameters<typeof validate>[2];
48
+
49
+ export const superstructResolver = <T extends Struct<any, any>>(
50
+ schema: T,
51
+ options?: Options,
52
+ ): Resolver<Infer<T>> => (values, _, validateAllFieldCriteria = false) => {
53
+ const [errors, result] = validate(values, schema, options);
54
+
55
+ if (errors != null) {
56
+ return {
57
+ values: {},
58
+ errors: transformToNestObject(
59
+ parseErrorSchema(errors, validateAllFieldCriteria),
60
+ ),
61
+ } as ResolverError<Infer<T>>;
62
+ }
63
+
64
+ return {
65
+ values: result,
66
+ errors: {},
67
+ } as ResolverSuccess<Infer<T>>;
68
+ };
@@ -0,0 +1 @@
1
+ export * from './vest';
@@ -1,5 +1,5 @@
1
- import { Resolver } from 'react-hook-form';
2
- import * as Vest from 'vest';
3
- declare type ICreateResult = ReturnType<typeof Vest.create>;
4
- export declare const vestResolver: <TFieldValues extends Record<string, any>>(schema: ICreateResult, _?: any, validateAllFieldCriteria?: boolean) => Resolver<TFieldValues, object>;
5
- export {};
1
+ import { Resolver } from 'react-hook-form';
2
+ import * as Vest from 'vest';
3
+ declare type ICreateResult = ReturnType<typeof Vest.create>;
4
+ export declare const vestResolver: <TFieldValues extends Record<string, any>>(schema: ICreateResult, _?: any, validateAllFieldCriteria?: boolean) => Resolver<TFieldValues, object>;
5
+ export {};
@@ -0,0 +1,2 @@
1
+ var r=require("react-hook-form");function e(){return(e=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var t=function(r,t){return Object.entries(r).reduce(function(r,n){var o,u=n[1];return e({},r,((o={})[n[0]]=e({type:"",message:u[0]},t?{types:u.reduce(function(r,t,n){var o;return e({},r,((o={})[n]=t,o))},{})}:{}),o))},{})};exports.vestResolver=function(e,n,o){return void 0===o&&(o=!1),function(n){try{var u=(s=e,function(){var r=arguments;return new Promise(function(e){return s.apply(void 0,[].slice.call(r)).done(e)})});return Promise.resolve(u(n)).then(function(e){var u=e.getErrors();return e.hasErrors()?{values:{},errors:r.transformToNestObject(t(u,o))}:{values:n,errors:{}}})}catch(r){return Promise.reject(r)}var s}};
2
+ //# sourceMappingURL=vest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vest.js","sources":["../src/vest.ts"],"sourcesContent":["import { FieldValues, Resolver, transformToNestObject } from 'react-hook-form';\nimport * as Vest from 'vest';\n\ntype VestErrors = Record<string, string[]>;\n\ntype ICreateResult = ReturnType<typeof Vest.create>;\n\ntype Promisify = <T extends ICreateResult, K>(\n fn: T,\n) => (args: K) => Promise<Vest.IVestResult>;\n\nconst promisify: Promisify = (validatorFn) => (...args) =>\n new Promise((resolve) => validatorFn(...args).done(resolve as Vest.DoneCB));\n\nconst parseErrorSchema = (\n vestError: VestErrors,\n validateAllFieldCriteria: boolean,\n) => {\n return Object.entries(vestError).reduce((prev, [key, value]) => {\n return {\n ...prev,\n [key]: {\n type: '',\n message: value[0],\n ...(validateAllFieldCriteria\n ? {\n types: value.reduce((prev, message, index) => {\n return {\n ...prev,\n [index]: message,\n };\n }, {}),\n }\n : {}),\n },\n };\n }, {});\n};\n\nexport const vestResolver = <TFieldValues extends FieldValues>(\n schema: ICreateResult,\n _: any = {},\n validateAllFieldCriteria = false,\n): Resolver<TFieldValues> => async (values) => {\n const validateSchema = promisify(schema);\n const result = await validateSchema(values);\n const errors = result.getErrors();\n\n if (!result.hasErrors()) {\n return { values: values as any, errors: {} };\n }\n\n return {\n values: {},\n errors: transformToNestObject(\n parseErrorSchema(errors, validateAllFieldCriteria),\n ),\n };\n};\n"],"names":["parseErrorSchema","vestError","validateAllFieldCriteria","Object","entries","reduce","prev","value","type","message","types","index","schema","_","values","validateSchema","validatorFn","Promise","resolve","done","result","errors","getErrors","hasErrors","transformToNestObject"],"mappings":"gPAWA,IAGMA,EAAmB,SACvBC,EACAC,GAEA,OAAOC,OAAOC,QAAQH,GAAWI,OAAO,SAACC,WAAYC,OACnD,YACKD,mBAEDE,KAAM,GACNC,QAASF,EAAM,IACXL,EACA,CACEQ,MAAOH,EAAMF,OAAO,SAACC,EAAMG,EAASE,SAClC,YACKL,UACFK,GAAQF,OAEV,KAEL,SAGP,0BAGuB,SAC1BG,EACAC,EACAX,mBAAAA,IAAAA,GAA2B,YACOY,OAClC,IAAMC,GAjCsBC,EAiCKJ,wCAhC7BK,QAAQ,SAACC,UAAYF,iCAAqBG,KAAKD,8BAiC9BH,EAAeD,kBAA9BM,GACN,IAAMC,EAASD,EAAOE,mBAEjBF,EAAOG,YAIL,CACLT,OAAQ,GACRO,OAAQG,wBACNxB,EAAiBqB,EAAQnB,KANpB,CAAEY,OAAQA,EAAeO,OAAQ,MAVhB,kCA5BC,IAACL"}
@@ -0,0 +1,2 @@
1
+ import{transformToNestObject as r}from"react-hook-form";function e(){return(e=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var t=function(r,t){return Object.entries(r).reduce(function(r,n){var o,u=n[1];return e({},r,((o={})[n[0]]=e({type:"",message:u[0]},t?{types:u.reduce(function(r,t,n){var o;return e({},r,((o={})[n]=t,o))},{})}:{}),o))},{})},n=function(e,n,o){return void 0===o&&(o=!1),function(n){try{var u=(a=e,function(){var r=arguments;return new Promise(function(e){return a.apply(void 0,[].slice.call(r)).done(e)})});return Promise.resolve(u(n)).then(function(e){var u=e.getErrors();return e.hasErrors()?{values:{},errors:r(t(u,o))}:{values:n,errors:{}}})}catch(r){return Promise.reject(r)}var a}};export{n as vestResolver};
2
+ //# sourceMappingURL=vest.module.js.map
@@ -0,0 +1,2 @@
1
+ import{transformToNestObject as r}from"react-hook-form";function e(){return(e=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=t[o])}return r}).apply(this,arguments)}const t=(r,t)=>Object.entries(r).reduce((r,[o,s])=>e({},r,{[o]:e({type:"",message:s[0]},t?{types:s.reduce((r,t,o)=>e({},r,{[o]:t}),{})}:{})}),{}),o=(e,o={},s=!1)=>async o=>{const n=(a=e,(...r)=>new Promise(e=>a(...r).done(e)));var a;const c=await n(o),i=c.getErrors();return c.hasErrors()?{values:{},errors:r(t(i,s))}:{values:o,errors:{}}};export{o as vestResolver};
2
+ //# sourceMappingURL=vest.modern.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vest.modern.js","sources":["../src/vest.ts"],"sourcesContent":["import { FieldValues, Resolver, transformToNestObject } from 'react-hook-form';\nimport * as Vest from 'vest';\n\ntype VestErrors = Record<string, string[]>;\n\ntype ICreateResult = ReturnType<typeof Vest.create>;\n\ntype Promisify = <T extends ICreateResult, K>(\n fn: T,\n) => (args: K) => Promise<Vest.IVestResult>;\n\nconst promisify: Promisify = (validatorFn) => (...args) =>\n new Promise((resolve) => validatorFn(...args).done(resolve as Vest.DoneCB));\n\nconst parseErrorSchema = (\n vestError: VestErrors,\n validateAllFieldCriteria: boolean,\n) => {\n return Object.entries(vestError).reduce((prev, [key, value]) => {\n return {\n ...prev,\n [key]: {\n type: '',\n message: value[0],\n ...(validateAllFieldCriteria\n ? {\n types: value.reduce((prev, message, index) => {\n return {\n ...prev,\n [index]: message,\n };\n }, {}),\n }\n : {}),\n },\n };\n }, {});\n};\n\nexport const vestResolver = <TFieldValues extends FieldValues>(\n schema: ICreateResult,\n _: any = {},\n validateAllFieldCriteria = false,\n): Resolver<TFieldValues> => async (values) => {\n const validateSchema = promisify(schema);\n const result = await validateSchema(values);\n const errors = result.getErrors();\n\n if (!result.hasErrors()) {\n return { values: values as any, errors: {} };\n }\n\n return {\n values: {},\n errors: transformToNestObject(\n parseErrorSchema(errors, validateAllFieldCriteria),\n ),\n };\n};\n"],"names":["parseErrorSchema","vestError","validateAllFieldCriteria","Object","entries","reduce","prev","key","value","[object Object]","type","message","types","index","vestResolver","schema","_","async","validateSchema","validatorFn","args","Promise","resolve","done","result","values","errors","getErrors","hasErrors","transformToNestObject"],"mappings":"uQAWA,MAGMA,EAAmB,CACvBC,EACAC,IAEOC,OAAOC,QAAQH,GAAWI,OAAO,CAACC,GAAOC,EAAKC,UAE9CF,GACHG,CAACF,MACCG,KAAM,GACNC,QAASH,EAAM,IACXN,EACA,CACEU,MAAOJ,EAAMH,OAAO,CAACC,EAAMK,EAASE,SAE7BP,GACHG,CAACI,GAAQF,IAEV,KAEL,MAGP,IAGQG,EAAe,CAC1BC,EACAC,EAAS,GACTd,GAA2B,IACAe,MAAAA,IAC3B,MAAMC,GAjCsBC,EAiCKJ,EAjCW,IAAIK,IAChD,IAAIC,QAASC,GAAYH,KAAeC,GAAMG,KAAKD,KADvBH,IAAAA,EAkC5B,MAAMK,QAAeN,EAAeO,GAC9BC,EAASF,EAAOG,YAEtB,OAAKH,EAAOI,YAIL,CACLH,OAAQ,GACRC,OAAQG,EACN7B,EAAiB0B,EAAQxB,KANpB,CAAEuB,OAAQA,EAAeC,OAAQ"}
@@ -0,0 +1,2 @@
1
+ import{transformToNestObject as r}from"react-hook-form";function e(){return(e=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var t=function(r,t){return Object.entries(r).reduce(function(r,n){var o,u=n[1];return e({},r,((o={})[n[0]]=e({type:"",message:u[0]},t?{types:u.reduce(function(r,t,n){var o;return e({},r,((o={})[n]=t,o))},{})}:{}),o))},{})},n=function(e,n,o){return void 0===o&&(o=!1),function(n){try{var u=(a=e,function(){var r=arguments;return new Promise(function(e){return a.apply(void 0,[].slice.call(r)).done(e)})});return Promise.resolve(u(n)).then(function(e){var u=e.getErrors();return e.hasErrors()?{values:{},errors:r(t(u,o))}:{values:n,errors:{}}})}catch(r){return Promise.reject(r)}var a}};export{n as vestResolver};
2
+ //# sourceMappingURL=vest.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vest.module.js","sources":["../src/vest.ts"],"sourcesContent":["import { FieldValues, Resolver, transformToNestObject } from 'react-hook-form';\nimport * as Vest from 'vest';\n\ntype VestErrors = Record<string, string[]>;\n\ntype ICreateResult = ReturnType<typeof Vest.create>;\n\ntype Promisify = <T extends ICreateResult, K>(\n fn: T,\n) => (args: K) => Promise<Vest.IVestResult>;\n\nconst promisify: Promisify = (validatorFn) => (...args) =>\n new Promise((resolve) => validatorFn(...args).done(resolve as Vest.DoneCB));\n\nconst parseErrorSchema = (\n vestError: VestErrors,\n validateAllFieldCriteria: boolean,\n) => {\n return Object.entries(vestError).reduce((prev, [key, value]) => {\n return {\n ...prev,\n [key]: {\n type: '',\n message: value[0],\n ...(validateAllFieldCriteria\n ? {\n types: value.reduce((prev, message, index) => {\n return {\n ...prev,\n [index]: message,\n };\n }, {}),\n }\n : {}),\n },\n };\n }, {});\n};\n\nexport const vestResolver = <TFieldValues extends FieldValues>(\n schema: ICreateResult,\n _: any = {},\n validateAllFieldCriteria = false,\n): Resolver<TFieldValues> => async (values) => {\n const validateSchema = promisify(schema);\n const result = await validateSchema(values);\n const errors = result.getErrors();\n\n if (!result.hasErrors()) {\n return { values: values as any, errors: {} };\n }\n\n return {\n values: {},\n errors: transformToNestObject(\n parseErrorSchema(errors, validateAllFieldCriteria),\n ),\n };\n};\n"],"names":["parseErrorSchema","vestError","validateAllFieldCriteria","Object","entries","reduce","prev","value","type","message","types","index","vestResolver","schema","_","values","validateSchema","validatorFn","Promise","resolve","done","result","errors","getErrors","hasErrors","transformToNestObject"],"mappings":"uQAWA,IAGMA,EAAmB,SACvBC,EACAC,GAEA,OAAOC,OAAOC,QAAQH,GAAWI,OAAO,SAACC,WAAYC,OACnD,YACKD,mBAEDE,KAAM,GACNC,QAASF,EAAM,IACXL,EACA,CACEQ,MAAOH,EAAMF,OAAO,SAACC,EAAMG,EAASE,SAClC,YACKL,UACFK,GAAQF,OAEV,KAEL,SAGP,KAGQG,EAAe,SAC1BC,EACAC,EACAZ,mBAAAA,IAAAA,GAA2B,YACOa,OAClC,IAAMC,GAjCsBC,EAiCKJ,wCAhC7BK,QAAQ,SAACC,UAAYF,iCAAqBG,KAAKD,8BAiC9BH,EAAeD,kBAA9BM,GACN,IAAMC,EAASD,EAAOE,mBAEjBF,EAAOG,YAIL,CACLT,OAAQ,GACRO,OAAQG,EACNzB,EAAiBsB,EAAQpB,KANpB,CAAEa,OAAQA,EAAeO,OAAQ,MAVhB,kCA5BC,IAACL"}
@@ -0,0 +1,2 @@
1
+ !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","react-hook-form"],r):r((e||self).hookformResolversVest={},e.reactHookForm)}(this,function(e,r){function t(){return(t=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e}).apply(this,arguments)}var o=function(e,r){return Object.entries(e).reduce(function(e,o){var n,s=o[1];return t({},e,((n={})[o[0]]=t({type:"",message:s[0]},r?{types:s.reduce(function(e,r,o){var n;return t({},e,((n={})[o]=r,n))},{})}:{}),n))},{})};e.vestResolver=function(e,t,n){return void 0===n&&(n=!1),function(t){try{var s=(i=e,function(){var e=arguments;return new Promise(function(r){return i.apply(void 0,[].slice.call(e)).done(r)})});return Promise.resolve(s(t)).then(function(e){var s=e.getErrors();return e.hasErrors()?{values:{},errors:r.transformToNestObject(o(s,n))}:{values:t,errors:{}}})}catch(e){return Promise.reject(e)}var i}}});
2
+ //# sourceMappingURL=vest.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vest.umd.js","sources":["../src/vest.ts"],"sourcesContent":["import { FieldValues, Resolver, transformToNestObject } from 'react-hook-form';\nimport * as Vest from 'vest';\n\ntype VestErrors = Record<string, string[]>;\n\ntype ICreateResult = ReturnType<typeof Vest.create>;\n\ntype Promisify = <T extends ICreateResult, K>(\n fn: T,\n) => (args: K) => Promise<Vest.IVestResult>;\n\nconst promisify: Promisify = (validatorFn) => (...args) =>\n new Promise((resolve) => validatorFn(...args).done(resolve as Vest.DoneCB));\n\nconst parseErrorSchema = (\n vestError: VestErrors,\n validateAllFieldCriteria: boolean,\n) => {\n return Object.entries(vestError).reduce((prev, [key, value]) => {\n return {\n ...prev,\n [key]: {\n type: '',\n message: value[0],\n ...(validateAllFieldCriteria\n ? {\n types: value.reduce((prev, message, index) => {\n return {\n ...prev,\n [index]: message,\n };\n }, {}),\n }\n : {}),\n },\n };\n }, {});\n};\n\nexport const vestResolver = <TFieldValues extends FieldValues>(\n schema: ICreateResult,\n _: any = {},\n validateAllFieldCriteria = false,\n): Resolver<TFieldValues> => async (values) => {\n const validateSchema = promisify(schema);\n const result = await validateSchema(values);\n const errors = result.getErrors();\n\n if (!result.hasErrors()) {\n return { values: values as any, errors: {} };\n }\n\n return {\n values: {},\n errors: transformToNestObject(\n parseErrorSchema(errors, validateAllFieldCriteria),\n ),\n };\n};\n"],"names":["parseErrorSchema","vestError","validateAllFieldCriteria","Object","entries","reduce","prev","value","type","message","types","index","schema","_","values","validateSchema","validatorFn","Promise","resolve","done","result","errors","getErrors","hasErrors","transformToNestObject"],"mappings":"6fAWA,IAGMA,EAAmB,SACvBC,EACAC,GAEA,OAAOC,OAAOC,QAAQH,GAAWI,OAAO,SAACC,WAAYC,OACnD,YACKD,mBAEDE,KAAM,GACNC,QAASF,EAAM,IACXL,EACA,CACEQ,MAAOH,EAAMF,OAAO,SAACC,EAAMG,EAASE,SAClC,YACKL,UACFK,GAAQF,OAEV,KAEL,SAGP,oBAGuB,SAC1BG,EACAC,EACAX,mBAAAA,IAAAA,GAA2B,YACOY,OAClC,IAAMC,GAjCsBC,EAiCKJ,wCAhC7BK,QAAQ,SAACC,UAAYF,iCAAqBG,KAAKD,8BAiC9BH,EAAeD,kBAA9BM,GACN,IAAMC,EAASD,EAAOE,mBAEjBF,EAAOG,YAIL,CACLT,OAAQ,GACRO,OAAQG,wBACNxB,EAAiBqB,EAAQnB,KANpB,CAAEY,OAAQA,EAAeO,OAAQ,MAVhB,kCA5BC,IAACL"}
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "vest",
3
+ "amdName": "hookformResolversVest",
4
+ "version": "1.0.0",
5
+ "private": true,
6
+ "description": "React Hook Form validation resolver: vest",
7
+ "main": "dist/vest.js",
8
+ "module": "dist/vest.module.js",
9
+ "umd:main": "dist/vest.umd.js",
10
+ "source": "src/index.ts",
11
+ "types": "dist/index.d.ts",
12
+ "license": "MIT",
13
+ "peerDependencies": {
14
+ "react-hook-form": ">=6.6.0",
15
+ "@hookform/resolvers": "^1.0.0"
16
+ }
17
+ }
@@ -0,0 +1,120 @@
1
+ import * as vest from 'vest';
2
+ import { vestResolver } from '..';
3
+
4
+ const validationSuite = vest.create('form', (data: any = {}) => {
5
+ vest.test('username', 'Username is required', () => {
6
+ vest.enforce(data.username).isNotEmpty();
7
+ });
8
+
9
+ vest.test('username', 'Must be longer than 3 chars', () => {
10
+ vest.enforce(data.username).longerThan(3);
11
+ });
12
+
13
+ vest.test('deepObject.data', 'deepObject.data is required', () => {
14
+ vest.enforce(data.deepObject.data).isNotEmpty();
15
+ });
16
+
17
+ vest.test('password', 'Password is required', () => {
18
+ vest.enforce(data.password).isNotEmpty();
19
+ });
20
+
21
+ vest.test('password', 'Password must be at least 5 chars', () => {
22
+ vest.enforce(data.password).longerThanOrEquals(5);
23
+ });
24
+
25
+ vest.test('password', 'Password must contain a digit', () => {
26
+ vest.enforce(data.password).matches(/[0-9]/);
27
+ });
28
+
29
+ vest.test('password', 'Password must contain a symbol', () => {
30
+ vest.enforce(data.password).matches(/[^A-Za-z0-9]/);
31
+ });
32
+ });
33
+
34
+ describe('vest', () => {
35
+ it('should return values from vestResolver when validation pass', async () => {
36
+ const data = {
37
+ username: 'asdda',
38
+ password: 'asddfg123!',
39
+ deepObject: {
40
+ data: 'test',
41
+ },
42
+ };
43
+ expect(await vestResolver(validationSuite)(data, {})).toEqual({
44
+ values: data,
45
+ errors: {},
46
+ });
47
+ });
48
+
49
+ it('should return single error message from vestResolver when validation fails and validateAllFieldCriteria set to false', async () => {
50
+ const data = {
51
+ username: '',
52
+ password: 'a',
53
+ deepObject: {
54
+ data: '',
55
+ },
56
+ };
57
+
58
+ expect(await vestResolver(validationSuite)(data, {})).toEqual({
59
+ values: {},
60
+ errors: {
61
+ username: {
62
+ type: '',
63
+ message: 'Username is required',
64
+ },
65
+ password: {
66
+ type: '',
67
+ message: 'Password must be at least 5 chars',
68
+ },
69
+ deepObject: {
70
+ data: {
71
+ type: '',
72
+ message: 'deepObject.data is required',
73
+ },
74
+ },
75
+ },
76
+ });
77
+ });
78
+
79
+ it('should return all the error messages from vestResolver when validation fails and validateAllFieldCriteria set to true', async () => {
80
+ const data = {
81
+ username: '',
82
+ password: 'a',
83
+ deepObject: {
84
+ data: '',
85
+ },
86
+ };
87
+
88
+ expect(await vestResolver(validationSuite, {}, true)(data, {})).toEqual({
89
+ values: {},
90
+ errors: {
91
+ username: {
92
+ type: '',
93
+ message: 'Username is required',
94
+ types: {
95
+ 0: 'Username is required',
96
+ 1: 'Must be longer than 3 chars',
97
+ },
98
+ },
99
+ password: {
100
+ type: '',
101
+ message: 'Password must be at least 5 chars',
102
+ types: {
103
+ 0: 'Password must be at least 5 chars',
104
+ 1: 'Password must contain a digit',
105
+ 2: 'Password must contain a symbol',
106
+ },
107
+ },
108
+ deepObject: {
109
+ data: {
110
+ type: '',
111
+ message: 'deepObject.data is required',
112
+ types: {
113
+ 0: 'deepObject.data is required',
114
+ },
115
+ },
116
+ },
117
+ },
118
+ });
119
+ });
120
+ });
@@ -0,0 +1 @@
1
+ export * from './vest';
@@ -0,0 +1,59 @@
1
+ import { FieldValues, Resolver, transformToNestObject } from 'react-hook-form';
2
+ import * as Vest from 'vest';
3
+
4
+ type VestErrors = Record<string, string[]>;
5
+
6
+ type ICreateResult = ReturnType<typeof Vest.create>;
7
+
8
+ type Promisify = <T extends ICreateResult, K>(
9
+ fn: T,
10
+ ) => (args: K) => Promise<Vest.IVestResult>;
11
+
12
+ const promisify: Promisify = (validatorFn) => (...args) =>
13
+ new Promise((resolve) => validatorFn(...args).done(resolve as Vest.DoneCB));
14
+
15
+ const parseErrorSchema = (
16
+ vestError: VestErrors,
17
+ validateAllFieldCriteria: boolean,
18
+ ) => {
19
+ return Object.entries(vestError).reduce((prev, [key, value]) => {
20
+ return {
21
+ ...prev,
22
+ [key]: {
23
+ type: '',
24
+ message: value[0],
25
+ ...(validateAllFieldCriteria
26
+ ? {
27
+ types: value.reduce((prev, message, index) => {
28
+ return {
29
+ ...prev,
30
+ [index]: message,
31
+ };
32
+ }, {}),
33
+ }
34
+ : {}),
35
+ },
36
+ };
37
+ }, {});
38
+ };
39
+
40
+ export const vestResolver = <TFieldValues extends FieldValues>(
41
+ schema: ICreateResult,
42
+ _: any = {},
43
+ validateAllFieldCriteria = false,
44
+ ): Resolver<TFieldValues> => async (values) => {
45
+ const validateSchema = promisify(schema);
46
+ const result = await validateSchema(values);
47
+ const errors = result.getErrors();
48
+
49
+ if (!result.hasErrors()) {
50
+ return { values: values as any, errors: {} };
51
+ }
52
+
53
+ return {
54
+ values: {},
55
+ errors: transformToNestObject(
56
+ parseErrorSchema(errors, validateAllFieldCriteria),
57
+ ),
58
+ };
59
+ };
@@ -0,0 +1 @@
1
+ export * from './yup';
@@ -1,5 +1,6 @@
1
1
  import { Resolver } from 'react-hook-form';
2
2
  import Yup from 'yup';
3
+ import Lazy from 'yup/lib/Lazy';
3
4
  declare type ValidateOptions<T extends Yup.AnyObjectSchema> = Parameters<T['validate']>[1];
4
- export declare const yupResolver: <TFieldValues extends Record<string, any>>(schema: Yup.AnyObjectSchema, options?: ValidateOptions<Yup.AnyObjectSchema>) => Resolver<TFieldValues, object>;
5
+ export declare const yupResolver: <TFieldValues extends Record<string, any>>(schema: Yup.AnyObjectSchema | Lazy<any, any>, options?: ValidateOptions<Yup.AnyObjectSchema>) => Resolver<TFieldValues, object>;
5
6
  export {};
@@ -0,0 +1,2 @@
1
+ var e=require("react-hook-form");function r(){return(r=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}exports.yupResolver=function(t,n){return void 0===n&&(n={abortEarly:!1}),function(o,s,a){void 0===a&&(a=!1);try{return Promise.resolve(function(e,a){try{var c=(n.context&&"development"===process.env.NODE_ENV&&console.warn("You should not used the yup options context. Please, use the 'useForm' context object instead"),Promise.resolve(t.validate(o,r({},n,{context:s}))).then(function(e){return{values:e,errors:{}}}))}catch(e){return a(e)}return c&&c.then?c.then(void 0,a):c}(0,function(t){if(!t.inner)throw t;var n=function(e,t){var n;return Array.isArray(e.inner)&&e.inner.length?e.inner.reduce(function(e,n){var o,s,a=n.path,c=n.message,u=n.type,i=e[a]&&e[a].types||{},p=a||u;return r({},e,p?((s={})[p]=r({},e[p]||{message:c,type:u},t?{types:r({},i,(o={},o[u]=i[u]?[].concat([].concat(i[u]),[c]):c,o))}:{}),s):{})},{}):((n={})[e.path]={message:e.message,type:e.type},n)}(t,a);return{values:{},errors:e.transformToNestObject(n)}}))}catch(e){return Promise.reject(e)}}};
2
+ //# sourceMappingURL=yup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"yup.js","sources":["../src/yup.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { Resolver, transformToNestObject, FieldValues } from 'react-hook-form';\nimport Yup from 'yup';\nimport Lazy from 'yup/lib/Lazy';\n\n/**\n * From 0.32.0, Yup add TypeScript support and `path` typing is optional that's why we have `@ts-expect-error`\n * FYI: `path`: a string, indicating where there error was thrown. `path` is empty at the root level.\n * react-hook-form's values are object so path is defined\n * https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string\n */\nconst parseErrorSchema = (\n error: Yup.ValidationError,\n validateAllFieldCriteria: boolean,\n) => {\n return Array.isArray(error.inner) && error.inner.length\n ? error.inner.reduce(\n (previous: Record<string, any>, { path, message, type }) => {\n // @ts-expect-error\n const previousTypes = (previous[path] && previous[path].types) || {};\n const key = path || type;\n\n return {\n ...previous,\n ...(key\n ? {\n [key]: {\n ...(previous[key] || {\n message,\n type,\n }),\n ...(validateAllFieldCriteria\n ? {\n types: {\n ...previousTypes,\n // @ts-expect-error\n [type]: previousTypes[type]\n ? // @ts-expect-error\n [...[].concat(previousTypes[type]), message]\n : message,\n },\n }\n : {}),\n },\n }\n : {}),\n };\n },\n {},\n )\n : {\n // @ts-expect-error\n [error.path]: { message: error.message, type: error.type },\n };\n};\n\ntype ValidateOptions<T extends Yup.AnyObjectSchema> = Parameters<\n T['validate']\n>[1];\n\nexport const yupResolver = <TFieldValues extends FieldValues>(\n schema: Yup.AnyObjectSchema | Lazy<any, any>,\n options: ValidateOptions<Yup.AnyObjectSchema> = {\n abortEarly: false,\n },\n): Resolver<TFieldValues> => async (\n values,\n context,\n validateAllFieldCriteria = false,\n) => {\n try {\n if (options.context && process.env.NODE_ENV === 'development') {\n // eslint-disable-next-line no-console\n console.warn(\n \"You should not used the yup options context. Please, use the 'useForm' context object instead\",\n );\n }\n return {\n values: await schema.validate(values, {\n ...options,\n context,\n }),\n errors: {},\n };\n } catch (e: any) {\n if (!e.inner) {\n throw e;\n }\n\n const parsedErrors = parseErrorSchema(e, validateAllFieldCriteria);\n return {\n values: {},\n errors: transformToNestObject(parsedErrors),\n };\n }\n};\n"],"names":["schema","options","abortEarly","values","context","validateAllFieldCriteria","process","env","NODE_ENV","console","warn","validate","errors","e","inner","parsedErrors","error","Array","isArray","length","reduce","previous","path","message","type","previousTypes","types","key","concat","parseErrorSchema","transformToNestObject"],"mappings":"oQA4D2B,SACzBA,EACAC,mBAAAA,IAAAA,EAAgD,CAC9CC,YAAY,aAGdC,EACAC,EACAC,YAAAA,IAAAA,GAA2B,uDAGrBJ,EAAQG,SAAoC,gBAAzBE,QAAQC,IAAIC,UAEjCC,QAAQC,KACN,iHAIYV,EAAOW,SAASR,OACzBF,GACHG,QAAAA,uBAHJ,MAAO,CACLD,SAIAS,OAAQ,4EAEHC,GACP,IAAKA,EAAEC,MACL,MAAMD,EAGR,IAAME,EA9Ee,SACvBC,EACAX,SAEA,OAAOY,MAAMC,QAAQF,EAAMF,QAAUE,EAAMF,MAAMK,OAC7CH,EAAMF,MAAMM,OACV,SAACC,aAAiCC,IAAAA,KAAMC,IAAAA,QAASC,IAAAA,KAEzCC,EAAiBJ,EAASC,IAASD,EAASC,GAAMI,OAAU,GAC5DC,EAAML,GAAQE,EAEpB,YACKH,EACCM,UAEGA,QACKN,EAASM,IAAQ,CACnBJ,QAAAA,EACAC,KAAAA,GAEEnB,EACA,CACEqB,WACKD,UAEFD,GAAOC,EAAcD,aAEd,GAAGI,OAAOH,EAAcD,KAAQD,IACpCA,OAGR,OAGR,KAGR,YAICP,EAAMM,MAAO,CAAEC,QAASP,EAAMO,QAASC,KAAMR,EAAMQ,SAqCnCK,CAAiBhB,EAAGR,GACzC,MAAO,CACLF,OAAQ,GACRS,OAAQkB,wBAAsBf,OAhCT"}
@@ -0,0 +1,2 @@
1
+ import{transformToNestObject as e}from"react-hook-form";function r(){return(r=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}var t=function(t,n){return void 0===n&&(n={abortEarly:!1}),function(o,a,s){void 0===s&&(s=!1);try{return Promise.resolve(function(e,s){try{var c=(n.context&&"development"===process.env.NODE_ENV&&console.warn("You should not used the yup options context. Please, use the 'useForm' context object instead"),Promise.resolve(t.validate(o,r({},n,{context:a}))).then(function(e){return{values:e,errors:{}}}))}catch(e){return s(e)}return c&&c.then?c.then(void 0,s):c}(0,function(t){if(!t.inner)throw t;var n=function(e,t){var n;return Array.isArray(e.inner)&&e.inner.length?e.inner.reduce(function(e,n){var o,a,s=n.path,c=n.message,u=n.type,i=e[s]&&e[s].types||{},p=s||u;return r({},e,p?((a={})[p]=r({},e[p]||{message:c,type:u},t?{types:r({},i,(o={},o[u]=i[u]?[].concat([].concat(i[u]),[c]):c,o))}:{}),a):{})},{}):((n={})[e.path]={message:e.message,type:e.type},n)}(t,s);return{values:{},errors:e(n)}}))}catch(e){return Promise.reject(e)}}};export{t as yupResolver};
2
+ //# sourceMappingURL=yup.module.js.map
@@ -0,0 +1,2 @@
1
+ import{transformToNestObject as e}from"react-hook-form";function t(){return(t=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}const r=(r,n={abortEarly:!1})=>async(o,s,a=!1)=>{try{return n.context&&"development"===process.env.NODE_ENV&&console.warn("You should not used the yup options context. Please, use the 'useForm' context object instead"),{values:await r.validate(o,t({},n,{context:s})),errors:{}}}catch(r){if(!r.inner)throw r;const n=((e,r)=>Array.isArray(e.inner)&&e.inner.length?e.inner.reduce((e,{path:n,message:o,type:s})=>{const a=e[n]&&e[n].types||{},c=n||s;return t({},e,c?{[c]:t({},e[c]||{message:o,type:s},r?{types:t({},a,{[s]:a[s]?[...[].concat(a[s]),o]:o})}:{})}:{})},{}):{[e.path]:{message:e.message,type:e.type}})(r,a);return{values:{},errors:e(n)}}};export{r as yupResolver};
2
+ //# sourceMappingURL=yup.modern.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"yup.modern.js","sources":["../src/yup.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { Resolver, transformToNestObject, FieldValues } from 'react-hook-form';\nimport Yup from 'yup';\nimport Lazy from 'yup/lib/Lazy';\n\n/**\n * From 0.32.0, Yup add TypeScript support and `path` typing is optional that's why we have `@ts-expect-error`\n * FYI: `path`: a string, indicating where there error was thrown. `path` is empty at the root level.\n * react-hook-form's values are object so path is defined\n * https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string\n */\nconst parseErrorSchema = (\n error: Yup.ValidationError,\n validateAllFieldCriteria: boolean,\n) => {\n return Array.isArray(error.inner) && error.inner.length\n ? error.inner.reduce(\n (previous: Record<string, any>, { path, message, type }) => {\n // @ts-expect-error\n const previousTypes = (previous[path] && previous[path].types) || {};\n const key = path || type;\n\n return {\n ...previous,\n ...(key\n ? {\n [key]: {\n ...(previous[key] || {\n message,\n type,\n }),\n ...(validateAllFieldCriteria\n ? {\n types: {\n ...previousTypes,\n // @ts-expect-error\n [type]: previousTypes[type]\n ? // @ts-expect-error\n [...[].concat(previousTypes[type]), message]\n : message,\n },\n }\n : {}),\n },\n }\n : {}),\n };\n },\n {},\n )\n : {\n // @ts-expect-error\n [error.path]: { message: error.message, type: error.type },\n };\n};\n\ntype ValidateOptions<T extends Yup.AnyObjectSchema> = Parameters<\n T['validate']\n>[1];\n\nexport const yupResolver = <TFieldValues extends FieldValues>(\n schema: Yup.AnyObjectSchema | Lazy<any, any>,\n options: ValidateOptions<Yup.AnyObjectSchema> = {\n abortEarly: false,\n },\n): Resolver<TFieldValues> => async (\n values,\n context,\n validateAllFieldCriteria = false,\n) => {\n try {\n if (options.context && process.env.NODE_ENV === 'development') {\n // eslint-disable-next-line no-console\n console.warn(\n \"You should not used the yup options context. Please, use the 'useForm' context object instead\",\n );\n }\n return {\n values: await schema.validate(values, {\n ...options,\n context,\n }),\n errors: {},\n };\n } catch (e: any) {\n if (!e.inner) {\n throw e;\n }\n\n const parsedErrors = parseErrorSchema(e, validateAllFieldCriteria);\n return {\n values: {},\n errors: transformToNestObject(parsedErrors),\n };\n }\n};\n"],"names":["yupResolver","schema","options","abortEarly","async","values","context","validateAllFieldCriteria","process","env","NODE_ENV","console","warn","validate","errors","e","inner","parsedErrors","error","Array","isArray","length","reduce","previous","path","message","type","previousTypes","types","key","[object Object]","concat","parseErrorSchema","transformToNestObject"],"mappings":"uQAWA,MAiDaA,EAAc,CACzBC,EACAC,EAAgD,CAC9CC,YAAY,KAEaC,MAC3BC,EACAC,EACAC,GAA2B,KAE3B,IAOE,OANIL,EAAQI,SAAoC,gBAAzBE,QAAQC,IAAIC,UAEjCC,QAAQC,KACN,iGAGG,CACLP,aAAcJ,EAAOY,SAASR,OACzBH,GACHI,QAAAA,KAEFQ,OAAQ,IAEV,MAAOC,GACP,IAAKA,EAAEC,MACL,MAAMD,EAGR,MAAME,EA9Ee,EACvBC,EACAX,IAEOY,MAAMC,QAAQF,EAAMF,QAAUE,EAAMF,MAAMK,OAC7CH,EAAMF,MAAMM,OACV,CAACC,GAAiCC,KAAAA,EAAMC,QAAAA,EAASC,KAAAA,MAE/C,MAAMC,EAAiBJ,EAASC,IAASD,EAASC,GAAMI,OAAU,GAC5DC,EAAML,GAAQE,EAEpB,YACKH,EACCM,EACA,CACEC,CAACD,QACKN,EAASM,IAAQ,CACnBJ,QAAAA,EACAC,KAAAA,GAEEnB,EACA,CACEqB,WACKD,GAEHG,CAACJ,GAAOC,EAAcD,GAElB,IAAI,GAAGK,OAAOJ,EAAcD,IAAQD,GACpCA,KAGR,KAGR,KAGR,IAEF,CAEEK,CAACZ,EAAMM,MAAO,CAAEC,QAASP,EAAMO,QAASC,KAAMR,EAAMQ,OAqCnCM,CAAiBjB,EAAGR,GACzC,MAAO,CACLF,OAAQ,GACRS,OAAQmB,EAAsBhB"}
@@ -0,0 +1,2 @@
1
+ import{transformToNestObject as e}from"react-hook-form";function r(){return(r=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}var t=function(t,n){return void 0===n&&(n={abortEarly:!1}),function(o,a,s){void 0===s&&(s=!1);try{return Promise.resolve(function(e,s){try{var c=(n.context&&"development"===process.env.NODE_ENV&&console.warn("You should not used the yup options context. Please, use the 'useForm' context object instead"),Promise.resolve(t.validate(o,r({},n,{context:a}))).then(function(e){return{values:e,errors:{}}}))}catch(e){return s(e)}return c&&c.then?c.then(void 0,s):c}(0,function(t){if(!t.inner)throw t;var n=function(e,t){var n;return Array.isArray(e.inner)&&e.inner.length?e.inner.reduce(function(e,n){var o,a,s=n.path,c=n.message,u=n.type,i=e[s]&&e[s].types||{},p=s||u;return r({},e,p?((a={})[p]=r({},e[p]||{message:c,type:u},t?{types:r({},i,(o={},o[u]=i[u]?[].concat([].concat(i[u]),[c]):c,o))}:{}),a):{})},{}):((n={})[e.path]={message:e.message,type:e.type},n)}(t,s);return{values:{},errors:e(n)}}))}catch(e){return Promise.reject(e)}}};export{t as yupResolver};
2
+ //# sourceMappingURL=yup.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"yup.module.js","sources":["../src/yup.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { Resolver, transformToNestObject, FieldValues } from 'react-hook-form';\nimport Yup from 'yup';\nimport Lazy from 'yup/lib/Lazy';\n\n/**\n * From 0.32.0, Yup add TypeScript support and `path` typing is optional that's why we have `@ts-expect-error`\n * FYI: `path`: a string, indicating where there error was thrown. `path` is empty at the root level.\n * react-hook-form's values are object so path is defined\n * https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string\n */\nconst parseErrorSchema = (\n error: Yup.ValidationError,\n validateAllFieldCriteria: boolean,\n) => {\n return Array.isArray(error.inner) && error.inner.length\n ? error.inner.reduce(\n (previous: Record<string, any>, { path, message, type }) => {\n // @ts-expect-error\n const previousTypes = (previous[path] && previous[path].types) || {};\n const key = path || type;\n\n return {\n ...previous,\n ...(key\n ? {\n [key]: {\n ...(previous[key] || {\n message,\n type,\n }),\n ...(validateAllFieldCriteria\n ? {\n types: {\n ...previousTypes,\n // @ts-expect-error\n [type]: previousTypes[type]\n ? // @ts-expect-error\n [...[].concat(previousTypes[type]), message]\n : message,\n },\n }\n : {}),\n },\n }\n : {}),\n };\n },\n {},\n )\n : {\n // @ts-expect-error\n [error.path]: { message: error.message, type: error.type },\n };\n};\n\ntype ValidateOptions<T extends Yup.AnyObjectSchema> = Parameters<\n T['validate']\n>[1];\n\nexport const yupResolver = <TFieldValues extends FieldValues>(\n schema: Yup.AnyObjectSchema | Lazy<any, any>,\n options: ValidateOptions<Yup.AnyObjectSchema> = {\n abortEarly: false,\n },\n): Resolver<TFieldValues> => async (\n values,\n context,\n validateAllFieldCriteria = false,\n) => {\n try {\n if (options.context && process.env.NODE_ENV === 'development') {\n // eslint-disable-next-line no-console\n console.warn(\n \"You should not used the yup options context. Please, use the 'useForm' context object instead\",\n );\n }\n return {\n values: await schema.validate(values, {\n ...options,\n context,\n }),\n errors: {},\n };\n } catch (e: any) {\n if (!e.inner) {\n throw e;\n }\n\n const parsedErrors = parseErrorSchema(e, validateAllFieldCriteria);\n return {\n values: {},\n errors: transformToNestObject(parsedErrors),\n };\n }\n};\n"],"names":["yupResolver","schema","options","abortEarly","values","context","validateAllFieldCriteria","process","env","NODE_ENV","console","warn","validate","errors","e","inner","parsedErrors","error","Array","isArray","length","reduce","previous","path","message","type","previousTypes","types","key","concat","parseErrorSchema","transformToNestObject"],"mappings":"uQAWA,IAiDaA,EAAc,SACzBC,EACAC,mBAAAA,IAAAA,EAAgD,CAC9CC,YAAY,aAGdC,EACAC,EACAC,YAAAA,IAAAA,GAA2B,uDAGrBJ,EAAQG,SAAoC,gBAAzBE,QAAQC,IAAIC,UAEjCC,QAAQC,KACN,iHAIYV,EAAOW,SAASR,OACzBF,GACHG,QAAAA,uBAHJ,MAAO,CACLD,SAIAS,OAAQ,4EAEHC,GACP,IAAKA,EAAEC,MACL,MAAMD,EAGR,IAAME,EA9Ee,SACvBC,EACAX,SAEA,OAAOY,MAAMC,QAAQF,EAAMF,QAAUE,EAAMF,MAAMK,OAC7CH,EAAMF,MAAMM,OACV,SAACC,aAAiCC,IAAAA,KAAMC,IAAAA,QAASC,IAAAA,KAEzCC,EAAiBJ,EAASC,IAASD,EAASC,GAAMI,OAAU,GAC5DC,EAAML,GAAQE,EAEpB,YACKH,EACCM,UAEGA,QACKN,EAASM,IAAQ,CACnBJ,QAAAA,EACAC,KAAAA,GAEEnB,EACA,CACEqB,WACKD,UAEFD,GAAOC,EAAcD,aAEd,GAAGI,OAAOH,EAAcD,KAAQD,IACpCA,OAGR,OAGR,KAGR,YAICP,EAAMM,MAAO,CAAEC,QAASP,EAAMO,QAASC,KAAMR,EAAMQ,SAqCnCK,CAAiBhB,EAAGR,GACzC,MAAO,CACLF,OAAQ,GACRS,OAAQkB,EAAsBf,OAhCT"}
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","react-hook-form"],t):t((e||self).hookformResolversYup={},e.reactHookForm)}(this,function(e,t){function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e}).apply(this,arguments)}e.yupResolver=function(e,o){return void 0===o&&(o={abortEarly:!1}),function(n,s,a){void 0===a&&(a=!1);try{return Promise.resolve(function(t,a){try{var i=(o.context&&"development"===process.env.NODE_ENV&&console.warn("You should not used the yup options context. Please, use the 'useForm' context object instead"),Promise.resolve(e.validate(n,r({},o,{context:s}))).then(function(e){return{values:e,errors:{}}}))}catch(e){return a(e)}return i&&i.then?i.then(void 0,a):i}(0,function(e){if(!e.inner)throw e;var o=function(e,t){var o;return Array.isArray(e.inner)&&e.inner.length?e.inner.reduce(function(e,o){var n,s,a=o.path,i=o.message,u=o.type,c=e[a]&&e[a].types||{},f=a||u;return r({},e,f?((s={})[f]=r({},e[f]||{message:i,type:u},t?{types:r({},c,(n={},n[u]=c[u]?[].concat([].concat(c[u]),[i]):i,n))}:{}),s):{})},{}):((o={})[e.path]={message:e.message,type:e.type},o)}(e,a);return{values:{},errors:t.transformToNestObject(o)}}))}catch(e){return Promise.reject(e)}}}});
2
+ //# sourceMappingURL=yup.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"yup.umd.js","sources":["../src/yup.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { Resolver, transformToNestObject, FieldValues } from 'react-hook-form';\nimport Yup from 'yup';\nimport Lazy from 'yup/lib/Lazy';\n\n/**\n * From 0.32.0, Yup add TypeScript support and `path` typing is optional that's why we have `@ts-expect-error`\n * FYI: `path`: a string, indicating where there error was thrown. `path` is empty at the root level.\n * react-hook-form's values are object so path is defined\n * https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string\n */\nconst parseErrorSchema = (\n error: Yup.ValidationError,\n validateAllFieldCriteria: boolean,\n) => {\n return Array.isArray(error.inner) && error.inner.length\n ? error.inner.reduce(\n (previous: Record<string, any>, { path, message, type }) => {\n // @ts-expect-error\n const previousTypes = (previous[path] && previous[path].types) || {};\n const key = path || type;\n\n return {\n ...previous,\n ...(key\n ? {\n [key]: {\n ...(previous[key] || {\n message,\n type,\n }),\n ...(validateAllFieldCriteria\n ? {\n types: {\n ...previousTypes,\n // @ts-expect-error\n [type]: previousTypes[type]\n ? // @ts-expect-error\n [...[].concat(previousTypes[type]), message]\n : message,\n },\n }\n : {}),\n },\n }\n : {}),\n };\n },\n {},\n )\n : {\n // @ts-expect-error\n [error.path]: { message: error.message, type: error.type },\n };\n};\n\ntype ValidateOptions<T extends Yup.AnyObjectSchema> = Parameters<\n T['validate']\n>[1];\n\nexport const yupResolver = <TFieldValues extends FieldValues>(\n schema: Yup.AnyObjectSchema | Lazy<any, any>,\n options: ValidateOptions<Yup.AnyObjectSchema> = {\n abortEarly: false,\n },\n): Resolver<TFieldValues> => async (\n values,\n context,\n validateAllFieldCriteria = false,\n) => {\n try {\n if (options.context && process.env.NODE_ENV === 'development') {\n // eslint-disable-next-line no-console\n console.warn(\n \"You should not used the yup options context. Please, use the 'useForm' context object instead\",\n );\n }\n return {\n values: await schema.validate(values, {\n ...options,\n context,\n }),\n errors: {},\n };\n } catch (e: any) {\n if (!e.inner) {\n throw e;\n }\n\n const parsedErrors = parseErrorSchema(e, validateAllFieldCriteria);\n return {\n values: {},\n errors: transformToNestObject(parsedErrors),\n };\n }\n};\n"],"names":["schema","options","abortEarly","values","context","validateAllFieldCriteria","process","env","NODE_ENV","console","warn","validate","errors","e","inner","parsedErrors","error","Array","isArray","length","reduce","previous","path","message","type","previousTypes","types","key","concat","parseErrorSchema","transformToNestObject"],"mappings":"0gBA4D2B,SACzBA,EACAC,mBAAAA,IAAAA,EAAgD,CAC9CC,YAAY,aAGdC,EACAC,EACAC,YAAAA,IAAAA,GAA2B,uDAGrBJ,EAAQG,SAAoC,gBAAzBE,QAAQC,IAAIC,UAEjCC,QAAQC,KACN,iHAIYV,EAAOW,SAASR,OACzBF,GACHG,QAAAA,uBAHJ,MAAO,CACLD,SAIAS,OAAQ,4EAEHC,GACP,IAAKA,EAAEC,MACL,MAAMD,EAGR,IAAME,EA9Ee,SACvBC,EACAX,SAEA,OAAOY,MAAMC,QAAQF,EAAMF,QAAUE,EAAMF,MAAMK,OAC7CH,EAAMF,MAAMM,OACV,SAACC,aAAiCC,IAAAA,KAAMC,IAAAA,QAASC,IAAAA,KAEzCC,EAAiBJ,EAASC,IAASD,EAASC,GAAMI,OAAU,GAC5DC,EAAML,GAAQE,EAEpB,YACKH,EACCM,UAEGA,QACKN,EAASM,IAAQ,CACnBJ,QAAAA,EACAC,KAAAA,GAEEnB,EACA,CACEqB,WACKD,UAEFD,GAAOC,EAAcD,aAEd,GAAGI,OAAOH,EAAcD,KAAQD,IACpCA,OAGR,OAGR,KAGR,YAICP,EAAMM,MAAO,CAAEC,QAASP,EAAMO,QAASC,KAAMR,EAAMQ,SAqCnCK,CAAiBhB,EAAGR,GACzC,MAAO,CACLF,OAAQ,GACRS,OAAQkB,wBAAsBf,OAhCT"}
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "yup",
3
+ "amdName": "hookformResolversYup",
4
+ "version": "1.0.0",
5
+ "private": true,
6
+ "description": "React Hook Form validation resolver: yup",
7
+ "main": "dist/yup.js",
8
+ "module": "dist/yup.module.js",
9
+ "umd:main": "dist/yup.umd.js",
10
+ "source": "src/index.ts",
11
+ "types": "dist/index.d.ts",
12
+ "license": "MIT",
13
+ "peerDependencies": {
14
+ "react-hook-form": ">=6.6.0",
15
+ "@hookform/resolvers": "^1.0.0"
16
+ }
17
+ }
@@ -0,0 +1,119 @@
1
+ // Jest Snapshot v1, https://goo.gl/fbAQLP
2
+
3
+ exports[`validateWithSchema should return undefined when no error reported 1`] = `
4
+ Object {
5
+ "errors": Object {
6
+ "age": Object {
7
+ "message": "age is a required field",
8
+ "type": "required",
9
+ },
10
+ "name": Object {
11
+ "message": "name is a required field",
12
+ "type": "required",
13
+ },
14
+ },
15
+ "values": Object {},
16
+ }
17
+ `;
18
+
19
+ exports[`yupResolver errors should get errors with validate all criteria fields 1`] = `
20
+ Object {
21
+ "errors": Object {
22
+ "age": Object {
23
+ "message": "age must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`\\"test\\"\`).",
24
+ "type": "typeError",
25
+ "types": Object {
26
+ "typeError": "age must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`\\"test\\"\`).",
27
+ },
28
+ },
29
+ "createdOn": Object {
30
+ "message": "createdOn must be a \`date\` type, but the final value was: \`Invalid Date\`.",
31
+ "type": "typeError",
32
+ "types": Object {
33
+ "typeError": "createdOn must be a \`date\` type, but the final value was: \`Invalid Date\`.",
34
+ },
35
+ },
36
+ "foo": Array [
37
+ Object {
38
+ "loose": Object {
39
+ "message": "foo[0].loose must be a \`boolean\` type, but the final value was: \`null\`.
40
+ If \\"null\\" is intended as an empty value be sure to mark the schema as \`.nullable()\`",
41
+ "type": "typeError",
42
+ "types": Object {
43
+ "typeError": "foo[0].loose must be a \`boolean\` type, but the final value was: \`null\`.
44
+ If \\"null\\" is intended as an empty value be sure to mark the schema as \`.nullable()\`",
45
+ },
46
+ },
47
+ },
48
+ ],
49
+ "password": Object {
50
+ "message": "password is a required field",
51
+ "type": "required",
52
+ "types": Object {
53
+ "matches": Array [
54
+ "Lowercase",
55
+ "Uppercase",
56
+ "Number",
57
+ "Special",
58
+ ],
59
+ "min": "password must be at least 8 characters",
60
+ "required": "password is a required field",
61
+ },
62
+ },
63
+ },
64
+ "values": Object {},
65
+ }
66
+ `;
67
+
68
+ exports[`yupResolver errors should get errors without validate all criteria fields 1`] = `
69
+ Object {
70
+ "errors": Object {
71
+ "age": Object {
72
+ "message": "age must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`\\"test\\"\`).",
73
+ "type": "typeError",
74
+ },
75
+ "createdOn": Object {
76
+ "message": "createdOn must be a \`date\` type, but the final value was: \`Invalid Date\`.",
77
+ "type": "typeError",
78
+ },
79
+ "foo": Array [
80
+ Object {
81
+ "loose": Object {
82
+ "message": "foo[0].loose must be a \`boolean\` type, but the final value was: \`null\`.
83
+ If \\"null\\" is intended as an empty value be sure to mark the schema as \`.nullable()\`",
84
+ "type": "typeError",
85
+ },
86
+ },
87
+ ],
88
+ "password": Object {
89
+ "message": "password is a required field",
90
+ "type": "required",
91
+ },
92
+ },
93
+ "values": Object {},
94
+ }
95
+ `;
96
+
97
+ exports[`yupResolver errors should return an error result if inner yup validation error has no path 1`] = `
98
+ Object {
99
+ "errors": Object {
100
+ "required": Object {
101
+ "message": "error1",
102
+ "type": "required",
103
+ },
104
+ },
105
+ "values": Object {},
106
+ }
107
+ `;
108
+
109
+ exports[`yupResolver should pass down the yup context 1`] = `
110
+ Object {
111
+ "errors": Object {
112
+ "name": Object {
113
+ "message": "name must be at least 6 characters",
114
+ "type": "min",
115
+ },
116
+ },
117
+ "values": Object {},
118
+ }
119
+ `;