@evervault/react-native 2.5.1 → 2.6.1

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 (157) hide show
  1. package/README.md +0 -2
  2. package/build/cjs/Card/Cvc.js +29 -0
  3. package/build/cjs/Card/Expiry.js +12 -0
  4. package/build/cjs/Card/Holder.js +15 -0
  5. package/build/cjs/Card/Number.js +27 -0
  6. package/build/cjs/Card/Root.js +70 -0
  7. package/build/cjs/Card/index.js +20 -0
  8. package/build/cjs/Card/schema.js +32 -0
  9. package/build/cjs/Card/types.js +21 -0
  10. package/build/cjs/Card/utils.js +87 -0
  11. package/build/cjs/EvervaultProvider.js +17 -0
  12. package/build/cjs/Input.js +107 -0
  13. package/build/cjs/ThreeDSecure/Frame.js +37 -0
  14. package/build/cjs/ThreeDSecure/Root.js +14 -0
  15. package/build/cjs/ThreeDSecure/config.js +7 -0
  16. package/build/cjs/ThreeDSecure/context.js +7 -0
  17. package/build/cjs/ThreeDSecure/event.js +20 -0
  18. package/build/cjs/ThreeDSecure/index.js +12 -0
  19. package/build/cjs/ThreeDSecure/session.js +141 -0
  20. package/build/cjs/ThreeDSecure/types.js +2 -0
  21. package/build/cjs/ThreeDSecure/useThreeDSecure.js +44 -0
  22. package/build/cjs/__mocks__/NativeEvervault.js +14 -0
  23. package/build/cjs/__mocks__/react-native-webview.js +10 -0
  24. package/build/cjs/context.js +7 -0
  25. package/build/cjs/index.js +25 -0
  26. package/build/cjs/node_modules/@hookform/resolvers/dist/resolvers.js +8 -0
  27. package/build/cjs/node_modules/@hookform/resolvers/zod/dist/zod.js +8 -0
  28. package/build/cjs/node_modules/react-hook-form/dist/index.esm.js +2221 -0
  29. package/build/cjs/node_modules/react-native-mask-input/lib/module/MaskInput.js +60 -0
  30. package/build/cjs/node_modules/react-native-mask-input/lib/module/formatWithMask.js +92 -0
  31. package/build/cjs/node_modules/react-native-mask-input/lib/module/index.js +10 -0
  32. package/build/cjs/node_modules/react-native-mask-input/lib/module/useMaskedInputProps.js +93 -0
  33. package/build/{index.cjs.js → cjs/node_modules/zod/lib/index.js} +193 -3490
  34. package/build/cjs/packages/card-validator/dist/evervault-card-validator.main.js +349 -0
  35. package/build/cjs/sdk.js +53 -0
  36. package/build/cjs/specs/NativeEvervault.js +7 -0
  37. package/build/cjs/useEvervault.js +14 -0
  38. package/build/cjs/utils.js +34 -0
  39. package/build/{Card → esm/Card}/Cvc.d.ts +0 -1
  40. package/build/esm/Card/Cvc.js +27 -0
  41. package/build/{Card → esm/Card}/Expiry.d.ts +0 -1
  42. package/build/esm/Card/Expiry.js +10 -0
  43. package/build/{Card → esm/Card}/Holder.d.ts +0 -1
  44. package/build/esm/Card/Holder.js +13 -0
  45. package/build/{Card → esm/Card}/Number.d.ts +0 -1
  46. package/build/esm/Card/Number.js +25 -0
  47. package/build/{Card → esm/Card}/Root.d.ts +0 -1
  48. package/build/esm/Card/Root.js +68 -0
  49. package/build/{Card → esm/Card}/index.d.ts +0 -1
  50. package/build/esm/Card/index.js +14 -0
  51. package/build/{Card → esm/Card}/schema.d.ts +0 -1
  52. package/build/esm/Card/schema.js +30 -0
  53. package/build/{Card → esm/Card}/types.d.ts +0 -1
  54. package/build/esm/Card/types.js +19 -0
  55. package/build/{Card → esm/Card}/utils.d.ts +0 -1
  56. package/build/esm/Card/utils.js +82 -0
  57. package/build/{EvervaultProvider.d.ts → esm/EvervaultProvider.d.ts} +0 -1
  58. package/build/esm/EvervaultProvider.js +15 -0
  59. package/build/{Input.d.ts → esm/Input.d.ts} +0 -1
  60. package/build/esm/Input.js +103 -0
  61. package/build/{ThreeDSecure → esm/ThreeDSecure}/Frame.d.ts +0 -1
  62. package/build/esm/ThreeDSecure/Frame.js +35 -0
  63. package/build/{ThreeDSecure → esm/ThreeDSecure}/Root.d.ts +0 -1
  64. package/build/esm/ThreeDSecure/Root.js +12 -0
  65. package/build/{ThreeDSecure → esm/ThreeDSecure}/config.d.ts +0 -1
  66. package/build/esm/ThreeDSecure/config.js +4 -0
  67. package/build/{ThreeDSecure → esm/ThreeDSecure}/context.d.ts +0 -1
  68. package/build/esm/ThreeDSecure/context.js +5 -0
  69. package/build/{ThreeDSecure → esm/ThreeDSecure}/event.d.ts +0 -1
  70. package/build/esm/ThreeDSecure/event.js +18 -0
  71. package/build/{ThreeDSecure → esm/ThreeDSecure}/index.d.ts +0 -1
  72. package/build/esm/ThreeDSecure/index.js +9 -0
  73. package/build/{ThreeDSecure → esm/ThreeDSecure}/session.d.ts +0 -1
  74. package/build/esm/ThreeDSecure/session.js +136 -0
  75. package/build/{ThreeDSecure → esm/ThreeDSecure}/types.d.ts +0 -1
  76. package/build/esm/ThreeDSecure/types.js +1 -0
  77. package/build/{ThreeDSecure → esm/ThreeDSecure}/useThreeDSecure.d.ts +0 -1
  78. package/build/esm/ThreeDSecure/useThreeDSecure.js +42 -0
  79. package/build/{__mocks__ → esm/__mocks__}/NativeEvervault.d.ts +0 -1
  80. package/build/esm/__mocks__/NativeEvervault.js +11 -0
  81. package/build/{__mocks__ → esm/__mocks__}/react-native-webview.d.ts +0 -1
  82. package/build/esm/__mocks__/react-native-webview.js +8 -0
  83. package/build/{context.d.ts → esm/context.d.ts} +0 -1
  84. package/build/esm/context.js +5 -0
  85. package/build/{index.d.ts → esm/index.d.ts} +0 -1
  86. package/build/esm/index.js +14 -0
  87. package/build/esm/node_modules/@hookform/resolvers/dist/resolvers.js +5 -0
  88. package/build/esm/node_modules/@hookform/resolvers/zod/dist/zod.js +6 -0
  89. package/build/esm/node_modules/react-hook-form/dist/index.esm.js +2211 -0
  90. package/build/esm/node_modules/react-native-mask-input/lib/module/MaskInput.js +37 -0
  91. package/build/esm/node_modules/react-native-mask-input/lib/module/formatWithMask.js +88 -0
  92. package/build/esm/node_modules/react-native-mask-input/lib/module/index.js +6 -0
  93. package/build/esm/node_modules/react-native-mask-input/lib/module/useMaskedInputProps.js +70 -0
  94. package/build/{index.esm.js → esm/node_modules/zod/lib/index.js} +1 -3377
  95. package/build/esm/packages/card-validator/dist/evervault-card-validator.main.js +345 -0
  96. package/build/{sdk.d.ts → esm/sdk.d.ts} +0 -1
  97. package/build/esm/sdk.js +51 -0
  98. package/build/{specs → esm/specs}/NativeEvervault.d.ts +0 -1
  99. package/build/esm/specs/NativeEvervault.js +5 -0
  100. package/build/{useEvervault.d.ts → esm/useEvervault.d.ts} +0 -1
  101. package/build/esm/useEvervault.js +12 -0
  102. package/build/{utils.d.ts → esm/utils.d.ts} +0 -1
  103. package/build/esm/utils.js +31 -0
  104. package/package.json +9 -20
  105. package/build/Card/Cvc.d.ts.map +0 -1
  106. package/build/Card/Cvc.test.d.ts +0 -2
  107. package/build/Card/Cvc.test.d.ts.map +0 -1
  108. package/build/Card/Expiry.d.ts.map +0 -1
  109. package/build/Card/Holder.d.ts.map +0 -1
  110. package/build/Card/Number.d.ts.map +0 -1
  111. package/build/Card/Number.test.d.ts +0 -2
  112. package/build/Card/Number.test.d.ts.map +0 -1
  113. package/build/Card/Root.d.ts.map +0 -1
  114. package/build/Card/Root.test.d.ts +0 -2
  115. package/build/Card/Root.test.d.ts.map +0 -1
  116. package/build/Card/index.d.ts.map +0 -1
  117. package/build/Card/schema.d.ts.map +0 -1
  118. package/build/Card/types.d.ts.map +0 -1
  119. package/build/Card/utils.d.ts.map +0 -1
  120. package/build/Card/utils.test.d.ts +0 -2
  121. package/build/Card/utils.test.d.ts.map +0 -1
  122. package/build/EvervaultProvider.d.ts.map +0 -1
  123. package/build/EvervaultProvider.test.d.ts +0 -2
  124. package/build/EvervaultProvider.test.d.ts.map +0 -1
  125. package/build/Input.d.ts.map +0 -1
  126. package/build/Input.test.d.ts +0 -2
  127. package/build/Input.test.d.ts.map +0 -1
  128. package/build/ThreeDSecure/Frame.d.ts.map +0 -1
  129. package/build/ThreeDSecure/Frame.test.d.ts +0 -2
  130. package/build/ThreeDSecure/Frame.test.d.ts.map +0 -1
  131. package/build/ThreeDSecure/Root.d.ts.map +0 -1
  132. package/build/ThreeDSecure/Root.test.d.ts +0 -2
  133. package/build/ThreeDSecure/Root.test.d.ts.map +0 -1
  134. package/build/ThreeDSecure/config.d.ts.map +0 -1
  135. package/build/ThreeDSecure/context.d.ts.map +0 -1
  136. package/build/ThreeDSecure/event.d.ts.map +0 -1
  137. package/build/ThreeDSecure/index.d.ts.map +0 -1
  138. package/build/ThreeDSecure/session.d.ts.map +0 -1
  139. package/build/ThreeDSecure/session.test.d.ts +0 -2
  140. package/build/ThreeDSecure/session.test.d.ts.map +0 -1
  141. package/build/ThreeDSecure/types.d.ts.map +0 -1
  142. package/build/ThreeDSecure/useThreeDSecure.d.ts.map +0 -1
  143. package/build/ThreeDSecure/useThreeDSecure.test.d.ts +0 -2
  144. package/build/ThreeDSecure/useThreeDSecure.test.d.ts.map +0 -1
  145. package/build/__mocks__/NativeEvervault.d.ts.map +0 -1
  146. package/build/__mocks__/react-native-webview.d.ts.map +0 -1
  147. package/build/context.d.ts.map +0 -1
  148. package/build/index.cjs.js.map +0 -1
  149. package/build/index.d.ts.map +0 -1
  150. package/build/sdk.d.ts.map +0 -1
  151. package/build/sdk.test.d.ts +0 -2
  152. package/build/sdk.test.d.ts.map +0 -1
  153. package/build/specs/NativeEvervault.d.ts.map +0 -1
  154. package/build/useEvervault.d.ts.map +0 -1
  155. package/build/useEvervault.test.d.ts +0 -2
  156. package/build/useEvervault.test.d.ts.map +0 -1
  157. package/build/utils.d.ts.map +0 -1
@@ -1,2307 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var reactNative = require('react-native');
4
- var jsxRuntime = require('react/jsx-runtime');
5
- var React = require('react');
6
- var reactNativeWebview = require('react-native-webview');
3
+ Object.defineProperty(exports, '__esModule', { value: true });
7
4
 
8
- function _interopNamespaceDefault(e) {
9
- var n = Object.create(null);
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- if (k !== 'default') {
13
- var d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: function () { return e[k]; }
17
- });
18
- }
19
- });
20
- }
21
- n.default = e;
22
- return Object.freeze(n);
23
- }
24
-
25
- var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
26
-
27
- const NativeEvervault = reactNative.TurboModuleRegistry.get("NativeEvervault");
28
-
29
- function getModule() {
30
- if (!NativeEvervault) {
31
- throw new Error("NativeEvervault is not available.");
32
- }
33
- return NativeEvervault;
34
- }
35
- const sdk = {
36
- verify() {
37
- getModule();
38
- return true;
39
- },
40
- initialize(teamId, appId) {
41
- const evervault = getModule();
42
- if (!teamId) {
43
- throw new Error("Team ID is required.");
44
- }
45
- if (!appId) {
46
- throw new Error("App ID is required.");
47
- }
48
- return evervault.initialize(teamId, appId);
49
- },
50
- async encrypt(instanceId, data) {
51
- const evervault = getModule();
52
- if (data === undefined) {
53
- return undefined;
54
- }
55
- else if (data === null) {
56
- return null;
57
- }
58
- else if (typeof data === "string") {
59
- return (await evervault.encryptString(instanceId, data));
60
- }
61
- else if (typeof data === "number") {
62
- return (await evervault.encryptNumber(instanceId, data));
63
- }
64
- else if (typeof data === "boolean") {
65
- return (await evervault.encryptBoolean(instanceId, data));
66
- }
67
- else if (Array.isArray(data)) {
68
- return (await evervault.encryptArray(instanceId, data));
69
- }
70
- else if (typeof data === "object") {
71
- return (await evervault.encryptObject(instanceId, data));
72
- }
73
- throw new Error("Unsupported data type.");
74
- },
75
- };
76
-
77
- const EvervaultContext = React.createContext(null);
78
-
79
- function EvervaultProvider({ teamId, appId, children, }) {
80
- const instanceId = React.useMemo(() => sdk.initialize(teamId, appId), [teamId, appId]);
81
- const encrypt = React.useCallback(function (data) {
82
- return sdk.encrypt(instanceId, data);
83
- }, [instanceId]);
84
- const context = React.useMemo(() => ({ teamId, appId, encrypt }), [teamId, appId, encrypt]);
85
- return (jsxRuntime.jsx(EvervaultContext.Provider, { value: context, children: children }));
86
- }
87
-
88
- function useEvervault() {
89
- const context = React.useContext(EvervaultContext);
90
- if (!context) {
91
- throw new Error("`useEvervault` must be used within an `EvervaultProvider`.");
92
- }
93
- return context;
94
- }
95
-
96
- var isCheckBoxInput = (element) => element.type === 'checkbox';
97
-
98
- var isDateObject = (value) => value instanceof Date;
99
-
100
- var isNullOrUndefined = (value) => value == null;
101
-
102
- const isObjectType = (value) => typeof value === 'object';
103
- var isObject = (value) => !isNullOrUndefined(value) &&
104
- !Array.isArray(value) &&
105
- isObjectType(value) &&
106
- !isDateObject(value);
107
-
108
- var getEventValue = (event) => isObject(event) && event.target
109
- ? isCheckBoxInput(event.target)
110
- ? event.target.checked
111
- : event.target.value
112
- : event;
113
-
114
- var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
115
-
116
- var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
117
-
118
- var isPlainObject = (tempObject) => {
119
- const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
120
- return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
121
- };
122
-
123
- var isWeb = typeof window !== 'undefined' &&
124
- typeof window.HTMLElement !== 'undefined' &&
125
- typeof document !== 'undefined';
126
-
127
- function cloneObject(data) {
128
- let copy;
129
- const isArray = Array.isArray(data);
130
- const isFileListInstance = typeof FileList !== 'undefined' ? data instanceof FileList : false;
131
- if (data instanceof Date) {
132
- copy = new Date(data);
133
- }
134
- else if (data instanceof Set) {
135
- copy = new Set(data);
136
- }
137
- else if (!(isWeb && (data instanceof Blob || isFileListInstance)) &&
138
- (isArray || isObject(data))) {
139
- copy = isArray ? [] : {};
140
- if (!isArray && !isPlainObject(data)) {
141
- copy = data;
142
- }
143
- else {
144
- for (const key in data) {
145
- if (data.hasOwnProperty(key)) {
146
- copy[key] = cloneObject(data[key]);
147
- }
148
- }
149
- }
150
- }
151
- else {
152
- return data;
153
- }
154
- return copy;
155
- }
156
-
157
- var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
158
-
159
- var isUndefined = (val) => val === undefined;
160
-
161
- var get = (object, path, defaultValue) => {
162
- if (!path || !isObject(object)) {
163
- return defaultValue;
164
- }
165
- const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);
166
- return isUndefined(result) || result === object
167
- ? isUndefined(object[path])
168
- ? defaultValue
169
- : object[path]
170
- : result;
171
- };
172
-
173
- var isBoolean = (value) => typeof value === 'boolean';
174
-
175
- var isKey = (value) => /^\w*$/.test(value);
176
-
177
- var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
178
-
179
- var set = (object, path, value) => {
180
- let index = -1;
181
- const tempPath = isKey(path) ? [path] : stringToPath(path);
182
- const length = tempPath.length;
183
- const lastIndex = length - 1;
184
- while (++index < length) {
185
- const key = tempPath[index];
186
- let newValue = value;
187
- if (index !== lastIndex) {
188
- const objValue = object[key];
189
- newValue =
190
- isObject(objValue) || Array.isArray(objValue)
191
- ? objValue
192
- : !isNaN(+tempPath[index + 1])
193
- ? []
194
- : {};
195
- }
196
- if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
197
- return;
198
- }
199
- object[key] = newValue;
200
- object = object[key];
201
- }
202
- return object;
203
- };
204
-
205
- const EVENTS = {
206
- BLUR: 'blur',
207
- FOCUS_OUT: 'focusout',
208
- CHANGE: 'change',
209
- };
210
- const VALIDATION_MODE = {
211
- onBlur: 'onBlur',
212
- onChange: 'onChange',
213
- onSubmit: 'onSubmit',
214
- onTouched: 'onTouched',
215
- all: 'all',
216
- };
217
- const INPUT_VALIDATION_RULES = {
218
- max: 'max',
219
- min: 'min',
220
- maxLength: 'maxLength',
221
- minLength: 'minLength',
222
- pattern: 'pattern',
223
- required: 'required',
224
- validate: 'validate',
225
- };
226
-
227
- const HookFormContext = React.createContext(null);
228
- /**
229
- * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
230
- *
231
- * @remarks
232
- * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
233
- *
234
- * @returns return all useForm methods
235
- *
236
- * @example
237
- * ```tsx
238
- * function App() {
239
- * const methods = useForm();
240
- * const onSubmit = data => console.log(data);
241
- *
242
- * return (
243
- * <FormProvider {...methods} >
244
- * <form onSubmit={methods.handleSubmit(onSubmit)}>
245
- * <NestedInput />
246
- * <input type="submit" />
247
- * </form>
248
- * </FormProvider>
249
- * );
250
- * }
251
- *
252
- * function NestedInput() {
253
- * const { register } = useFormContext(); // retrieve all hook methods
254
- * return <input {...register("test")} />;
255
- * }
256
- * ```
257
- */
258
- const useFormContext = () => React.useContext(HookFormContext);
259
- /**
260
- * A provider component that propagates the `useForm` methods to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useFormContext}.
261
- *
262
- * @remarks
263
- * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
264
- *
265
- * @param props - all useForm methods
266
- *
267
- * @example
268
- * ```tsx
269
- * function App() {
270
- * const methods = useForm();
271
- * const onSubmit = data => console.log(data);
272
- *
273
- * return (
274
- * <FormProvider {...methods} >
275
- * <form onSubmit={methods.handleSubmit(onSubmit)}>
276
- * <NestedInput />
277
- * <input type="submit" />
278
- * </form>
279
- * </FormProvider>
280
- * );
281
- * }
282
- *
283
- * function NestedInput() {
284
- * const { register } = useFormContext(); // retrieve all hook methods
285
- * return <input {...register("test")} />;
286
- * }
287
- * ```
288
- */
289
- const FormProvider = (props) => {
290
- const { children, ...data } = props;
291
- return (React.createElement(HookFormContext.Provider, { value: data }, children));
292
- };
293
-
294
- var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
295
- const result = {
296
- defaultValues: control._defaultValues,
297
- };
298
- for (const key in formState) {
299
- Object.defineProperty(result, key, {
300
- get: () => {
301
- const _key = key;
302
- if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
303
- control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
304
- }
305
- localProxyFormState && (localProxyFormState[_key] = true);
306
- return formState[_key];
307
- },
308
- });
309
- }
310
- return result;
311
- };
312
-
313
- var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
314
-
315
- var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
316
- updateFormState(formStateData);
317
- const { name, ...formState } = formStateData;
318
- return (isEmptyObject(formState) ||
319
- Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
320
- Object.keys(formState).find((key) => _proxyFormState[key] ===
321
- (!isRoot || VALIDATION_MODE.all)));
322
- };
323
-
324
- var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
325
-
326
- var shouldSubscribeByName = (name, signalName, exact) => !name ||
327
- !signalName ||
328
- name === signalName ||
329
- convertToArrayPayload(name).some((currentName) => currentName &&
330
- (exact
331
- ? currentName === signalName
332
- : currentName.startsWith(signalName) ||
333
- signalName.startsWith(currentName)));
334
-
335
- function useSubscribe(props) {
336
- const _props = React.useRef(props);
337
- _props.current = props;
338
- React.useEffect(() => {
339
- const subscription = !props.disabled &&
340
- _props.current.subject &&
341
- _props.current.subject.subscribe({
342
- next: _props.current.next,
343
- });
344
- return () => {
345
- subscription && subscription.unsubscribe();
346
- };
347
- }, [props.disabled]);
348
- }
349
-
350
- /**
351
- * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
352
- *
353
- * @remarks
354
- * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
355
- *
356
- * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
357
- *
358
- * @example
359
- * ```tsx
360
- * function App() {
361
- * const { register, handleSubmit, control } = useForm({
362
- * defaultValues: {
363
- * firstName: "firstName"
364
- * }});
365
- * const { dirtyFields } = useFormState({
366
- * control
367
- * });
368
- * const onSubmit = (data) => console.log(data);
369
- *
370
- * return (
371
- * <form onSubmit={handleSubmit(onSubmit)}>
372
- * <input {...register("firstName")} placeholder="First Name" />
373
- * {dirtyFields.firstName && <p>Field is dirty.</p>}
374
- * <input type="submit" />
375
- * </form>
376
- * );
377
- * }
378
- * ```
379
- */
380
- function useFormState(props) {
381
- const methods = useFormContext();
382
- const { control = methods.control, disabled, name, exact } = props || {};
383
- const [formState, updateFormState] = React.useState(control._formState);
384
- const _mounted = React.useRef(true);
385
- const _localProxyFormState = React.useRef({
386
- isDirty: false,
387
- isLoading: false,
388
- dirtyFields: false,
389
- touchedFields: false,
390
- validatingFields: false,
391
- isValidating: false,
392
- isValid: false,
393
- errors: false,
394
- });
395
- const _name = React.useRef(name);
396
- _name.current = name;
397
- useSubscribe({
398
- disabled,
399
- next: (value) => _mounted.current &&
400
- shouldSubscribeByName(_name.current, value.name, exact) &&
401
- shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
402
- updateFormState({
403
- ...control._formState,
404
- ...value,
405
- }),
406
- subject: control._subjects.state,
407
- });
408
- React.useEffect(() => {
409
- _mounted.current = true;
410
- _localProxyFormState.current.isValid && control._updateValid(true);
411
- return () => {
412
- _mounted.current = false;
413
- };
414
- }, [control]);
415
- return React.useMemo(() => getProxyFormState(formState, control, _localProxyFormState.current, false), [formState, control]);
416
- }
417
-
418
- var isString = (value) => typeof value === 'string';
419
-
420
- var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
421
- if (isString(names)) {
422
- isGlobal && _names.watch.add(names);
423
- return get(formValues, names, defaultValue);
424
- }
425
- if (Array.isArray(names)) {
426
- return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
427
- }
428
- isGlobal && (_names.watchAll = true);
429
- return formValues;
430
- };
431
-
432
- /**
433
- * Custom hook to subscribe to field change and isolate re-rendering at the component level.
434
- *
435
- * @remarks
436
- *
437
- * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
438
- *
439
- * @example
440
- * ```tsx
441
- * const { control } = useForm();
442
- * const values = useWatch({
443
- * name: "fieldName"
444
- * control,
445
- * })
446
- * ```
447
- */
448
- function useWatch(props) {
449
- const methods = useFormContext();
450
- const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};
451
- const _name = React.useRef(name);
452
- _name.current = name;
453
- useSubscribe({
454
- disabled,
455
- subject: control._subjects.values,
456
- next: (formState) => {
457
- if (shouldSubscribeByName(_name.current, formState.name, exact)) {
458
- updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
459
- }
460
- },
461
- });
462
- const [value, updateValue] = React.useState(control._getWatch(name, defaultValue));
463
- React.useEffect(() => control._removeUnmounted());
464
- return value;
465
- }
466
-
467
- /**
468
- * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
469
- *
470
- * @remarks
471
- * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
472
- *
473
- * @param props - the path name to the form field value, and validation rules.
474
- *
475
- * @returns field properties, field and form state. {@link UseControllerReturn}
476
- *
477
- * @example
478
- * ```tsx
479
- * function Input(props) {
480
- * const { field, fieldState, formState } = useController(props);
481
- * return (
482
- * <div>
483
- * <input {...field} placeholder={props.name} />
484
- * <p>{fieldState.isTouched && "Touched"}</p>
485
- * <p>{formState.isSubmitted ? "submitted" : ""}</p>
486
- * </div>
487
- * );
488
- * }
489
- * ```
490
- */
491
- function useController(props) {
492
- const methods = useFormContext();
493
- const { name, disabled, control = methods.control, shouldUnregister } = props;
494
- const isArrayField = isNameInFieldArray(control._names.array, name);
495
- const value = useWatch({
496
- control,
497
- name,
498
- defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
499
- exact: true,
500
- });
501
- const formState = useFormState({
502
- control,
503
- name,
504
- exact: true,
505
- });
506
- const _registerProps = React.useRef(control.register(name, {
507
- ...props.rules,
508
- value,
509
- ...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}),
510
- }));
511
- const fieldState = React.useMemo(() => Object.defineProperties({}, {
512
- invalid: {
513
- enumerable: true,
514
- get: () => !!get(formState.errors, name),
515
- },
516
- isDirty: {
517
- enumerable: true,
518
- get: () => !!get(formState.dirtyFields, name),
519
- },
520
- isTouched: {
521
- enumerable: true,
522
- get: () => !!get(formState.touchedFields, name),
523
- },
524
- isValidating: {
525
- enumerable: true,
526
- get: () => !!get(formState.validatingFields, name),
527
- },
528
- error: {
529
- enumerable: true,
530
- get: () => get(formState.errors, name),
531
- },
532
- }), [formState, name]);
533
- const field = React.useMemo(() => ({
534
- name,
535
- value,
536
- ...(isBoolean(disabled) || formState.disabled
537
- ? { disabled: formState.disabled || disabled }
538
- : {}),
539
- onChange: (event) => _registerProps.current.onChange({
540
- target: {
541
- value: getEventValue(event),
542
- name: name,
543
- },
544
- type: EVENTS.CHANGE,
545
- }),
546
- onBlur: () => _registerProps.current.onBlur({
547
- target: {
548
- value: get(control._formValues, name),
549
- name: name,
550
- },
551
- type: EVENTS.BLUR,
552
- }),
553
- ref: (elm) => {
554
- const field = get(control._fields, name);
555
- if (field && elm) {
556
- field._f.ref = {
557
- focus: () => elm.focus(),
558
- select: () => elm.select(),
559
- setCustomValidity: (message) => elm.setCustomValidity(message),
560
- reportValidity: () => elm.reportValidity(),
561
- };
562
- }
563
- },
564
- }), [
565
- name,
566
- control._formValues,
567
- disabled,
568
- formState.disabled,
569
- value,
570
- control._fields,
571
- ]);
572
- React.useEffect(() => {
573
- const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
574
- const updateMounted = (name, value) => {
575
- const field = get(control._fields, name);
576
- if (field && field._f) {
577
- field._f.mount = value;
578
- }
579
- };
580
- updateMounted(name, true);
581
- if (_shouldUnregisterField) {
582
- const value = cloneObject(get(control._options.defaultValues, name));
583
- set(control._defaultValues, name, value);
584
- if (isUndefined(get(control._formValues, name))) {
585
- set(control._formValues, name, value);
586
- }
587
- }
588
- !isArrayField && control.register(name);
589
- return () => {
590
- (isArrayField
591
- ? _shouldUnregisterField && !control._state.action
592
- : _shouldUnregisterField)
593
- ? control.unregister(name)
594
- : updateMounted(name, false);
595
- };
596
- }, [name, control, isArrayField, shouldUnregister]);
597
- React.useEffect(() => {
598
- control._updateDisabledField({
599
- disabled,
600
- fields: control._fields,
601
- name,
602
- });
603
- }, [disabled, name, control]);
604
- return React.useMemo(() => ({
605
- field,
606
- formState,
607
- fieldState,
608
- }), [field, formState, fieldState]);
609
- }
610
-
611
- var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
612
- ? {
613
- ...errors[name],
614
- types: {
615
- ...(errors[name] && errors[name].types ? errors[name].types : {}),
616
- [type]: message || true,
617
- },
618
- }
619
- : {};
620
-
621
- var getValidationModes = (mode) => ({
622
- isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
623
- isOnBlur: mode === VALIDATION_MODE.onBlur,
624
- isOnChange: mode === VALIDATION_MODE.onChange,
625
- isOnAll: mode === VALIDATION_MODE.all,
626
- isOnTouch: mode === VALIDATION_MODE.onTouched,
627
- });
628
-
629
- var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
630
- (_names.watchAll ||
631
- _names.watch.has(name) ||
632
- [..._names.watch].some((watchName) => name.startsWith(watchName) &&
633
- /^\.\w+/.test(name.slice(watchName.length))));
634
-
635
- const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
636
- for (const key of fieldsNames || Object.keys(fields)) {
637
- const field = get(fields, key);
638
- if (field) {
639
- const { _f, ...currentField } = field;
640
- if (_f) {
641
- if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
642
- return true;
643
- }
644
- else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
645
- return true;
646
- }
647
- else {
648
- if (iterateFieldsByAction(currentField, action)) {
649
- break;
650
- }
651
- }
652
- }
653
- else if (isObject(currentField)) {
654
- if (iterateFieldsByAction(currentField, action)) {
655
- break;
656
- }
657
- }
658
- }
659
- }
660
- return;
661
- };
662
-
663
- var updateFieldArrayRootError = (errors, error, name) => {
664
- const fieldArrayErrors = convertToArrayPayload(get(errors, name));
665
- set(fieldArrayErrors, 'root', error[name]);
666
- set(errors, name, fieldArrayErrors);
667
- return errors;
668
- };
669
-
670
- var isFileInput = (element) => element.type === 'file';
671
-
672
- var isFunction = (value) => typeof value === 'function';
673
-
674
- var isHTMLElement = (value) => {
675
- if (!isWeb) {
676
- return false;
677
- }
678
- const owner = value ? value.ownerDocument : 0;
679
- return (value instanceof
680
- (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
681
- };
682
-
683
- var isMessage = (value) => isString(value);
684
-
685
- var isRadioInput = (element) => element.type === 'radio';
686
-
687
- var isRegex = (value) => value instanceof RegExp;
688
-
689
- const defaultResult = {
690
- value: false,
691
- isValid: false,
692
- };
693
- const validResult = { value: true, isValid: true };
694
- var getCheckboxValue = (options) => {
695
- if (Array.isArray(options)) {
696
- if (options.length > 1) {
697
- const values = options
698
- .filter((option) => option && option.checked && !option.disabled)
699
- .map((option) => option.value);
700
- return { value: values, isValid: !!values.length };
701
- }
702
- return options[0].checked && !options[0].disabled
703
- ? // @ts-expect-error expected to work in the browser
704
- options[0].attributes && !isUndefined(options[0].attributes.value)
705
- ? isUndefined(options[0].value) || options[0].value === ''
706
- ? validResult
707
- : { value: options[0].value, isValid: true }
708
- : validResult
709
- : defaultResult;
710
- }
711
- return defaultResult;
712
- };
713
-
714
- const defaultReturn = {
715
- isValid: false,
716
- value: null,
717
- };
718
- var getRadioValue = (options) => Array.isArray(options)
719
- ? options.reduce((previous, option) => option && option.checked && !option.disabled
720
- ? {
721
- isValid: true,
722
- value: option.value,
723
- }
724
- : previous, defaultReturn)
725
- : defaultReturn;
726
-
727
- function getValidateError(result, ref, type = 'validate') {
728
- if (isMessage(result) ||
729
- (Array.isArray(result) && result.every(isMessage)) ||
730
- (isBoolean(result) && !result)) {
731
- return {
732
- type,
733
- message: isMessage(result) ? result : '',
734
- ref,
735
- };
736
- }
737
- }
738
-
739
- var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
740
- ? validationData
741
- : {
742
- value: validationData,
743
- message: '',
744
- };
745
-
746
- var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
747
- const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, } = field._f;
748
- const inputValue = get(formValues, name);
749
- if (!mount || disabledFieldNames.has(name)) {
750
- return {};
751
- }
752
- const inputRef = refs ? refs[0] : ref;
753
- const setCustomValidity = (message) => {
754
- if (shouldUseNativeValidation && inputRef.reportValidity) {
755
- inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
756
- inputRef.reportValidity();
757
- }
758
- };
759
- const error = {};
760
- const isRadio = isRadioInput(ref);
761
- const isCheckBox = isCheckBoxInput(ref);
762
- const isRadioOrCheckbox = isRadio || isCheckBox;
763
- const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
764
- isUndefined(ref.value) &&
765
- isUndefined(inputValue)) ||
766
- (isHTMLElement(ref) && ref.value === '') ||
767
- inputValue === '' ||
768
- (Array.isArray(inputValue) && !inputValue.length);
769
- const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
770
- const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
771
- const message = exceedMax ? maxLengthMessage : minLengthMessage;
772
- error[name] = {
773
- type: exceedMax ? maxType : minType,
774
- message,
775
- ref,
776
- ...appendErrorsCurry(exceedMax ? maxType : minType, message),
777
- };
778
- };
779
- if (isFieldArray
780
- ? !Array.isArray(inputValue) || !inputValue.length
781
- : required &&
782
- ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
783
- (isBoolean(inputValue) && !inputValue) ||
784
- (isCheckBox && !getCheckboxValue(refs).isValid) ||
785
- (isRadio && !getRadioValue(refs).isValid))) {
786
- const { value, message } = isMessage(required)
787
- ? { value: !!required, message: required }
788
- : getValueAndMessage(required);
789
- if (value) {
790
- error[name] = {
791
- type: INPUT_VALIDATION_RULES.required,
792
- message,
793
- ref: inputRef,
794
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
795
- };
796
- if (!validateAllFieldCriteria) {
797
- setCustomValidity(message);
798
- return error;
799
- }
800
- }
801
- }
802
- if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
803
- let exceedMax;
804
- let exceedMin;
805
- const maxOutput = getValueAndMessage(max);
806
- const minOutput = getValueAndMessage(min);
807
- if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
808
- const valueNumber = ref.valueAsNumber ||
809
- (inputValue ? +inputValue : inputValue);
810
- if (!isNullOrUndefined(maxOutput.value)) {
811
- exceedMax = valueNumber > maxOutput.value;
812
- }
813
- if (!isNullOrUndefined(minOutput.value)) {
814
- exceedMin = valueNumber < minOutput.value;
815
- }
816
- }
817
- else {
818
- const valueDate = ref.valueAsDate || new Date(inputValue);
819
- const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
820
- const isTime = ref.type == 'time';
821
- const isWeek = ref.type == 'week';
822
- if (isString(maxOutput.value) && inputValue) {
823
- exceedMax = isTime
824
- ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
825
- : isWeek
826
- ? inputValue > maxOutput.value
827
- : valueDate > new Date(maxOutput.value);
828
- }
829
- if (isString(minOutput.value) && inputValue) {
830
- exceedMin = isTime
831
- ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
832
- : isWeek
833
- ? inputValue < minOutput.value
834
- : valueDate < new Date(minOutput.value);
835
- }
836
- }
837
- if (exceedMax || exceedMin) {
838
- getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
839
- if (!validateAllFieldCriteria) {
840
- setCustomValidity(error[name].message);
841
- return error;
842
- }
843
- }
844
- }
845
- if ((maxLength || minLength) &&
846
- !isEmpty &&
847
- (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
848
- const maxLengthOutput = getValueAndMessage(maxLength);
849
- const minLengthOutput = getValueAndMessage(minLength);
850
- const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
851
- inputValue.length > +maxLengthOutput.value;
852
- const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
853
- inputValue.length < +minLengthOutput.value;
854
- if (exceedMax || exceedMin) {
855
- getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
856
- if (!validateAllFieldCriteria) {
857
- setCustomValidity(error[name].message);
858
- return error;
859
- }
860
- }
861
- }
862
- if (pattern && !isEmpty && isString(inputValue)) {
863
- const { value: patternValue, message } = getValueAndMessage(pattern);
864
- if (isRegex(patternValue) && !inputValue.match(patternValue)) {
865
- error[name] = {
866
- type: INPUT_VALIDATION_RULES.pattern,
867
- message,
868
- ref,
869
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
870
- };
871
- if (!validateAllFieldCriteria) {
872
- setCustomValidity(message);
873
- return error;
874
- }
875
- }
876
- }
877
- if (validate) {
878
- if (isFunction(validate)) {
879
- const result = await validate(inputValue, formValues);
880
- const validateError = getValidateError(result, inputRef);
881
- if (validateError) {
882
- error[name] = {
883
- ...validateError,
884
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
885
- };
886
- if (!validateAllFieldCriteria) {
887
- setCustomValidity(validateError.message);
888
- return error;
889
- }
890
- }
891
- }
892
- else if (isObject(validate)) {
893
- let validationResult = {};
894
- for (const key in validate) {
895
- if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
896
- break;
897
- }
898
- const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
899
- if (validateError) {
900
- validationResult = {
901
- ...validateError,
902
- ...appendErrorsCurry(key, validateError.message),
903
- };
904
- setCustomValidity(validateError.message);
905
- if (validateAllFieldCriteria) {
906
- error[name] = validationResult;
907
- }
908
- }
909
- }
910
- if (!isEmptyObject(validationResult)) {
911
- error[name] = {
912
- ref: inputRef,
913
- ...validationResult,
914
- };
915
- if (!validateAllFieldCriteria) {
916
- return error;
917
- }
918
- }
919
- }
920
- }
921
- setCustomValidity(true);
922
- return error;
923
- };
924
-
925
- function baseGet(object, updatePath) {
926
- const length = updatePath.slice(0, -1).length;
927
- let index = 0;
928
- while (index < length) {
929
- object = isUndefined(object) ? index++ : object[updatePath[index++]];
930
- }
931
- return object;
932
- }
933
- function isEmptyArray(obj) {
934
- for (const key in obj) {
935
- if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
936
- return false;
937
- }
938
- }
939
- return true;
940
- }
941
- function unset(object, path) {
942
- const paths = Array.isArray(path)
943
- ? path
944
- : isKey(path)
945
- ? [path]
946
- : stringToPath(path);
947
- const childObject = paths.length === 1 ? object : baseGet(object, paths);
948
- const index = paths.length - 1;
949
- const key = paths[index];
950
- if (childObject) {
951
- delete childObject[key];
952
- }
953
- if (index !== 0 &&
954
- ((isObject(childObject) && isEmptyObject(childObject)) ||
955
- (Array.isArray(childObject) && isEmptyArray(childObject)))) {
956
- unset(object, paths.slice(0, -1));
957
- }
958
- return object;
959
- }
960
-
961
- var createSubject = () => {
962
- let _observers = [];
963
- const next = (value) => {
964
- for (const observer of _observers) {
965
- observer.next && observer.next(value);
966
- }
967
- };
968
- const subscribe = (observer) => {
969
- _observers.push(observer);
970
- return {
971
- unsubscribe: () => {
972
- _observers = _observers.filter((o) => o !== observer);
973
- },
974
- };
975
- };
976
- const unsubscribe = () => {
977
- _observers = [];
978
- };
979
- return {
980
- get observers() {
981
- return _observers;
982
- },
983
- next,
984
- subscribe,
985
- unsubscribe,
986
- };
987
- };
988
-
989
- var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
990
-
991
- function deepEqual(object1, object2) {
992
- if (isPrimitive(object1) || isPrimitive(object2)) {
993
- return object1 === object2;
994
- }
995
- if (isDateObject(object1) && isDateObject(object2)) {
996
- return object1.getTime() === object2.getTime();
997
- }
998
- const keys1 = Object.keys(object1);
999
- const keys2 = Object.keys(object2);
1000
- if (keys1.length !== keys2.length) {
1001
- return false;
1002
- }
1003
- for (const key of keys1) {
1004
- const val1 = object1[key];
1005
- if (!keys2.includes(key)) {
1006
- return false;
1007
- }
1008
- if (key !== 'ref') {
1009
- const val2 = object2[key];
1010
- if ((isDateObject(val1) && isDateObject(val2)) ||
1011
- (isObject(val1) && isObject(val2)) ||
1012
- (Array.isArray(val1) && Array.isArray(val2))
1013
- ? !deepEqual(val1, val2)
1014
- : val1 !== val2) {
1015
- return false;
1016
- }
1017
- }
1018
- }
1019
- return true;
1020
- }
1021
-
1022
- var isMultipleSelect = (element) => element.type === `select-multiple`;
1023
-
1024
- var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
1025
-
1026
- var live = (ref) => isHTMLElement(ref) && ref.isConnected;
1027
-
1028
- var objectHasFunction = (data) => {
1029
- for (const key in data) {
1030
- if (isFunction(data[key])) {
1031
- return true;
1032
- }
1033
- }
1034
- return false;
1035
- };
1036
-
1037
- function markFieldsDirty(data, fields = {}) {
1038
- const isParentNodeArray = Array.isArray(data);
1039
- if (isObject(data) || isParentNodeArray) {
1040
- for (const key in data) {
1041
- if (Array.isArray(data[key]) ||
1042
- (isObject(data[key]) && !objectHasFunction(data[key]))) {
1043
- fields[key] = Array.isArray(data[key]) ? [] : {};
1044
- markFieldsDirty(data[key], fields[key]);
1045
- }
1046
- else if (!isNullOrUndefined(data[key])) {
1047
- fields[key] = true;
1048
- }
1049
- }
1050
- }
1051
- return fields;
1052
- }
1053
- function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
1054
- const isParentNodeArray = Array.isArray(data);
1055
- if (isObject(data) || isParentNodeArray) {
1056
- for (const key in data) {
1057
- if (Array.isArray(data[key]) ||
1058
- (isObject(data[key]) && !objectHasFunction(data[key]))) {
1059
- if (isUndefined(formValues) ||
1060
- isPrimitive(dirtyFieldsFromValues[key])) {
1061
- dirtyFieldsFromValues[key] = Array.isArray(data[key])
1062
- ? markFieldsDirty(data[key], [])
1063
- : { ...markFieldsDirty(data[key]) };
1064
- }
1065
- else {
1066
- getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1067
- }
1068
- }
1069
- else {
1070
- dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
1071
- }
1072
- }
1073
- }
1074
- return dirtyFieldsFromValues;
1075
- }
1076
- var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
1077
-
1078
- var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
1079
- ? value
1080
- : valueAsNumber
1081
- ? value === ''
1082
- ? NaN
1083
- : value
1084
- ? +value
1085
- : value
1086
- : valueAsDate && isString(value)
1087
- ? new Date(value)
1088
- : setValueAs
1089
- ? setValueAs(value)
1090
- : value;
1091
-
1092
- function getFieldValue(_f) {
1093
- const ref = _f.ref;
1094
- if (isFileInput(ref)) {
1095
- return ref.files;
1096
- }
1097
- if (isRadioInput(ref)) {
1098
- return getRadioValue(_f.refs).value;
1099
- }
1100
- if (isMultipleSelect(ref)) {
1101
- return [...ref.selectedOptions].map(({ value }) => value);
1102
- }
1103
- if (isCheckBoxInput(ref)) {
1104
- return getCheckboxValue(_f.refs).value;
1105
- }
1106
- return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1107
- }
1108
-
1109
- var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1110
- const fields = {};
1111
- for (const name of fieldsNames) {
1112
- const field = get(_fields, name);
1113
- field && set(fields, name, field._f);
1114
- }
1115
- return {
1116
- criteriaMode,
1117
- names: [...fieldsNames],
1118
- fields,
1119
- shouldUseNativeValidation,
1120
- };
1121
- };
1122
-
1123
- var getRuleValue = (rule) => isUndefined(rule)
1124
- ? rule
1125
- : isRegex(rule)
1126
- ? rule.source
1127
- : isObject(rule)
1128
- ? isRegex(rule.value)
1129
- ? rule.value.source
1130
- : rule.value
1131
- : rule;
1132
-
1133
- const ASYNC_FUNCTION = 'AsyncFunction';
1134
- var hasPromiseValidation = (fieldReference) => !!fieldReference &&
1135
- !!fieldReference.validate &&
1136
- !!((isFunction(fieldReference.validate) &&
1137
- fieldReference.validate.constructor.name === ASYNC_FUNCTION) ||
1138
- (isObject(fieldReference.validate) &&
1139
- Object.values(fieldReference.validate).find((validateFunction) => validateFunction.constructor.name === ASYNC_FUNCTION)));
1140
-
1141
- var hasValidation = (options) => options.mount &&
1142
- (options.required ||
1143
- options.min ||
1144
- options.max ||
1145
- options.maxLength ||
1146
- options.minLength ||
1147
- options.pattern ||
1148
- options.validate);
1149
-
1150
- function schemaErrorLookup(errors, _fields, name) {
1151
- const error = get(errors, name);
1152
- if (error || isKey(name)) {
1153
- return {
1154
- error,
1155
- name,
1156
- };
1157
- }
1158
- const names = name.split('.');
1159
- while (names.length) {
1160
- const fieldName = names.join('.');
1161
- const field = get(_fields, fieldName);
1162
- const foundError = get(errors, fieldName);
1163
- if (field && !Array.isArray(field) && name !== fieldName) {
1164
- return { name };
1165
- }
1166
- if (foundError && foundError.type) {
1167
- return {
1168
- name: fieldName,
1169
- error: foundError,
1170
- };
1171
- }
1172
- names.pop();
1173
- }
1174
- return {
1175
- name,
1176
- };
1177
- }
1178
-
1179
- var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1180
- if (mode.isOnAll) {
1181
- return false;
1182
- }
1183
- else if (!isSubmitted && mode.isOnTouch) {
1184
- return !(isTouched || isBlurEvent);
1185
- }
1186
- else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
1187
- return !isBlurEvent;
1188
- }
1189
- else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
1190
- return isBlurEvent;
1191
- }
1192
- return true;
1193
- };
1194
-
1195
- var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
1196
-
1197
- const defaultOptions = {
1198
- mode: VALIDATION_MODE.onSubmit,
1199
- reValidateMode: VALIDATION_MODE.onChange,
1200
- shouldFocusError: true,
1201
- };
1202
- function createFormControl(props = {}) {
1203
- let _options = {
1204
- ...defaultOptions,
1205
- ...props,
1206
- };
1207
- let _formState = {
1208
- submitCount: 0,
1209
- isDirty: false,
1210
- isLoading: isFunction(_options.defaultValues),
1211
- isValidating: false,
1212
- isSubmitted: false,
1213
- isSubmitting: false,
1214
- isSubmitSuccessful: false,
1215
- isValid: false,
1216
- touchedFields: {},
1217
- dirtyFields: {},
1218
- validatingFields: {},
1219
- errors: _options.errors || {},
1220
- disabled: _options.disabled || false,
1221
- };
1222
- let _fields = {};
1223
- let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
1224
- ? cloneObject(_options.defaultValues || _options.values) || {}
1225
- : {};
1226
- let _formValues = _options.shouldUnregister
1227
- ? {}
1228
- : cloneObject(_defaultValues);
1229
- let _state = {
1230
- action: false,
1231
- mount: false,
1232
- watch: false,
1233
- };
1234
- let _names = {
1235
- mount: new Set(),
1236
- disabled: new Set(),
1237
- unMount: new Set(),
1238
- array: new Set(),
1239
- watch: new Set(),
1240
- };
1241
- let delayErrorCallback;
1242
- let timer = 0;
1243
- const _proxyFormState = {
1244
- isDirty: false,
1245
- dirtyFields: false,
1246
- validatingFields: false,
1247
- touchedFields: false,
1248
- isValidating: false,
1249
- isValid: false,
1250
- errors: false,
1251
- };
1252
- const _subjects = {
1253
- values: createSubject(),
1254
- array: createSubject(),
1255
- state: createSubject(),
1256
- };
1257
- const validationModeBeforeSubmit = getValidationModes(_options.mode);
1258
- const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
1259
- const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1260
- const debounce = (callback) => (wait) => {
1261
- clearTimeout(timer);
1262
- timer = setTimeout(callback, wait);
1263
- };
1264
- const _updateValid = async (shouldUpdateValid) => {
1265
- if (!_options.disabled && (_proxyFormState.isValid || shouldUpdateValid)) {
1266
- const isValid = _options.resolver
1267
- ? isEmptyObject((await _executeSchema()).errors)
1268
- : await executeBuiltInValidation(_fields, true);
1269
- if (isValid !== _formState.isValid) {
1270
- _subjects.state.next({
1271
- isValid,
1272
- });
1273
- }
1274
- }
1275
- };
1276
- const _updateIsValidating = (names, isValidating) => {
1277
- if (!_options.disabled &&
1278
- (_proxyFormState.isValidating || _proxyFormState.validatingFields)) {
1279
- (names || Array.from(_names.mount)).forEach((name) => {
1280
- if (name) {
1281
- isValidating
1282
- ? set(_formState.validatingFields, name, isValidating)
1283
- : unset(_formState.validatingFields, name);
1284
- }
1285
- });
1286
- _subjects.state.next({
1287
- validatingFields: _formState.validatingFields,
1288
- isValidating: !isEmptyObject(_formState.validatingFields),
1289
- });
1290
- }
1291
- };
1292
- const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1293
- if (args && method && !_options.disabled) {
1294
- _state.action = true;
1295
- if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1296
- const fieldValues = method(get(_fields, name), args.argA, args.argB);
1297
- shouldSetValues && set(_fields, name, fieldValues);
1298
- }
1299
- if (shouldUpdateFieldsAndState &&
1300
- Array.isArray(get(_formState.errors, name))) {
1301
- const errors = method(get(_formState.errors, name), args.argA, args.argB);
1302
- shouldSetValues && set(_formState.errors, name, errors);
1303
- unsetEmptyArray(_formState.errors, name);
1304
- }
1305
- if (_proxyFormState.touchedFields &&
1306
- shouldUpdateFieldsAndState &&
1307
- Array.isArray(get(_formState.touchedFields, name))) {
1308
- const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1309
- shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1310
- }
1311
- if (_proxyFormState.dirtyFields) {
1312
- _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1313
- }
1314
- _subjects.state.next({
1315
- name,
1316
- isDirty: _getDirty(name, values),
1317
- dirtyFields: _formState.dirtyFields,
1318
- errors: _formState.errors,
1319
- isValid: _formState.isValid,
1320
- });
1321
- }
1322
- else {
1323
- set(_formValues, name, values);
1324
- }
1325
- };
1326
- const updateErrors = (name, error) => {
1327
- set(_formState.errors, name, error);
1328
- _subjects.state.next({
1329
- errors: _formState.errors,
1330
- });
1331
- };
1332
- const _setErrors = (errors) => {
1333
- _formState.errors = errors;
1334
- _subjects.state.next({
1335
- errors: _formState.errors,
1336
- isValid: false,
1337
- });
1338
- };
1339
- const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1340
- const field = get(_fields, name);
1341
- if (field) {
1342
- const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1343
- isUndefined(defaultValue) ||
1344
- (ref && ref.defaultChecked) ||
1345
- shouldSkipSetValueAs
1346
- ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
1347
- : setFieldValue(name, defaultValue);
1348
- _state.mount && _updateValid();
1349
- }
1350
- };
1351
- const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1352
- let shouldUpdateField = false;
1353
- let isPreviousDirty = false;
1354
- const output = {
1355
- name,
1356
- };
1357
- if (!_options.disabled) {
1358
- const disabledField = !!(get(_fields, name) &&
1359
- get(_fields, name)._f &&
1360
- get(_fields, name)._f.disabled);
1361
- if (!isBlurEvent || shouldDirty) {
1362
- if (_proxyFormState.isDirty) {
1363
- isPreviousDirty = _formState.isDirty;
1364
- _formState.isDirty = output.isDirty = _getDirty();
1365
- shouldUpdateField = isPreviousDirty !== output.isDirty;
1366
- }
1367
- const isCurrentFieldPristine = disabledField || deepEqual(get(_defaultValues, name), fieldValue);
1368
- isPreviousDirty = !!(!disabledField && get(_formState.dirtyFields, name));
1369
- isCurrentFieldPristine || disabledField
1370
- ? unset(_formState.dirtyFields, name)
1371
- : set(_formState.dirtyFields, name, true);
1372
- output.dirtyFields = _formState.dirtyFields;
1373
- shouldUpdateField =
1374
- shouldUpdateField ||
1375
- (_proxyFormState.dirtyFields &&
1376
- isPreviousDirty !== !isCurrentFieldPristine);
1377
- }
1378
- if (isBlurEvent) {
1379
- const isPreviousFieldTouched = get(_formState.touchedFields, name);
1380
- if (!isPreviousFieldTouched) {
1381
- set(_formState.touchedFields, name, isBlurEvent);
1382
- output.touchedFields = _formState.touchedFields;
1383
- shouldUpdateField =
1384
- shouldUpdateField ||
1385
- (_proxyFormState.touchedFields &&
1386
- isPreviousFieldTouched !== isBlurEvent);
1387
- }
1388
- }
1389
- shouldUpdateField && shouldRender && _subjects.state.next(output);
1390
- }
1391
- return shouldUpdateField ? output : {};
1392
- };
1393
- const shouldRenderByError = (name, isValid, error, fieldState) => {
1394
- const previousFieldError = get(_formState.errors, name);
1395
- const shouldUpdateValid = _proxyFormState.isValid &&
1396
- isBoolean(isValid) &&
1397
- _formState.isValid !== isValid;
1398
- if (_options.delayError && error) {
1399
- delayErrorCallback = debounce(() => updateErrors(name, error));
1400
- delayErrorCallback(_options.delayError);
1401
- }
1402
- else {
1403
- clearTimeout(timer);
1404
- delayErrorCallback = null;
1405
- error
1406
- ? set(_formState.errors, name, error)
1407
- : unset(_formState.errors, name);
1408
- }
1409
- if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
1410
- !isEmptyObject(fieldState) ||
1411
- shouldUpdateValid) {
1412
- const updatedFormState = {
1413
- ...fieldState,
1414
- ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
1415
- errors: _formState.errors,
1416
- name,
1417
- };
1418
- _formState = {
1419
- ..._formState,
1420
- ...updatedFormState,
1421
- };
1422
- _subjects.state.next(updatedFormState);
1423
- }
1424
- };
1425
- const _executeSchema = async (name) => {
1426
- _updateIsValidating(name, true);
1427
- const result = await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1428
- _updateIsValidating(name);
1429
- return result;
1430
- };
1431
- const executeSchemaAndUpdateState = async (names) => {
1432
- const { errors } = await _executeSchema(names);
1433
- if (names) {
1434
- for (const name of names) {
1435
- const error = get(errors, name);
1436
- error
1437
- ? set(_formState.errors, name, error)
1438
- : unset(_formState.errors, name);
1439
- }
1440
- }
1441
- else {
1442
- _formState.errors = errors;
1443
- }
1444
- return errors;
1445
- };
1446
- const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
1447
- valid: true,
1448
- }) => {
1449
- for (const name in fields) {
1450
- const field = fields[name];
1451
- if (field) {
1452
- const { _f, ...fieldValue } = field;
1453
- if (_f) {
1454
- const isFieldArrayRoot = _names.array.has(_f.name);
1455
- const isPromiseFunction = field._f && hasPromiseValidation(field._f);
1456
- if (isPromiseFunction && _proxyFormState.validatingFields) {
1457
- _updateIsValidating([name], true);
1458
- }
1459
- const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
1460
- if (isPromiseFunction && _proxyFormState.validatingFields) {
1461
- _updateIsValidating([name]);
1462
- }
1463
- if (fieldError[_f.name]) {
1464
- context.valid = false;
1465
- if (shouldOnlyCheckValid) {
1466
- break;
1467
- }
1468
- }
1469
- !shouldOnlyCheckValid &&
1470
- (get(fieldError, _f.name)
1471
- ? isFieldArrayRoot
1472
- ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
1473
- : set(_formState.errors, _f.name, fieldError[_f.name])
1474
- : unset(_formState.errors, _f.name));
1475
- }
1476
- !isEmptyObject(fieldValue) &&
1477
- (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
1478
- }
1479
- }
1480
- return context.valid;
1481
- };
1482
- const _removeUnmounted = () => {
1483
- for (const name of _names.unMount) {
1484
- const field = get(_fields, name);
1485
- field &&
1486
- (field._f.refs
1487
- ? field._f.refs.every((ref) => !live(ref))
1488
- : !live(field._f.ref)) &&
1489
- unregister(name);
1490
- }
1491
- _names.unMount = new Set();
1492
- };
1493
- const _getDirty = (name, data) => !_options.disabled &&
1494
- (name && data && set(_formValues, name, data),
1495
- !deepEqual(getValues(), _defaultValues));
1496
- const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1497
- ...(_state.mount
1498
- ? _formValues
1499
- : isUndefined(defaultValue)
1500
- ? _defaultValues
1501
- : isString(names)
1502
- ? { [names]: defaultValue }
1503
- : defaultValue),
1504
- }, isGlobal, defaultValue);
1505
- const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : []));
1506
- const setFieldValue = (name, value, options = {}) => {
1507
- const field = get(_fields, name);
1508
- let fieldValue = value;
1509
- if (field) {
1510
- const fieldReference = field._f;
1511
- if (fieldReference) {
1512
- !fieldReference.disabled &&
1513
- set(_formValues, name, getFieldValueAs(value, fieldReference));
1514
- fieldValue =
1515
- isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
1516
- ? ''
1517
- : value;
1518
- if (isMultipleSelect(fieldReference.ref)) {
1519
- [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
1520
- }
1521
- else if (fieldReference.refs) {
1522
- if (isCheckBoxInput(fieldReference.ref)) {
1523
- fieldReference.refs.length > 1
1524
- ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&
1525
- (checkboxRef.checked = Array.isArray(fieldValue)
1526
- ? !!fieldValue.find((data) => data === checkboxRef.value)
1527
- : fieldValue === checkboxRef.value))
1528
- : fieldReference.refs[0] &&
1529
- (fieldReference.refs[0].checked = !!fieldValue);
1530
- }
1531
- else {
1532
- fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
1533
- }
1534
- }
1535
- else if (isFileInput(fieldReference.ref)) {
1536
- fieldReference.ref.value = '';
1537
- }
1538
- else {
1539
- fieldReference.ref.value = fieldValue;
1540
- if (!fieldReference.ref.type) {
1541
- _subjects.values.next({
1542
- name,
1543
- values: { ..._formValues },
1544
- });
1545
- }
1546
- }
1547
- }
1548
- }
1549
- (options.shouldDirty || options.shouldTouch) &&
1550
- updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
1551
- options.shouldValidate && trigger(name);
1552
- };
1553
- const setValues = (name, value, options) => {
1554
- for (const fieldKey in value) {
1555
- const fieldValue = value[fieldKey];
1556
- const fieldName = `${name}.${fieldKey}`;
1557
- const field = get(_fields, fieldName);
1558
- (_names.array.has(name) ||
1559
- isObject(fieldValue) ||
1560
- (field && !field._f)) &&
1561
- !isDateObject(fieldValue)
1562
- ? setValues(fieldName, fieldValue, options)
1563
- : setFieldValue(fieldName, fieldValue, options);
1564
- }
1565
- };
1566
- const setValue = (name, value, options = {}) => {
1567
- const field = get(_fields, name);
1568
- const isFieldArray = _names.array.has(name);
1569
- const cloneValue = cloneObject(value);
1570
- set(_formValues, name, cloneValue);
1571
- if (isFieldArray) {
1572
- _subjects.array.next({
1573
- name,
1574
- values: { ..._formValues },
1575
- });
1576
- if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
1577
- options.shouldDirty) {
1578
- _subjects.state.next({
1579
- name,
1580
- dirtyFields: getDirtyFields(_defaultValues, _formValues),
1581
- isDirty: _getDirty(name, cloneValue),
1582
- });
1583
- }
1584
- }
1585
- else {
1586
- field && !field._f && !isNullOrUndefined(cloneValue)
1587
- ? setValues(name, cloneValue, options)
1588
- : setFieldValue(name, cloneValue, options);
1589
- }
1590
- isWatched(name, _names) && _subjects.state.next({ ..._formState });
1591
- _subjects.values.next({
1592
- name: _state.mount ? name : undefined,
1593
- values: { ..._formValues },
1594
- });
1595
- };
1596
- const onChange = async (event) => {
1597
- _state.mount = true;
1598
- const target = event.target;
1599
- let name = target.name;
1600
- let isFieldValueUpdated = true;
1601
- const field = get(_fields, name);
1602
- const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
1603
- const _updateIsFieldValueUpdated = (fieldValue) => {
1604
- isFieldValueUpdated =
1605
- Number.isNaN(fieldValue) ||
1606
- (isDateObject(fieldValue) && isNaN(fieldValue.getTime())) ||
1607
- deepEqual(fieldValue, get(_formValues, name, fieldValue));
1608
- };
1609
- if (field) {
1610
- let error;
1611
- let isValid;
1612
- const fieldValue = getCurrentFieldValue();
1613
- const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1614
- const shouldSkipValidation = (!hasValidation(field._f) &&
1615
- !_options.resolver &&
1616
- !get(_formState.errors, name) &&
1617
- !field._f.deps) ||
1618
- skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1619
- const watched = isWatched(name, _names, isBlurEvent);
1620
- set(_formValues, name, fieldValue);
1621
- if (isBlurEvent) {
1622
- field._f.onBlur && field._f.onBlur(event);
1623
- delayErrorCallback && delayErrorCallback(0);
1624
- }
1625
- else if (field._f.onChange) {
1626
- field._f.onChange(event);
1627
- }
1628
- const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
1629
- const shouldRender = !isEmptyObject(fieldState) || watched;
1630
- !isBlurEvent &&
1631
- _subjects.values.next({
1632
- name,
1633
- type: event.type,
1634
- values: { ..._formValues },
1635
- });
1636
- if (shouldSkipValidation) {
1637
- if (_proxyFormState.isValid) {
1638
- if (_options.mode === 'onBlur' && isBlurEvent) {
1639
- _updateValid();
1640
- }
1641
- else if (!isBlurEvent) {
1642
- _updateValid();
1643
- }
1644
- }
1645
- return (shouldRender &&
1646
- _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
1647
- }
1648
- !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1649
- if (_options.resolver) {
1650
- const { errors } = await _executeSchema([name]);
1651
- _updateIsFieldValueUpdated(fieldValue);
1652
- if (isFieldValueUpdated) {
1653
- const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1654
- const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1655
- error = errorLookupResult.error;
1656
- name = errorLookupResult.name;
1657
- isValid = isEmptyObject(errors);
1658
- }
1659
- }
1660
- else {
1661
- _updateIsValidating([name], true);
1662
- error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1663
- _updateIsValidating([name]);
1664
- _updateIsFieldValueUpdated(fieldValue);
1665
- if (isFieldValueUpdated) {
1666
- if (error) {
1667
- isValid = false;
1668
- }
1669
- else if (_proxyFormState.isValid) {
1670
- isValid = await executeBuiltInValidation(_fields, true);
1671
- }
1672
- }
1673
- }
1674
- if (isFieldValueUpdated) {
1675
- field._f.deps &&
1676
- trigger(field._f.deps);
1677
- shouldRenderByError(name, isValid, error, fieldState);
1678
- }
1679
- }
1680
- };
1681
- const _focusInput = (ref, key) => {
1682
- if (get(_formState.errors, key) && ref.focus) {
1683
- ref.focus();
1684
- return 1;
1685
- }
1686
- return;
1687
- };
1688
- const trigger = async (name, options = {}) => {
1689
- let isValid;
1690
- let validationResult;
1691
- const fieldNames = convertToArrayPayload(name);
1692
- if (_options.resolver) {
1693
- const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1694
- isValid = isEmptyObject(errors);
1695
- validationResult = name
1696
- ? !fieldNames.some((name) => get(errors, name))
1697
- : isValid;
1698
- }
1699
- else if (name) {
1700
- validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1701
- const field = get(_fields, fieldName);
1702
- return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1703
- }))).every(Boolean);
1704
- !(!validationResult && !_formState.isValid) && _updateValid();
1705
- }
1706
- else {
1707
- validationResult = isValid = await executeBuiltInValidation(_fields);
1708
- }
1709
- _subjects.state.next({
1710
- ...(!isString(name) ||
1711
- (_proxyFormState.isValid && isValid !== _formState.isValid)
1712
- ? {}
1713
- : { name }),
1714
- ...(_options.resolver || !name ? { isValid } : {}),
1715
- errors: _formState.errors,
1716
- });
1717
- options.shouldFocus &&
1718
- !validationResult &&
1719
- iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
1720
- return validationResult;
1721
- };
1722
- const getValues = (fieldNames) => {
1723
- const values = {
1724
- ...(_state.mount ? _formValues : _defaultValues),
1725
- };
1726
- return isUndefined(fieldNames)
1727
- ? values
1728
- : isString(fieldNames)
1729
- ? get(values, fieldNames)
1730
- : fieldNames.map((name) => get(values, name));
1731
- };
1732
- const getFieldState = (name, formState) => ({
1733
- invalid: !!get((formState || _formState).errors, name),
1734
- isDirty: !!get((formState || _formState).dirtyFields, name),
1735
- error: get((formState || _formState).errors, name),
1736
- isValidating: !!get(_formState.validatingFields, name),
1737
- isTouched: !!get((formState || _formState).touchedFields, name),
1738
- });
1739
- const clearErrors = (name) => {
1740
- name &&
1741
- convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1742
- _subjects.state.next({
1743
- errors: name ? _formState.errors : {},
1744
- });
1745
- };
1746
- const setError = (name, error, options) => {
1747
- const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1748
- const currentError = get(_formState.errors, name) || {};
1749
- // Don't override existing error messages elsewhere in the object tree.
1750
- const { ref: currentRef, message, type, ...restOfErrorTree } = currentError;
1751
- set(_formState.errors, name, {
1752
- ...restOfErrorTree,
1753
- ...error,
1754
- ref,
1755
- });
1756
- _subjects.state.next({
1757
- name,
1758
- errors: _formState.errors,
1759
- isValid: false,
1760
- });
1761
- options && options.shouldFocus && ref && ref.focus && ref.focus();
1762
- };
1763
- const watch = (name, defaultValue) => isFunction(name)
1764
- ? _subjects.values.subscribe({
1765
- next: (payload) => name(_getWatch(undefined, defaultValue), payload),
1766
- })
1767
- : _getWatch(name, defaultValue, true);
1768
- const unregister = (name, options = {}) => {
1769
- for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1770
- _names.mount.delete(fieldName);
1771
- _names.array.delete(fieldName);
1772
- if (!options.keepValue) {
1773
- unset(_fields, fieldName);
1774
- unset(_formValues, fieldName);
1775
- }
1776
- !options.keepError && unset(_formState.errors, fieldName);
1777
- !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1778
- !options.keepTouched && unset(_formState.touchedFields, fieldName);
1779
- !options.keepIsValidating &&
1780
- unset(_formState.validatingFields, fieldName);
1781
- !_options.shouldUnregister &&
1782
- !options.keepDefaultValue &&
1783
- unset(_defaultValues, fieldName);
1784
- }
1785
- _subjects.values.next({
1786
- values: { ..._formValues },
1787
- });
1788
- _subjects.state.next({
1789
- ..._formState,
1790
- ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
1791
- });
1792
- !options.keepIsValid && _updateValid();
1793
- };
1794
- const _updateDisabledField = ({ disabled, name, field, fields, }) => {
1795
- if ((isBoolean(disabled) && _state.mount) ||
1796
- !!disabled ||
1797
- _names.disabled.has(name)) {
1798
- disabled ? _names.disabled.add(name) : _names.disabled.delete(name);
1799
- updateTouchAndDirty(name, getFieldValue(field ? field._f : get(fields, name)._f), false, false, true);
1800
- }
1801
- };
1802
- const register = (name, options = {}) => {
1803
- let field = get(_fields, name);
1804
- const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled);
1805
- set(_fields, name, {
1806
- ...(field || {}),
1807
- _f: {
1808
- ...(field && field._f ? field._f : { ref: { name } }),
1809
- name,
1810
- mount: true,
1811
- ...options,
1812
- },
1813
- });
1814
- _names.mount.add(name);
1815
- if (field) {
1816
- _updateDisabledField({
1817
- field,
1818
- disabled: isBoolean(options.disabled)
1819
- ? options.disabled
1820
- : _options.disabled,
1821
- name,
1822
- });
1823
- }
1824
- else {
1825
- updateValidAndValue(name, true, options.value);
1826
- }
1827
- return {
1828
- ...(disabledIsDefined
1829
- ? { disabled: options.disabled || _options.disabled }
1830
- : {}),
1831
- ...(_options.progressive
1832
- ? {
1833
- required: !!options.required,
1834
- min: getRuleValue(options.min),
1835
- max: getRuleValue(options.max),
1836
- minLength: getRuleValue(options.minLength),
1837
- maxLength: getRuleValue(options.maxLength),
1838
- pattern: getRuleValue(options.pattern),
1839
- }
1840
- : {}),
1841
- name,
1842
- onChange,
1843
- onBlur: onChange,
1844
- ref: (ref) => {
1845
- if (ref) {
1846
- register(name, options);
1847
- field = get(_fields, name);
1848
- const fieldRef = isUndefined(ref.value)
1849
- ? ref.querySelectorAll
1850
- ? ref.querySelectorAll('input,select,textarea')[0] || ref
1851
- : ref
1852
- : ref;
1853
- const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1854
- const refs = field._f.refs || [];
1855
- if (radioOrCheckbox
1856
- ? refs.find((option) => option === fieldRef)
1857
- : fieldRef === field._f.ref) {
1858
- return;
1859
- }
1860
- set(_fields, name, {
1861
- _f: {
1862
- ...field._f,
1863
- ...(radioOrCheckbox
1864
- ? {
1865
- refs: [
1866
- ...refs.filter(live),
1867
- fieldRef,
1868
- ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
1869
- ],
1870
- ref: { type: fieldRef.type, name },
1871
- }
1872
- : { ref: fieldRef }),
1873
- },
1874
- });
1875
- updateValidAndValue(name, false, undefined, fieldRef);
1876
- }
1877
- else {
1878
- field = get(_fields, name, {});
1879
- if (field._f) {
1880
- field._f.mount = false;
1881
- }
1882
- (_options.shouldUnregister || options.shouldUnregister) &&
1883
- !(isNameInFieldArray(_names.array, name) && _state.action) &&
1884
- _names.unMount.add(name);
1885
- }
1886
- },
1887
- };
1888
- };
1889
- const _focusError = () => _options.shouldFocusError &&
1890
- iterateFieldsByAction(_fields, _focusInput, _names.mount);
1891
- const _disableForm = (disabled) => {
1892
- if (isBoolean(disabled)) {
1893
- _subjects.state.next({ disabled });
1894
- iterateFieldsByAction(_fields, (ref, name) => {
1895
- const currentField = get(_fields, name);
1896
- if (currentField) {
1897
- ref.disabled = currentField._f.disabled || disabled;
1898
- if (Array.isArray(currentField._f.refs)) {
1899
- currentField._f.refs.forEach((inputRef) => {
1900
- inputRef.disabled = currentField._f.disabled || disabled;
1901
- });
1902
- }
1903
- }
1904
- }, 0, false);
1905
- }
1906
- };
1907
- const handleSubmit = (onValid, onInvalid) => async (e) => {
1908
- let onValidError = undefined;
1909
- if (e) {
1910
- e.preventDefault && e.preventDefault();
1911
- e.persist && e.persist();
1912
- }
1913
- let fieldValues = cloneObject(_formValues);
1914
- if (_names.disabled.size) {
1915
- for (const name of _names.disabled) {
1916
- set(fieldValues, name, undefined);
1917
- }
1918
- }
1919
- _subjects.state.next({
1920
- isSubmitting: true,
1921
- });
1922
- if (_options.resolver) {
1923
- const { errors, values } = await _executeSchema();
1924
- _formState.errors = errors;
1925
- fieldValues = values;
1926
- }
1927
- else {
1928
- await executeBuiltInValidation(_fields);
1929
- }
1930
- unset(_formState.errors, 'root');
1931
- if (isEmptyObject(_formState.errors)) {
1932
- _subjects.state.next({
1933
- errors: {},
1934
- });
1935
- try {
1936
- await onValid(fieldValues, e);
1937
- }
1938
- catch (error) {
1939
- onValidError = error;
1940
- }
1941
- }
1942
- else {
1943
- if (onInvalid) {
1944
- await onInvalid({ ..._formState.errors }, e);
1945
- }
1946
- _focusError();
1947
- setTimeout(_focusError);
1948
- }
1949
- _subjects.state.next({
1950
- isSubmitted: true,
1951
- isSubmitting: false,
1952
- isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
1953
- submitCount: _formState.submitCount + 1,
1954
- errors: _formState.errors,
1955
- });
1956
- if (onValidError) {
1957
- throw onValidError;
1958
- }
1959
- };
1960
- const resetField = (name, options = {}) => {
1961
- if (get(_fields, name)) {
1962
- if (isUndefined(options.defaultValue)) {
1963
- setValue(name, cloneObject(get(_defaultValues, name)));
1964
- }
1965
- else {
1966
- setValue(name, options.defaultValue);
1967
- set(_defaultValues, name, cloneObject(options.defaultValue));
1968
- }
1969
- if (!options.keepTouched) {
1970
- unset(_formState.touchedFields, name);
1971
- }
1972
- if (!options.keepDirty) {
1973
- unset(_formState.dirtyFields, name);
1974
- _formState.isDirty = options.defaultValue
1975
- ? _getDirty(name, cloneObject(get(_defaultValues, name)))
1976
- : _getDirty();
1977
- }
1978
- if (!options.keepError) {
1979
- unset(_formState.errors, name);
1980
- _proxyFormState.isValid && _updateValid();
1981
- }
1982
- _subjects.state.next({ ..._formState });
1983
- }
1984
- };
1985
- const _reset = (formValues, keepStateOptions = {}) => {
1986
- const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
1987
- const cloneUpdatedValues = cloneObject(updatedValues);
1988
- const isEmptyResetValues = isEmptyObject(formValues);
1989
- const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;
1990
- if (!keepStateOptions.keepDefaultValues) {
1991
- _defaultValues = updatedValues;
1992
- }
1993
- if (!keepStateOptions.keepValues) {
1994
- if (keepStateOptions.keepDirtyValues) {
1995
- const fieldsToCheck = new Set([
1996
- ..._names.mount,
1997
- ...Object.keys(getDirtyFields(_defaultValues, _formValues)),
1998
- ]);
1999
- for (const fieldName of Array.from(fieldsToCheck)) {
2000
- get(_formState.dirtyFields, fieldName)
2001
- ? set(values, fieldName, get(_formValues, fieldName))
2002
- : setValue(fieldName, get(values, fieldName));
2003
- }
2004
- }
2005
- else {
2006
- if (isWeb && isUndefined(formValues)) {
2007
- for (const name of _names.mount) {
2008
- const field = get(_fields, name);
2009
- if (field && field._f) {
2010
- const fieldReference = Array.isArray(field._f.refs)
2011
- ? field._f.refs[0]
2012
- : field._f.ref;
2013
- if (isHTMLElement(fieldReference)) {
2014
- const form = fieldReference.closest('form');
2015
- if (form) {
2016
- form.reset();
2017
- break;
2018
- }
2019
- }
2020
- }
2021
- }
2022
- }
2023
- _fields = {};
2024
- }
2025
- _formValues = _options.shouldUnregister
2026
- ? keepStateOptions.keepDefaultValues
2027
- ? cloneObject(_defaultValues)
2028
- : {}
2029
- : cloneObject(values);
2030
- _subjects.array.next({
2031
- values: { ...values },
2032
- });
2033
- _subjects.values.next({
2034
- values: { ...values },
2035
- });
2036
- }
2037
- _names = {
2038
- mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(),
2039
- unMount: new Set(),
2040
- array: new Set(),
2041
- disabled: new Set(),
2042
- watch: new Set(),
2043
- watchAll: false,
2044
- focus: '',
2045
- };
2046
- _state.mount =
2047
- !_proxyFormState.isValid ||
2048
- !!keepStateOptions.keepIsValid ||
2049
- !!keepStateOptions.keepDirtyValues;
2050
- _state.watch = !!_options.shouldUnregister;
2051
- _subjects.state.next({
2052
- submitCount: keepStateOptions.keepSubmitCount
2053
- ? _formState.submitCount
2054
- : 0,
2055
- isDirty: isEmptyResetValues
2056
- ? false
2057
- : keepStateOptions.keepDirty
2058
- ? _formState.isDirty
2059
- : !!(keepStateOptions.keepDefaultValues &&
2060
- !deepEqual(formValues, _defaultValues)),
2061
- isSubmitted: keepStateOptions.keepIsSubmitted
2062
- ? _formState.isSubmitted
2063
- : false,
2064
- dirtyFields: isEmptyResetValues
2065
- ? {}
2066
- : keepStateOptions.keepDirtyValues
2067
- ? keepStateOptions.keepDefaultValues && _formValues
2068
- ? getDirtyFields(_defaultValues, _formValues)
2069
- : _formState.dirtyFields
2070
- : keepStateOptions.keepDefaultValues && formValues
2071
- ? getDirtyFields(_defaultValues, formValues)
2072
- : keepStateOptions.keepDirty
2073
- ? _formState.dirtyFields
2074
- : {},
2075
- touchedFields: keepStateOptions.keepTouched
2076
- ? _formState.touchedFields
2077
- : {},
2078
- errors: keepStateOptions.keepErrors ? _formState.errors : {},
2079
- isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful
2080
- ? _formState.isSubmitSuccessful
2081
- : false,
2082
- isSubmitting: false,
2083
- });
2084
- };
2085
- const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
2086
- ? formValues(_formValues)
2087
- : formValues, keepStateOptions);
2088
- const setFocus = (name, options = {}) => {
2089
- const field = get(_fields, name);
2090
- const fieldReference = field && field._f;
2091
- if (fieldReference) {
2092
- const fieldRef = fieldReference.refs
2093
- ? fieldReference.refs[0]
2094
- : fieldReference.ref;
2095
- if (fieldRef.focus) {
2096
- fieldRef.focus();
2097
- options.shouldSelect &&
2098
- isFunction(fieldRef.select) &&
2099
- fieldRef.select();
2100
- }
2101
- }
2102
- };
2103
- const _updateFormState = (updatedFormState) => {
2104
- _formState = {
2105
- ..._formState,
2106
- ...updatedFormState,
2107
- };
2108
- };
2109
- const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
2110
- _options.defaultValues().then((values) => {
2111
- reset(values, _options.resetOptions);
2112
- _subjects.state.next({
2113
- isLoading: false,
2114
- });
2115
- });
2116
- return {
2117
- control: {
2118
- register,
2119
- unregister,
2120
- getFieldState,
2121
- handleSubmit,
2122
- setError,
2123
- _executeSchema,
2124
- _getWatch,
2125
- _getDirty,
2126
- _updateValid,
2127
- _removeUnmounted,
2128
- _updateFieldArray,
2129
- _updateDisabledField,
2130
- _getFieldArray,
2131
- _reset,
2132
- _resetDefaultValues,
2133
- _updateFormState,
2134
- _disableForm,
2135
- _subjects,
2136
- _proxyFormState,
2137
- _setErrors,
2138
- get _fields() {
2139
- return _fields;
2140
- },
2141
- get _formValues() {
2142
- return _formValues;
2143
- },
2144
- get _state() {
2145
- return _state;
2146
- },
2147
- set _state(value) {
2148
- _state = value;
2149
- },
2150
- get _defaultValues() {
2151
- return _defaultValues;
2152
- },
2153
- get _names() {
2154
- return _names;
2155
- },
2156
- set _names(value) {
2157
- _names = value;
2158
- },
2159
- get _formState() {
2160
- return _formState;
2161
- },
2162
- set _formState(value) {
2163
- _formState = value;
2164
- },
2165
- get _options() {
2166
- return _options;
2167
- },
2168
- set _options(value) {
2169
- _options = {
2170
- ..._options,
2171
- ...value,
2172
- };
2173
- },
2174
- },
2175
- trigger,
2176
- register,
2177
- handleSubmit,
2178
- watch,
2179
- setValue,
2180
- getValues,
2181
- reset,
2182
- resetField,
2183
- clearErrors,
2184
- unregister,
2185
- setError,
2186
- setFocus,
2187
- getFieldState,
2188
- };
2189
- }
2190
-
2191
- /**
2192
- * Custom hook to manage the entire form.
2193
- *
2194
- * @remarks
2195
- * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2196
- *
2197
- * @param props - form configuration and validation parameters.
2198
- *
2199
- * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2200
- *
2201
- * @example
2202
- * ```tsx
2203
- * function App() {
2204
- * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2205
- * const onSubmit = data => console.log(data);
2206
- *
2207
- * console.log(watch("example"));
2208
- *
2209
- * return (
2210
- * <form onSubmit={handleSubmit(onSubmit)}>
2211
- * <input defaultValue="test" {...register("example")} />
2212
- * <input {...register("exampleRequired", { required: true })} />
2213
- * {errors.exampleRequired && <span>This field is required</span>}
2214
- * <button>Submit</button>
2215
- * </form>
2216
- * );
2217
- * }
2218
- * ```
2219
- */
2220
- function useForm(props = {}) {
2221
- const _formControl = React.useRef(undefined);
2222
- const _values = React.useRef(undefined);
2223
- const [formState, updateFormState] = React.useState({
2224
- isDirty: false,
2225
- isValidating: false,
2226
- isLoading: isFunction(props.defaultValues),
2227
- isSubmitted: false,
2228
- isSubmitting: false,
2229
- isSubmitSuccessful: false,
2230
- isValid: false,
2231
- submitCount: 0,
2232
- dirtyFields: {},
2233
- touchedFields: {},
2234
- validatingFields: {},
2235
- errors: props.errors || {},
2236
- disabled: props.disabled || false,
2237
- defaultValues: isFunction(props.defaultValues)
2238
- ? undefined
2239
- : props.defaultValues,
2240
- });
2241
- if (!_formControl.current) {
2242
- _formControl.current = {
2243
- ...createFormControl(props),
2244
- formState,
2245
- };
2246
- }
2247
- const control = _formControl.current.control;
2248
- control._options = props;
2249
- useSubscribe({
2250
- subject: control._subjects.state,
2251
- next: (value) => {
2252
- if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
2253
- updateFormState({ ...control._formState });
2254
- }
2255
- },
2256
- });
2257
- React.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
2258
- React.useEffect(() => {
2259
- if (control._proxyFormState.isDirty) {
2260
- const isDirty = control._getDirty();
2261
- if (isDirty !== formState.isDirty) {
2262
- control._subjects.state.next({
2263
- isDirty,
2264
- });
2265
- }
2266
- }
2267
- }, [control, formState.isDirty]);
2268
- React.useEffect(() => {
2269
- if (props.values && !deepEqual(props.values, _values.current)) {
2270
- control._reset(props.values, control._options.resetOptions);
2271
- _values.current = props.values;
2272
- updateFormState((state) => ({ ...state }));
2273
- }
2274
- else {
2275
- control._resetDefaultValues();
2276
- }
2277
- }, [props.values, control]);
2278
- React.useEffect(() => {
2279
- if (props.errors) {
2280
- control._setErrors(props.errors);
2281
- }
2282
- }, [props.errors, control]);
2283
- React.useEffect(() => {
2284
- if (!control._state.mount) {
2285
- control._updateValid();
2286
- control._state.mount = true;
2287
- }
2288
- if (control._state.watch) {
2289
- control._state.watch = false;
2290
- control._subjects.state.next({ ...control._formState });
2291
- }
2292
- control._removeUnmounted();
2293
- });
2294
- React.useEffect(() => {
2295
- props.shouldUnregister &&
2296
- control._subjects.values.next({
2297
- values: control._getWatch(),
2298
- });
2299
- }, [props.shouldUnregister, control]);
2300
- _formControl.current.formState = getProxyFormState(formState, control);
2301
- return _formControl.current;
2302
- }
2303
-
2304
- var util;
5
+ exports.util = void 0;
2305
6
  (function (util) {
2306
7
  util.assertEqual = (val) => val;
2307
8
  function assertIs(_arg) { }
@@ -2363,8 +64,8 @@ var util;
2363
64
  }
2364
65
  return value;
2365
66
  };
2366
- })(util || (util = {}));
2367
- var objectUtil;
67
+ })(exports.util || (exports.util = {}));
68
+ exports.objectUtil = void 0;
2368
69
  (function (objectUtil) {
2369
70
  objectUtil.mergeShapes = (first, second) => {
2370
71
  return {
@@ -2372,8 +73,8 @@ var objectUtil;
2372
73
  ...second, // second overwrites first
2373
74
  };
2374
75
  };
2375
- })(objectUtil || (objectUtil = {}));
2376
- const ZodParsedType = util.arrayToEnum([
76
+ })(exports.objectUtil || (exports.objectUtil = {}));
77
+ const ZodParsedType = exports.util.arrayToEnum([
2377
78
  "string",
2378
79
  "nan",
2379
80
  "number",
@@ -2440,7 +141,7 @@ const getParsedType = (data) => {
2440
141
  }
2441
142
  };
2442
143
 
2443
- const ZodIssueCode = util.arrayToEnum([
144
+ const ZodIssueCode = exports.util.arrayToEnum([
2444
145
  "invalid_type",
2445
146
  "invalid_literal",
2446
147
  "custom",
@@ -2544,7 +245,7 @@ class ZodError extends Error {
2544
245
  return this.message;
2545
246
  }
2546
247
  get message() {
2547
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
248
+ return JSON.stringify(this.issues, exports.util.jsonStringifyReplacer, 2);
2548
249
  }
2549
250
  get isEmpty() {
2550
251
  return this.issues.length === 0;
@@ -2584,19 +285,19 @@ const errorMap = (issue, _ctx) => {
2584
285
  }
2585
286
  break;
2586
287
  case ZodIssueCode.invalid_literal:
2587
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
288
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, exports.util.jsonStringifyReplacer)}`;
2588
289
  break;
2589
290
  case ZodIssueCode.unrecognized_keys:
2590
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
291
+ message = `Unrecognized key(s) in object: ${exports.util.joinValues(issue.keys, ", ")}`;
2591
292
  break;
2592
293
  case ZodIssueCode.invalid_union:
2593
294
  message = `Invalid input`;
2594
295
  break;
2595
296
  case ZodIssueCode.invalid_union_discriminator:
2596
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
297
+ message = `Invalid discriminator value. Expected ${exports.util.joinValues(issue.options)}`;
2597
298
  break;
2598
299
  case ZodIssueCode.invalid_enum_value:
2599
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
300
+ message = `Invalid enum value. Expected ${exports.util.joinValues(issue.options)}, received '${issue.received}'`;
2600
301
  break;
2601
302
  case ZodIssueCode.invalid_arguments:
2602
303
  message = `Invalid function arguments`;
@@ -2622,7 +323,7 @@ const errorMap = (issue, _ctx) => {
2622
323
  message = `Invalid input: must end with "${issue.validation.endsWith}"`;
2623
324
  }
2624
325
  else {
2625
- util.assertNever(issue.validation);
326
+ exports.util.assertNever(issue.validation);
2626
327
  }
2627
328
  }
2628
329
  else if (issue.validation !== "regex") {
@@ -2692,7 +393,7 @@ const errorMap = (issue, _ctx) => {
2692
393
  break;
2693
394
  default:
2694
395
  message = _ctx.defaultError;
2695
- util.assertNever(issue);
396
+ exports.util.assertNever(issue);
2696
397
  }
2697
398
  return { message };
2698
399
  };
@@ -3100,7 +801,7 @@ class ZodType {
3100
801
  _refinement(refinement) {
3101
802
  return new ZodEffects({
3102
803
  schema: this,
3103
- typeName: ZodFirstPartyTypeKind.ZodEffects,
804
+ typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
3104
805
  effect: { type: "refinement", refinement },
3105
806
  });
3106
807
  }
@@ -3166,7 +867,7 @@ class ZodType {
3166
867
  return new ZodEffects({
3167
868
  ...processCreateParams(this._def),
3168
869
  schema: this,
3169
- typeName: ZodFirstPartyTypeKind.ZodEffects,
870
+ typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
3170
871
  effect: { type: "transform", transform },
3171
872
  });
3172
873
  }
@@ -3176,12 +877,12 @@ class ZodType {
3176
877
  ...processCreateParams(this._def),
3177
878
  innerType: this,
3178
879
  defaultValue: defaultValueFunc,
3179
- typeName: ZodFirstPartyTypeKind.ZodDefault,
880
+ typeName: exports.ZodFirstPartyTypeKind.ZodDefault,
3180
881
  });
3181
882
  }
3182
883
  brand() {
3183
884
  return new ZodBranded({
3184
- typeName: ZodFirstPartyTypeKind.ZodBranded,
885
+ typeName: exports.ZodFirstPartyTypeKind.ZodBranded,
3185
886
  type: this,
3186
887
  ...processCreateParams(this._def),
3187
888
  });
@@ -3192,7 +893,7 @@ class ZodType {
3192
893
  ...processCreateParams(this._def),
3193
894
  innerType: this,
3194
895
  catchValue: catchValueFunc,
3195
- typeName: ZodFirstPartyTypeKind.ZodCatch,
896
+ typeName: exports.ZodFirstPartyTypeKind.ZodCatch,
3196
897
  });
3197
898
  }
3198
899
  describe(description) {
@@ -3651,7 +1352,7 @@ class ZodString extends ZodType {
3651
1352
  }
3652
1353
  }
3653
1354
  else {
3654
- util.assertNever(check);
1355
+ exports.util.assertNever(check);
3655
1356
  }
3656
1357
  }
3657
1358
  return { status: status.value, value: input.data };
@@ -3899,7 +1600,7 @@ ZodString.create = (params) => {
3899
1600
  var _a;
3900
1601
  return new ZodString({
3901
1602
  checks: [],
3902
- typeName: ZodFirstPartyTypeKind.ZodString,
1603
+ typeName: exports.ZodFirstPartyTypeKind.ZodString,
3903
1604
  coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
3904
1605
  ...processCreateParams(params),
3905
1606
  });
@@ -3938,7 +1639,7 @@ class ZodNumber extends ZodType {
3938
1639
  const status = new ParseStatus();
3939
1640
  for (const check of this._def.checks) {
3940
1641
  if (check.kind === "int") {
3941
- if (!util.isInteger(input.data)) {
1642
+ if (!exports.util.isInteger(input.data)) {
3942
1643
  ctx = this._getOrReturnCtx(input, ctx);
3943
1644
  addIssueToContext(ctx, {
3944
1645
  code: ZodIssueCode.invalid_type,
@@ -4005,7 +1706,7 @@ class ZodNumber extends ZodType {
4005
1706
  }
4006
1707
  }
4007
1708
  else {
4008
- util.assertNever(check);
1709
+ exports.util.assertNever(check);
4009
1710
  }
4010
1711
  }
4011
1712
  return { status: status.value, value: input.data };
@@ -4128,7 +1829,7 @@ class ZodNumber extends ZodType {
4128
1829
  }
4129
1830
  get isInt() {
4130
1831
  return !!this._def.checks.find((ch) => ch.kind === "int" ||
4131
- (ch.kind === "multipleOf" && util.isInteger(ch.value)));
1832
+ (ch.kind === "multipleOf" && exports.util.isInteger(ch.value)));
4132
1833
  }
4133
1834
  get isFinite() {
4134
1835
  let max = null, min = null;
@@ -4153,7 +1854,7 @@ class ZodNumber extends ZodType {
4153
1854
  ZodNumber.create = (params) => {
4154
1855
  return new ZodNumber({
4155
1856
  checks: [],
4156
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1857
+ typeName: exports.ZodFirstPartyTypeKind.ZodNumber,
4157
1858
  coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
4158
1859
  ...processCreateParams(params),
4159
1860
  });
@@ -4224,7 +1925,7 @@ class ZodBigInt extends ZodType {
4224
1925
  }
4225
1926
  }
4226
1927
  else {
4227
- util.assertNever(check);
1928
+ exports.util.assertNever(check);
4228
1929
  }
4229
1930
  }
4230
1931
  return { status: status.value, value: input.data };
@@ -4334,7 +2035,7 @@ ZodBigInt.create = (params) => {
4334
2035
  var _a;
4335
2036
  return new ZodBigInt({
4336
2037
  checks: [],
4337
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
2038
+ typeName: exports.ZodFirstPartyTypeKind.ZodBigInt,
4338
2039
  coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
4339
2040
  ...processCreateParams(params),
4340
2041
  });
@@ -4359,7 +2060,7 @@ class ZodBoolean extends ZodType {
4359
2060
  }
4360
2061
  ZodBoolean.create = (params) => {
4361
2062
  return new ZodBoolean({
4362
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2063
+ typeName: exports.ZodFirstPartyTypeKind.ZodBoolean,
4363
2064
  coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
4364
2065
  ...processCreateParams(params),
4365
2066
  });
@@ -4418,7 +2119,7 @@ class ZodDate extends ZodType {
4418
2119
  }
4419
2120
  }
4420
2121
  else {
4421
- util.assertNever(check);
2122
+ exports.util.assertNever(check);
4422
2123
  }
4423
2124
  }
4424
2125
  return {
@@ -4471,7 +2172,7 @@ ZodDate.create = (params) => {
4471
2172
  return new ZodDate({
4472
2173
  checks: [],
4473
2174
  coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
4474
- typeName: ZodFirstPartyTypeKind.ZodDate,
2175
+ typeName: exports.ZodFirstPartyTypeKind.ZodDate,
4475
2176
  ...processCreateParams(params),
4476
2177
  });
4477
2178
  };
@@ -4492,7 +2193,7 @@ class ZodSymbol extends ZodType {
4492
2193
  }
4493
2194
  ZodSymbol.create = (params) => {
4494
2195
  return new ZodSymbol({
4495
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2196
+ typeName: exports.ZodFirstPartyTypeKind.ZodSymbol,
4496
2197
  ...processCreateParams(params),
4497
2198
  });
4498
2199
  };
@@ -4513,7 +2214,7 @@ class ZodUndefined extends ZodType {
4513
2214
  }
4514
2215
  ZodUndefined.create = (params) => {
4515
2216
  return new ZodUndefined({
4516
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2217
+ typeName: exports.ZodFirstPartyTypeKind.ZodUndefined,
4517
2218
  ...processCreateParams(params),
4518
2219
  });
4519
2220
  };
@@ -4534,7 +2235,7 @@ class ZodNull extends ZodType {
4534
2235
  }
4535
2236
  ZodNull.create = (params) => {
4536
2237
  return new ZodNull({
4537
- typeName: ZodFirstPartyTypeKind.ZodNull,
2238
+ typeName: exports.ZodFirstPartyTypeKind.ZodNull,
4538
2239
  ...processCreateParams(params),
4539
2240
  });
4540
2241
  };
@@ -4550,7 +2251,7 @@ class ZodAny extends ZodType {
4550
2251
  }
4551
2252
  ZodAny.create = (params) => {
4552
2253
  return new ZodAny({
4553
- typeName: ZodFirstPartyTypeKind.ZodAny,
2254
+ typeName: exports.ZodFirstPartyTypeKind.ZodAny,
4554
2255
  ...processCreateParams(params),
4555
2256
  });
4556
2257
  };
@@ -4566,7 +2267,7 @@ class ZodUnknown extends ZodType {
4566
2267
  }
4567
2268
  ZodUnknown.create = (params) => {
4568
2269
  return new ZodUnknown({
4569
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2270
+ typeName: exports.ZodFirstPartyTypeKind.ZodUnknown,
4570
2271
  ...processCreateParams(params),
4571
2272
  });
4572
2273
  };
@@ -4583,7 +2284,7 @@ class ZodNever extends ZodType {
4583
2284
  }
4584
2285
  ZodNever.create = (params) => {
4585
2286
  return new ZodNever({
4586
- typeName: ZodFirstPartyTypeKind.ZodNever,
2287
+ typeName: exports.ZodFirstPartyTypeKind.ZodNever,
4587
2288
  ...processCreateParams(params),
4588
2289
  });
4589
2290
  };
@@ -4604,7 +2305,7 @@ class ZodVoid extends ZodType {
4604
2305
  }
4605
2306
  ZodVoid.create = (params) => {
4606
2307
  return new ZodVoid({
4607
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2308
+ typeName: exports.ZodFirstPartyTypeKind.ZodVoid,
4608
2309
  ...processCreateParams(params),
4609
2310
  });
4610
2311
  };
@@ -4705,7 +2406,7 @@ ZodArray.create = (schema, params) => {
4705
2406
  minLength: null,
4706
2407
  maxLength: null,
4707
2408
  exactLength: null,
4708
- typeName: ZodFirstPartyTypeKind.ZodArray,
2409
+ typeName: exports.ZodFirstPartyTypeKind.ZodArray,
4709
2410
  ...processCreateParams(params),
4710
2411
  });
4711
2412
  };
@@ -4791,7 +2492,7 @@ class ZodObject extends ZodType {
4791
2492
  if (this._cached !== null)
4792
2493
  return this._cached;
4793
2494
  const shape = this._def.shape();
4794
- const keys = util.objectKeys(shape);
2495
+ const keys = exports.util.objectKeys(shape);
4795
2496
  return (this._cached = { shape, keys });
4796
2497
  }
4797
2498
  _parse(input) {
@@ -4962,7 +2663,7 @@ class ZodObject extends ZodType {
4962
2663
  ...this._def.shape(),
4963
2664
  ...merging._def.shape(),
4964
2665
  }),
4965
- typeName: ZodFirstPartyTypeKind.ZodObject,
2666
+ typeName: exports.ZodFirstPartyTypeKind.ZodObject,
4966
2667
  });
4967
2668
  return merged;
4968
2669
  }
@@ -5033,7 +2734,7 @@ class ZodObject extends ZodType {
5033
2734
  }
5034
2735
  pick(mask) {
5035
2736
  const shape = {};
5036
- util.objectKeys(mask).forEach((key) => {
2737
+ exports.util.objectKeys(mask).forEach((key) => {
5037
2738
  if (mask[key] && this.shape[key]) {
5038
2739
  shape[key] = this.shape[key];
5039
2740
  }
@@ -5045,7 +2746,7 @@ class ZodObject extends ZodType {
5045
2746
  }
5046
2747
  omit(mask) {
5047
2748
  const shape = {};
5048
- util.objectKeys(this.shape).forEach((key) => {
2749
+ exports.util.objectKeys(this.shape).forEach((key) => {
5049
2750
  if (!mask[key]) {
5050
2751
  shape[key] = this.shape[key];
5051
2752
  }
@@ -5063,7 +2764,7 @@ class ZodObject extends ZodType {
5063
2764
  }
5064
2765
  partial(mask) {
5065
2766
  const newShape = {};
5066
- util.objectKeys(this.shape).forEach((key) => {
2767
+ exports.util.objectKeys(this.shape).forEach((key) => {
5067
2768
  const fieldSchema = this.shape[key];
5068
2769
  if (mask && !mask[key]) {
5069
2770
  newShape[key] = fieldSchema;
@@ -5079,7 +2780,7 @@ class ZodObject extends ZodType {
5079
2780
  }
5080
2781
  required(mask) {
5081
2782
  const newShape = {};
5082
- util.objectKeys(this.shape).forEach((key) => {
2783
+ exports.util.objectKeys(this.shape).forEach((key) => {
5083
2784
  if (mask && !mask[key]) {
5084
2785
  newShape[key] = this.shape[key];
5085
2786
  }
@@ -5098,7 +2799,7 @@ class ZodObject extends ZodType {
5098
2799
  });
5099
2800
  }
5100
2801
  keyof() {
5101
- return createZodEnum(util.objectKeys(this.shape));
2802
+ return createZodEnum(exports.util.objectKeys(this.shape));
5102
2803
  }
5103
2804
  }
5104
2805
  ZodObject.create = (shape, params) => {
@@ -5106,7 +2807,7 @@ ZodObject.create = (shape, params) => {
5106
2807
  shape: () => shape,
5107
2808
  unknownKeys: "strip",
5108
2809
  catchall: ZodNever.create(),
5109
- typeName: ZodFirstPartyTypeKind.ZodObject,
2810
+ typeName: exports.ZodFirstPartyTypeKind.ZodObject,
5110
2811
  ...processCreateParams(params),
5111
2812
  });
5112
2813
  };
@@ -5115,7 +2816,7 @@ ZodObject.strictCreate = (shape, params) => {
5115
2816
  shape: () => shape,
5116
2817
  unknownKeys: "strict",
5117
2818
  catchall: ZodNever.create(),
5118
- typeName: ZodFirstPartyTypeKind.ZodObject,
2819
+ typeName: exports.ZodFirstPartyTypeKind.ZodObject,
5119
2820
  ...processCreateParams(params),
5120
2821
  });
5121
2822
  };
@@ -5124,7 +2825,7 @@ ZodObject.lazycreate = (shape, params) => {
5124
2825
  shape,
5125
2826
  unknownKeys: "strip",
5126
2827
  catchall: ZodNever.create(),
5127
- typeName: ZodFirstPartyTypeKind.ZodObject,
2828
+ typeName: exports.ZodFirstPartyTypeKind.ZodObject,
5128
2829
  ...processCreateParams(params),
5129
2830
  });
5130
2831
  };
@@ -5220,7 +2921,7 @@ class ZodUnion extends ZodType {
5220
2921
  ZodUnion.create = (types, params) => {
5221
2922
  return new ZodUnion({
5222
2923
  options: types,
5223
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2924
+ typeName: exports.ZodFirstPartyTypeKind.ZodUnion,
5224
2925
  ...processCreateParams(params),
5225
2926
  });
5226
2927
  };
@@ -5246,7 +2947,7 @@ const getDiscriminator = (type) => {
5246
2947
  }
5247
2948
  else if (type instanceof ZodNativeEnum) {
5248
2949
  // eslint-disable-next-line ban/ban
5249
- return util.objectValues(type.enum);
2950
+ return exports.util.objectValues(type.enum);
5250
2951
  }
5251
2952
  else if (type instanceof ZodDefault) {
5252
2953
  return getDiscriminator(type._def.innerType);
@@ -5347,7 +3048,7 @@ class ZodDiscriminatedUnion extends ZodType {
5347
3048
  }
5348
3049
  }
5349
3050
  return new ZodDiscriminatedUnion({
5350
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3051
+ typeName: exports.ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
5351
3052
  discriminator,
5352
3053
  options,
5353
3054
  optionsMap,
@@ -5362,8 +3063,8 @@ function mergeValues(a, b) {
5362
3063
  return { valid: true, data: a };
5363
3064
  }
5364
3065
  else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
5365
- const bKeys = util.objectKeys(b);
5366
- const sharedKeys = util
3066
+ const bKeys = exports.util.objectKeys(b);
3067
+ const sharedKeys = exports.util
5367
3068
  .objectKeys(a)
5368
3069
  .filter((key) => bKeys.indexOf(key) !== -1);
5369
3070
  const newObj = { ...a, ...b };
@@ -5451,7 +3152,7 @@ ZodIntersection.create = (left, right, params) => {
5451
3152
  return new ZodIntersection({
5452
3153
  left: left,
5453
3154
  right: right,
5454
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
3155
+ typeName: exports.ZodFirstPartyTypeKind.ZodIntersection,
5455
3156
  ...processCreateParams(params),
5456
3157
  });
5457
3158
  };
@@ -5520,7 +3221,7 @@ ZodTuple.create = (schemas, params) => {
5520
3221
  }
5521
3222
  return new ZodTuple({
5522
3223
  items: schemas,
5523
- typeName: ZodFirstPartyTypeKind.ZodTuple,
3224
+ typeName: exports.ZodFirstPartyTypeKind.ZodTuple,
5524
3225
  rest: null,
5525
3226
  ...processCreateParams(params),
5526
3227
  });
@@ -5567,14 +3268,14 @@ class ZodRecord extends ZodType {
5567
3268
  return new ZodRecord({
5568
3269
  keyType: first,
5569
3270
  valueType: second,
5570
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3271
+ typeName: exports.ZodFirstPartyTypeKind.ZodRecord,
5571
3272
  ...processCreateParams(third),
5572
3273
  });
5573
3274
  }
5574
3275
  return new ZodRecord({
5575
3276
  keyType: ZodString.create(),
5576
3277
  valueType: first,
5577
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3278
+ typeName: exports.ZodFirstPartyTypeKind.ZodRecord,
5578
3279
  ...processCreateParams(second),
5579
3280
  });
5580
3281
  }
@@ -5642,7 +3343,7 @@ ZodMap.create = (keyType, valueType, params) => {
5642
3343
  return new ZodMap({
5643
3344
  valueType,
5644
3345
  keyType,
5645
- typeName: ZodFirstPartyTypeKind.ZodMap,
3346
+ typeName: exports.ZodFirstPartyTypeKind.ZodMap,
5646
3347
  ...processCreateParams(params),
5647
3348
  });
5648
3349
  };
@@ -5728,7 +3429,7 @@ ZodSet.create = (valueType, params) => {
5728
3429
  valueType,
5729
3430
  minSize: null,
5730
3431
  maxSize: null,
5731
- typeName: ZodFirstPartyTypeKind.ZodSet,
3432
+ typeName: exports.ZodFirstPartyTypeKind.ZodSet,
5732
3433
  ...processCreateParams(params),
5733
3434
  });
5734
3435
  };
@@ -5855,7 +3556,7 @@ class ZodFunction extends ZodType {
5855
3556
  ? args
5856
3557
  : ZodTuple.create([]).rest(ZodUnknown.create())),
5857
3558
  returns: returns || ZodUnknown.create(),
5858
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3559
+ typeName: exports.ZodFirstPartyTypeKind.ZodFunction,
5859
3560
  ...processCreateParams(params),
5860
3561
  });
5861
3562
  }
@@ -5873,7 +3574,7 @@ class ZodLazy extends ZodType {
5873
3574
  ZodLazy.create = (getter, params) => {
5874
3575
  return new ZodLazy({
5875
3576
  getter: getter,
5876
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3577
+ typeName: exports.ZodFirstPartyTypeKind.ZodLazy,
5877
3578
  ...processCreateParams(params),
5878
3579
  });
5879
3580
  };
@@ -5897,14 +3598,14 @@ class ZodLiteral extends ZodType {
5897
3598
  ZodLiteral.create = (value, params) => {
5898
3599
  return new ZodLiteral({
5899
3600
  value: value,
5900
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3601
+ typeName: exports.ZodFirstPartyTypeKind.ZodLiteral,
5901
3602
  ...processCreateParams(params),
5902
3603
  });
5903
3604
  };
5904
3605
  function createZodEnum(values, params) {
5905
3606
  return new ZodEnum({
5906
3607
  values,
5907
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3608
+ typeName: exports.ZodFirstPartyTypeKind.ZodEnum,
5908
3609
  ...processCreateParams(params),
5909
3610
  });
5910
3611
  }
@@ -5918,7 +3619,7 @@ class ZodEnum extends ZodType {
5918
3619
  const ctx = this._getOrReturnCtx(input);
5919
3620
  const expectedValues = this._def.values;
5920
3621
  addIssueToContext(ctx, {
5921
- expected: util.joinValues(expectedValues),
3622
+ expected: exports.util.joinValues(expectedValues),
5922
3623
  received: ctx.parsedType,
5923
3624
  code: ZodIssueCode.invalid_type,
5924
3625
  });
@@ -5984,23 +3685,23 @@ class ZodNativeEnum extends ZodType {
5984
3685
  _ZodNativeEnum_cache.set(this, void 0);
5985
3686
  }
5986
3687
  _parse(input) {
5987
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3688
+ const nativeEnumValues = exports.util.getValidEnumValues(this._def.values);
5988
3689
  const ctx = this._getOrReturnCtx(input);
5989
3690
  if (ctx.parsedType !== ZodParsedType.string &&
5990
3691
  ctx.parsedType !== ZodParsedType.number) {
5991
- const expectedValues = util.objectValues(nativeEnumValues);
3692
+ const expectedValues = exports.util.objectValues(nativeEnumValues);
5992
3693
  addIssueToContext(ctx, {
5993
- expected: util.joinValues(expectedValues),
3694
+ expected: exports.util.joinValues(expectedValues),
5994
3695
  received: ctx.parsedType,
5995
3696
  code: ZodIssueCode.invalid_type,
5996
3697
  });
5997
3698
  return INVALID;
5998
3699
  }
5999
3700
  if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache)) {
6000
- __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)));
3701
+ __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(exports.util.getValidEnumValues(this._def.values)));
6001
3702
  }
6002
3703
  if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache).has(input.data)) {
6003
- const expectedValues = util.objectValues(nativeEnumValues);
3704
+ const expectedValues = exports.util.objectValues(nativeEnumValues);
6004
3705
  addIssueToContext(ctx, {
6005
3706
  received: ctx.data,
6006
3707
  code: ZodIssueCode.invalid_enum_value,
@@ -6018,7 +3719,7 @@ _ZodNativeEnum_cache = new WeakMap();
6018
3719
  ZodNativeEnum.create = (values, params) => {
6019
3720
  return new ZodNativeEnum({
6020
3721
  values: values,
6021
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3722
+ typeName: exports.ZodFirstPartyTypeKind.ZodNativeEnum,
6022
3723
  ...processCreateParams(params),
6023
3724
  });
6024
3725
  };
@@ -6051,7 +3752,7 @@ class ZodPromise extends ZodType {
6051
3752
  ZodPromise.create = (schema, params) => {
6052
3753
  return new ZodPromise({
6053
3754
  type: schema,
6054
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3755
+ typeName: exports.ZodFirstPartyTypeKind.ZodPromise,
6055
3756
  ...processCreateParams(params),
6056
3757
  });
6057
3758
  };
@@ -6060,7 +3761,7 @@ class ZodEffects extends ZodType {
6060
3761
  return this._def.schema;
6061
3762
  }
6062
3763
  sourceType() {
6063
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
3764
+ return this._def.schema._def.typeName === exports.ZodFirstPartyTypeKind.ZodEffects
6064
3765
  ? this._def.schema.sourceType()
6065
3766
  : this._def.schema;
6066
3767
  }
@@ -6183,13 +3884,13 @@ class ZodEffects extends ZodType {
6183
3884
  });
6184
3885
  }
6185
3886
  }
6186
- util.assertNever(effect);
3887
+ exports.util.assertNever(effect);
6187
3888
  }
6188
3889
  }
6189
3890
  ZodEffects.create = (schema, effect, params) => {
6190
3891
  return new ZodEffects({
6191
3892
  schema,
6192
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3893
+ typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
6193
3894
  effect,
6194
3895
  ...processCreateParams(params),
6195
3896
  });
@@ -6198,7 +3899,7 @@ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
6198
3899
  return new ZodEffects({
6199
3900
  schema,
6200
3901
  effect: { type: "preprocess", transform: preprocess },
6201
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3902
+ typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
6202
3903
  ...processCreateParams(params),
6203
3904
  });
6204
3905
  };
@@ -6217,7 +3918,7 @@ class ZodOptional extends ZodType {
6217
3918
  ZodOptional.create = (type, params) => {
6218
3919
  return new ZodOptional({
6219
3920
  innerType: type,
6220
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3921
+ typeName: exports.ZodFirstPartyTypeKind.ZodOptional,
6221
3922
  ...processCreateParams(params),
6222
3923
  });
6223
3924
  };
@@ -6236,7 +3937,7 @@ class ZodNullable extends ZodType {
6236
3937
  ZodNullable.create = (type, params) => {
6237
3938
  return new ZodNullable({
6238
3939
  innerType: type,
6239
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3940
+ typeName: exports.ZodFirstPartyTypeKind.ZodNullable,
6240
3941
  ...processCreateParams(params),
6241
3942
  });
6242
3943
  };
@@ -6260,7 +3961,7 @@ class ZodDefault extends ZodType {
6260
3961
  ZodDefault.create = (type, params) => {
6261
3962
  return new ZodDefault({
6262
3963
  innerType: type,
6263
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3964
+ typeName: exports.ZodFirstPartyTypeKind.ZodDefault,
6264
3965
  defaultValue: typeof params.default === "function"
6265
3966
  ? params.default
6266
3967
  : () => params.default,
@@ -6321,7 +4022,7 @@ class ZodCatch extends ZodType {
6321
4022
  ZodCatch.create = (type, params) => {
6322
4023
  return new ZodCatch({
6323
4024
  innerType: type,
6324
- typeName: ZodFirstPartyTypeKind.ZodCatch,
4025
+ typeName: exports.ZodFirstPartyTypeKind.ZodCatch,
6325
4026
  catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
6326
4027
  ...processCreateParams(params),
6327
4028
  });
@@ -6343,7 +4044,7 @@ class ZodNaN extends ZodType {
6343
4044
  }
6344
4045
  ZodNaN.create = (params) => {
6345
4046
  return new ZodNaN({
6346
- typeName: ZodFirstPartyTypeKind.ZodNaN,
4047
+ typeName: exports.ZodFirstPartyTypeKind.ZodNaN,
6347
4048
  ...processCreateParams(params),
6348
4049
  });
6349
4050
  };
@@ -6416,7 +4117,7 @@ class ZodPipeline extends ZodType {
6416
4117
  return new ZodPipeline({
6417
4118
  in: a,
6418
4119
  out: b,
6419
- typeName: ZodFirstPartyTypeKind.ZodPipeline,
4120
+ typeName: exports.ZodFirstPartyTypeKind.ZodPipeline,
6420
4121
  });
6421
4122
  }
6422
4123
  }
@@ -6440,7 +4141,7 @@ class ZodReadonly extends ZodType {
6440
4141
  ZodReadonly.create = (type, params) => {
6441
4142
  return new ZodReadonly({
6442
4143
  innerType: type,
6443
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
4144
+ typeName: exports.ZodFirstPartyTypeKind.ZodReadonly,
6444
4145
  ...processCreateParams(params),
6445
4146
  });
6446
4147
  };
@@ -6498,7 +4199,7 @@ fatal) {
6498
4199
  const late = {
6499
4200
  object: ZodObject.lazycreate,
6500
4201
  };
6501
- var ZodFirstPartyTypeKind;
4202
+ exports.ZodFirstPartyTypeKind = void 0;
6502
4203
  (function (ZodFirstPartyTypeKind) {
6503
4204
  ZodFirstPartyTypeKind["ZodString"] = "ZodString";
6504
4205
  ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
@@ -6536,7 +4237,7 @@ var ZodFirstPartyTypeKind;
6536
4237
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
6537
4238
  ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
6538
4239
  ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
6539
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4240
+ })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
6540
4241
  const instanceOfType = (
6541
4242
  // const instanceOfType = <T extends new (...args: any[]) => any>(
6542
4243
  cls, params = {
@@ -6607,8 +4308,8 @@ var z = /*#__PURE__*/Object.freeze({
6607
4308
  isDirty: isDirty,
6608
4309
  isValid: isValid,
6609
4310
  isAsync: isAsync,
6610
- get util () { return util; },
6611
- get objectUtil () { return objectUtil; },
4311
+ get util () { return exports.util; },
4312
+ get objectUtil () { return exports.objectUtil; },
6612
4313
  ZodParsedType: ZodParsedType,
6613
4314
  getParsedType: getParsedType,
6614
4315
  ZodType: ZodType,
@@ -6655,7 +4356,7 @@ var z = /*#__PURE__*/Object.freeze({
6655
4356
  Schema: ZodType,
6656
4357
  ZodSchema: ZodType,
6657
4358
  late: late,
6658
- get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
4359
+ get ZodFirstPartyTypeKind () { return exports.ZodFirstPartyTypeKind; },
6659
4360
  coerce: coerce,
6660
4361
  any: anyType,
6661
4362
  array: arrayType,
@@ -6702,1107 +4403,109 @@ var z = /*#__PURE__*/Object.freeze({
6702
4403
  ZodError: ZodError
6703
4404
  });
6704
4405
 
6705
- function g(e) {
6706
- let n = 0, t = false, s = e.length - 1, l;
6707
- for (; s >= 0; )
6708
- l = parseInt(e.charAt(s), 10), t && (l *= 2, l > 9 && (l = l % 10 + 1)), t = !t, n += l, s--;
6709
- return n % 10 === 0;
6710
- }
6711
- const h = [
6712
- {
6713
- name: "visa",
6714
- isLocal: false,
6715
- numberValidationRules: {
6716
- luhnCheck: true,
6717
- ranges: [4],
6718
- lengths: [16, 18, 19]
6719
- },
6720
- securityCodeValidationRules: {
6721
- lengths: [3]
6722
- }
6723
- },
6724
- {
6725
- name: "mastercard",
6726
- isLocal: false,
6727
- numberValidationRules: {
6728
- luhnCheck: true,
6729
- ranges: [[51, 55], [2221, 2229], [223, 229], [23, 26], [270, 271], 2720],
6730
- lengths: [16]
6731
- },
6732
- securityCodeValidationRules: {
6733
- lengths: [3]
6734
- }
6735
- },
6736
- {
6737
- name: "american-express",
6738
- isLocal: false,
6739
- numberValidationRules: {
6740
- luhnCheck: true,
6741
- ranges: [34, 37],
6742
- lengths: [15]
6743
- },
6744
- securityCodeValidationRules: {
6745
- lengths: [3, 4]
6746
- }
6747
- },
6748
- {
6749
- name: "diners-club",
6750
- isLocal: false,
6751
- numberValidationRules: {
6752
- luhnCheck: true,
6753
- ranges: [[300, 305], 3095, 36, 38, 39],
6754
- lengths: [14, 16, 19]
6755
- },
6756
- securityCodeValidationRules: {
6757
- lengths: [3]
6758
- }
6759
- },
6760
- {
6761
- name: "discover",
6762
- isLocal: false,
6763
- numberValidationRules: {
6764
- luhnCheck: true,
6765
- ranges: [6011, [644, 649], [65e4, 651999], [653150, 659999], 622],
6766
- lengths: [16, 19]
6767
- },
6768
- securityCodeValidationRules: {
6769
- lengths: [3]
6770
- }
6771
- },
6772
- {
6773
- name: "jcb",
6774
- isLocal: false,
6775
- numberValidationRules: {
6776
- luhnCheck: true,
6777
- ranges: [
6778
- 2131,
6779
- 1800,
6780
- [3088, 3094],
6781
- [3096, 3102],
6782
- [3112, 3120],
6783
- [3158, 3159],
6784
- [3337, 3349],
6785
- [3528, 3589]
6786
- ],
6787
- lengths: [16, 17, 18, 19]
6788
- },
6789
- securityCodeValidationRules: {
6790
- lengths: [3]
6791
- }
6792
- },
6793
- {
6794
- name: "unionpay",
6795
- isLocal: false,
6796
- numberValidationRules: {
6797
- luhnCheck: false,
6798
- ranges: [
6799
- 620,
6800
- [62100, 62182],
6801
- [62184, 62187],
6802
- [62185, 62197],
6803
- [62200, 62205],
6804
- [622010, 622999],
6805
- 622018,
6806
- [62207, 62209],
6807
- [623, 626],
6808
- 6270,
6809
- 6272,
6810
- 6276,
6811
- [627700, 627779],
6812
- [627781, 627799],
6813
- [6282, 6289],
6814
- 6291,
6815
- 6292,
6816
- 810,
6817
- [8110, 8131],
6818
- [8132, 8151],
6819
- [8152, 8163],
6820
- [8164, 8171]
6821
- ],
6822
- lengths: [14, 15, 16, 17, 18, 19]
6823
- },
6824
- securityCodeValidationRules: {
6825
- lengths: [3]
6826
- }
6827
- },
6828
- {
6829
- name: "maestro",
6830
- isLocal: false,
6831
- numberValidationRules: {
6832
- luhnCheck: true,
6833
- ranges: [
6834
- 5018,
6835
- 5020,
6836
- 5038,
6837
- 5893,
6838
- 6101,
6839
- 6304,
6840
- 6759,
6841
- 6761,
6842
- 6762,
6843
- 6763,
6844
- 493698,
6845
- [5e5, 504174],
6846
- [504176, 506698],
6847
- [506779, 508999],
6848
- 69
6849
- ],
6850
- lengths: [12, 13, 14, 15, 16, 17, 18, 19]
6851
- },
6852
- securityCodeValidationRules: {
6853
- lengths: [3]
6854
- }
6855
- },
6856
- {
6857
- name: "elo",
6858
- isLocal: true,
6859
- numberValidationRules: {
6860
- luhnCheck: true,
6861
- ranges: [
6862
- 401178,
6863
- 401179,
6864
- 438935,
6865
- 457631,
6866
- 457632,
6867
- 431274,
6868
- 451416,
6869
- 457393,
6870
- 504175,
6871
- [506699, 506778],
6872
- [509e3, 509999],
6873
- 627780,
6874
- 636297,
6875
- 636368,
6876
- [650031, 650033],
6877
- [650035, 650051],
6878
- [650405, 650439],
6879
- [650485, 650538],
6880
- [650541, 650598],
6881
- [650700, 650718],
6882
- [650720, 650727],
6883
- [650901, 650978],
6884
- [651652, 651679],
6885
- [655e3, 655019],
6886
- [655021, 655058]
6887
- ],
6888
- lengths: [16]
6889
- },
6890
- securityCodeValidationRules: {
6891
- lengths: [3]
6892
- }
6893
- },
6894
- {
6895
- name: "mir",
6896
- isLocal: true,
6897
- numberValidationRules: {
6898
- luhnCheck: true,
6899
- ranges: [[2200, 2204]],
6900
- lengths: [16, 17, 18, 19]
6901
- },
6902
- securityCodeValidationRules: {
6903
- lengths: [3]
6904
- }
6905
- },
6906
- {
6907
- name: "hiper",
6908
- isLocal: true,
6909
- numberValidationRules: {
6910
- luhnCheck: true,
6911
- ranges: [637095, 63737423, 63743358, 637568, 637599, 637609, 637612],
6912
- lengths: [16]
6913
- },
6914
- securityCodeValidationRules: {
6915
- lengths: [3]
6916
- }
6917
- },
6918
- {
6919
- name: "hipercard",
6920
- isLocal: true,
6921
- numberValidationRules: {
6922
- luhnCheck: true,
6923
- ranges: [606282],
6924
- lengths: [16]
6925
- },
6926
- securityCodeValidationRules: {
6927
- lengths: [3]
6928
- }
6929
- },
6930
- {
6931
- name: "szep",
6932
- isLocal: true,
6933
- numberValidationRules: {
6934
- luhnCheck: true,
6935
- ranges: [30867825, 61013170, 61013242],
6936
- lengths: [16]
6937
- },
6938
- securityCodeValidationRules: {
6939
- lengths: [3]
6940
- }
6941
- },
6942
- {
6943
- name: "uatp",
6944
- isLocal: false,
6945
- numberValidationRules: {
6946
- luhnCheck: true,
6947
- ranges: [1],
6948
- lengths: [15]
6949
- },
6950
- securityCodeValidationRules: {
6951
- lengths: [0]
6952
- }
6953
- },
6954
- {
6955
- name: "rupay",
6956
- isLocal: false,
6957
- numberValidationRules: {
6958
- luhnCheck: true,
6959
- ranges: [60, 81, 82, 508, [652100, 653149], [817200, 819899]],
6960
- lengths: [16]
6961
- },
6962
- securityCodeValidationRules: {
6963
- lengths: [3]
6964
- }
6965
- }
6966
- ];
6967
- function m(e, n, t) {
6968
- const s = String(n).length, l = e.substring(0, s), a = parseInt(l, 10);
6969
- return l.length < s ? false : (n = parseInt(String(n).substring(0, l.length), 10), t = parseInt(String(t).substring(0, l.length), 10), a >= n && a <= t);
6970
- }
6971
- function V(e, n) {
6972
- return e.startsWith(String(n));
6973
- }
6974
- function f(e) {
6975
- return e.length < 16 ? e.substring(0, 6) : e.substring(0, 8);
6976
- }
6977
- function C(e) {
6978
- const n = String(e).replace(/\s/g, "");
6979
- if (!/^\d*$/.test(n))
6980
- return {
6981
- brand: null,
6982
- localBrands: [],
6983
- bin: null,
6984
- lastFour: null,
6985
- isValid: false
6986
- };
6987
- const t = h.filter((i) => i.numberValidationRules.ranges.some((r) => {
6988
- if (Array.isArray(r)) {
6989
- if (r[0] && r[1])
6990
- return m(n, r[0], r[1]);
6991
- } else
6992
- return V(n, r);
6993
- return false;
6994
- })), s = t.filter((i) => !i.isLocal), l = t.filter((i) => i.isLocal), a = t.length > 0 && t.every((i) => {
6995
- const { lengths: r, luhnCheck: o } = i.numberValidationRules, c = r.includes(n.length), d = !o || g(n);
6996
- return c && d;
6997
- }), u = e.length > 5;
6998
- return {
6999
- brand: s.length > 0 ? s[0].name : null,
7000
- localBrands: l.map((i) => i.name),
7001
- bin: u ? f(e) : null,
7002
- lastFour: a ? n.substring(n.length - 4) : null,
7003
- isValid: a
7004
- };
7005
- }
7006
- function R(e, n) {
7007
- if (!/^\d{3,4}$/.test(e))
7008
- return {
7009
- cvc: null,
7010
- isValid: false
7011
- };
7012
- if (!n)
7013
- return {
7014
- cvc: e,
7015
- isValid: true
7016
- };
7017
- const t = C(n);
7018
- if (!t.isValid)
7019
- return {
7020
- cvc: null,
7021
- isValid: false
7022
- };
7023
- const s = [];
7024
- t.brand && s.push(t.brand), t.localBrands && s.push(...t.localBrands);
7025
- const l = h.filter((a) => s.includes(a.name)).some((a) => a.securityCodeValidationRules.lengths.includes(e.length));
7026
- return {
7027
- cvc: l ? e : null,
7028
- isValid: l
7029
- };
7030
- }
7031
- function b(e) {
7032
- var i;
7033
- const n = /^(0[1-9]|1[[0-2]).*$/, t = e.match(n), s = t ? parseInt(t[1].toString(), 10) : null, l = /^(0[1-9]|1[[0-2])(\d{2})$/, a = e.match(l), u = a ? parseInt(a[2].toString(), 10) : null;
7034
- if (s) {
7035
- const r = (/* @__PURE__ */ new Date()).getFullYear() % 100, o = (/* @__PURE__ */ new Date()).getMonth() + 1, c = !u || u < r || u === r && s < o;
7036
- return {
7037
- month: s.toString().padStart(2, "0"),
7038
- year: ((i = u == null ? void 0 : u.toString()) == null ? void 0 : i.padStart(2, "0")) ?? null,
7039
- isValid: !c
7040
- };
7041
- }
7042
- return {
7043
- month: null,
7044
- year: null,
7045
- isValid: false
7046
- };
7047
- }
7048
-
7049
- async function formatPayload(values, context) {
7050
- const number = values.number?.replace(/\s/g, "") || "";
7051
- const { brand, localBrands, bin, lastFour, isValid: isNumberValid, } = C(number);
7052
- if (number.length > 0 &&
7053
- brand !== "american-express" &&
7054
- values.cvc?.length === 4) {
7055
- context.form.setValue("cvc", values.cvc?.slice(0, 3));
7056
- }
7057
- const { cvc, isValid: isCvcValid } = R(values.cvc ?? "", number);
7058
- const formErrors = context.form.formState.errors;
7059
- const isValid = !Object.keys(formErrors).length;
7060
- const isComplete = areValuesComplete(values);
7061
- const errors = {};
7062
- if (formErrors.name?.message) {
7063
- errors.name = formErrors.name.message;
7064
- }
7065
- if (formErrors.number?.message) {
7066
- errors.number = formErrors.number.message;
7067
- }
7068
- if (formErrors.expiry?.message) {
7069
- errors.expiry = formErrors.expiry.message;
7070
- }
7071
- if (formErrors.cvc?.message) {
7072
- errors.cvc = formErrors.cvc.message;
7073
- }
7074
- return {
7075
- card: {
7076
- name: values.name ?? null,
7077
- brand,
7078
- localBrands,
7079
- bin,
7080
- lastFour,
7081
- expiry: formatExpiry(values.expiry ?? ""),
7082
- number: isNumberValid ? await context.encrypt(number) : null,
7083
- cvc: isCvcValid ? await context.encrypt(cvc ?? "") : null,
7084
- },
7085
- isComplete,
7086
- isValid: isValid && isComplete,
7087
- errors,
7088
- };
7089
- }
7090
- function areValuesComplete(values) {
7091
- if ("name" in values && !values.name?.length) {
7092
- return false;
7093
- }
7094
- if ("number" in values && !C(values.number ?? "").isValid) {
7095
- return false;
7096
- }
7097
- if ("expiry" in values && !b(values.expiry ?? "").isValid) {
7098
- return false;
7099
- }
7100
- if ("cvc" in values &&
7101
- !R(values.cvc ?? "", values.number).isValid) {
7102
- return false;
7103
- }
7104
- return true;
7105
- }
7106
- function isAcceptedBrand(acceptedBrands, cardNumberValidationResult) {
7107
- if (!acceptedBrands?.length)
7108
- return true;
7109
- if (!cardNumberValidationResult.isValid)
7110
- return false;
7111
- const { brand, localBrands } = cardNumberValidationResult;
7112
- const acceptedBrandsSet = new Set(acceptedBrands);
7113
- const isBrandAccepted = brand !== null && acceptedBrandsSet.has(brand);
7114
- const isLocalBrandAccepted = localBrands.some((localBrand) => acceptedBrandsSet.has(localBrand));
7115
- return isBrandAccepted || isLocalBrandAccepted;
7116
- }
7117
- function formatExpiry(expiry) {
7118
- const parsedExpiry = b(expiry);
7119
- if (!parsedExpiry.isValid) {
7120
- return null;
7121
- }
7122
- return {
7123
- month: parsedExpiry.month,
7124
- year: parsedExpiry.year,
7125
- };
7126
- }
7127
-
7128
- function getCardFormSchema(acceptedBrands) {
7129
- return z.object({
7130
- name: z.string().min(1, "Missing name"),
7131
- number: z
7132
- .string()
7133
- .min(1, "Required")
7134
- .refine((value) => C(value).isValid, {
7135
- message: "Invalid card number",
7136
- })
7137
- .refine((value) => isAcceptedBrand(acceptedBrands, C(value)), { message: "Brand not accepted" }),
7138
- expiry: z
7139
- .string()
7140
- .min(1, "Required")
7141
- .refine((value) => b(value).isValid, {
7142
- message: "Invalid expiry",
7143
- }),
7144
- cvc: z
7145
- .string()
7146
- .min(1, "Required")
7147
- .refine((value) => R(value).isValid, {
7148
- message: "Invalid CVC",
7149
- }),
7150
- });
7151
- }
7152
-
7153
- const r=(t,r,o)=>{if(t&&"reportValidity"in t){const s=get(o,r);t.setCustomValidity(s&&s.message||""),t.reportValidity();}},o=(e,t)=>{for(const o in t.fields){const s=t.fields[o];s&&s.ref&&"reportValidity"in s.ref?r(s.ref,o,e):s&&s.refs&&s.refs.forEach(t=>r(t,o,e));}},s$1=(r,s)=>{s.shouldUseNativeValidation&&o(r,s);const n={};for(const o in r){const f=get(s.fields,o),c=Object.assign(r[o]||{},{ref:f&&f.ref});if(i(s.names||Object.keys(r),o)){const r=Object.assign({},get(n,o));set(r,"root",c),set(n,o,r);}else set(n,o,c);}return n},i=(e,t)=>{const r=n$1(t);return e.some(e=>n$1(e).match(`^${r}\\.\\d+`))};function n$1(e){return e.replace(/\]|\[/g,"")}
7154
-
7155
- function n(r,e){for(var n={};r.length;){var s=r[0],t=s.code,i=s.message,a=s.path.join(".");if(!n[a])if("unionErrors"in s){var u=s.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code};}else n[a]={message:i,type:t};if("unionErrors"in s&&s.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[s.code];n[a]=appendErrors(a,e,n,t,f?[].concat(f,s.message):s.message);}r.shift();}return n}function s(o$1,s,t){return void 0===t&&(t={}),function(i,a,u){try{return Promise.resolve(function(e,n){try{var a=Promise.resolve(o$1["sync"===t.mode?"parse":"parseAsync"](i,s)).then(function(e){return u.shouldUseNativeValidation&&o({},u),{errors:{},values:t.raw?Object.assign({},i):e}});}catch(r){return n(r)}return a&&a.then?a.then(void 0,n):a}(0,function(r){if(function(r){return Array.isArray(null==r?void 0:r.errors)}(r))return {values:{},errors:s$1(n(r.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw r}))}catch(r){return Promise.reject(r)}}}
7156
-
7157
- // Taken from https://github.com/gregberge/react-merge-refs
7158
- function mergeRefs(...refs) {
7159
- return (value) => {
7160
- refs.forEach((ref) => {
7161
- if (typeof ref === "function") {
7162
- ref(value);
7163
- }
7164
- else if (ref != null) {
7165
- ref.current = value;
7166
- }
7167
- });
7168
- };
7169
- }
7170
-
7171
- function formatWithMask(props) {
7172
- const {
7173
- text,
7174
- mask,
7175
- obfuscationCharacter = '*',
7176
- maskAutoComplete = false
7177
- } = props; // make sure it'll not break with null or undefined inputs
7178
-
7179
- if (!text) return {
7180
- masked: '',
7181
- unmasked: '',
7182
- obfuscated: ''
7183
- };
7184
- if (!mask) return {
7185
- masked: text || '',
7186
- unmasked: text || '',
7187
- obfuscated: text || ''
7188
- };
7189
- let maskArray = typeof mask === 'function' ? mask(text) : mask;
7190
- let masked = '';
7191
- let obfuscated = '';
7192
- let unmasked = '';
7193
- let maskCharIndex = 0;
7194
- let valueCharIndex = 0;
7195
-
7196
- while (true) {
7197
- // if mask is ended, break.
7198
- if (maskCharIndex === maskArray.length) {
7199
- break;
7200
- }
7201
-
7202
- let maskChar = maskArray[maskCharIndex];
7203
- let valueChar = text[valueCharIndex]; // if value is ended, break.
7204
-
7205
- if (valueCharIndex === text.length) {
7206
- if (typeof maskChar === 'string' && maskAutoComplete) {
7207
- masked += maskChar;
7208
- obfuscated += maskChar;
7209
- maskCharIndex += 1;
7210
- continue;
7211
- }
7212
-
7213
- break;
7214
- } // value equals mask: add to masked result and advance on both mask and value indexes
7215
-
7216
-
7217
- if (maskChar === valueChar) {
7218
- masked += maskChar;
7219
- obfuscated += maskChar;
7220
- valueCharIndex += 1;
7221
- maskCharIndex += 1;
7222
- continue;
7223
- }
7224
-
7225
- let unmaskedValueChar = text[valueCharIndex]; // it's a regex maskChar: let's advance on value index and validate the value within the regex
7226
-
7227
- if (typeof maskChar === 'object') {
7228
- // advance on value index
7229
- valueCharIndex += 1;
7230
- const shouldObsfucateChar = Array.isArray(maskChar);
7231
- const maskCharRegex = Array.isArray(maskChar) ? maskChar[0] : maskChar;
7232
- const matchRegex = RegExp(maskCharRegex).test(valueChar); // value match regex: add to masked and unmasked result and advance on mask index too
7233
-
7234
- if (matchRegex) {
7235
- masked += valueChar;
7236
- obfuscated += shouldObsfucateChar ? obfuscationCharacter : valueChar;
7237
- unmasked += unmaskedValueChar;
7238
- maskCharIndex += 1;
7239
- }
7240
-
7241
- continue;
7242
- } else {
7243
- // it's a fixed maskChar: add to maskedResult and advance on mask index
7244
- masked += maskChar;
7245
- obfuscated += maskChar;
7246
- maskCharIndex += 1;
7247
- continue;
7248
- }
7249
- }
7250
-
7251
- return {
7252
- masked,
7253
- unmasked,
7254
- obfuscated
7255
- };
7256
- }
7257
-
7258
- var useMaskedInputProps = (props => {
7259
- const {
7260
- value,
7261
- mask,
7262
- onChangeText,
7263
- placeholderFillCharacter = '_',
7264
- obfuscationCharacter,
7265
- showObfuscatedValue,
7266
- maskAutoComplete
7267
- } = props;
7268
- const maskArray = React__namespace.useMemo(() => typeof mask === 'function' ? mask(value) : mask, [mask, value]);
7269
- const formattedValueResult = React__namespace.useMemo(() => {
7270
- return formatWithMask({
7271
- text: value || '',
7272
- mask,
7273
- obfuscationCharacter
7274
- });
7275
- }, [mask, obfuscationCharacter, value]);
7276
- const maskHasObfuscation = React__namespace.useMemo(() => maskArray && !!maskArray.find(maskItem => Array.isArray(maskItem)), [maskArray]);
7277
- const isValueObfuscated = React__namespace.useMemo(() => !!maskHasObfuscation && !!showObfuscatedValue, [maskHasObfuscation, showObfuscatedValue]);
7278
- const handleChangeText = React__namespace.useCallback(text => {
7279
- let textToFormat = text;
7280
-
7281
- if (isValueObfuscated) {
7282
- textToFormat = formattedValueResult.masked || '';
7283
-
7284
- if (textToFormat.length > text.length) {
7285
- textToFormat = textToFormat.slice(0, -1);
7286
- } else if (textToFormat.length < text.length) {
7287
- textToFormat = textToFormat + text[text.length - 1];
7288
- }
7289
- }
7290
-
7291
- const result = formatWithMask({
7292
- text: textToFormat,
7293
- mask,
7294
- obfuscationCharacter,
7295
- maskAutoComplete: maskAutoComplete && textToFormat.length > formattedValueResult.masked.length
7296
- });
7297
- onChangeText && onChangeText(result.masked, result.unmasked, result.obfuscated);
7298
- }, [isValueObfuscated, mask, obfuscationCharacter, onChangeText, formattedValueResult.masked, maskAutoComplete]);
7299
- const defaultPlaceholder = React__namespace.useMemo(() => {
7300
- if (maskArray) {
7301
- return maskArray.map(maskChar => {
7302
- if (typeof maskChar === 'string') {
7303
- return maskChar;
7304
- } else {
7305
- return placeholderFillCharacter;
7306
- }
7307
- }).join('');
7308
- } else {
7309
- return undefined;
7310
- }
7311
- }, [maskArray, placeholderFillCharacter]);
7312
- const inputValue = isValueObfuscated ? formattedValueResult.obfuscated : formattedValueResult.masked;
7313
- return {
7314
- onChangeText: handleChangeText,
7315
- value: inputValue,
7316
- selection: isValueObfuscated ? {
7317
- start: inputValue.length,
7318
- end: inputValue.length
7319
- } : undefined,
7320
- placeholder: defaultPlaceholder
7321
- };
7322
- });
7323
-
7324
- function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
7325
- var MaskInput = /*#__PURE__*/React__namespace.forwardRef(function (props, ref) {
7326
- const {
7327
- mask,
7328
- value,
7329
- onChangeText,
7330
- placeholderFillCharacter = '_',
7331
- obfuscationCharacter,
7332
- showObfuscatedValue,
7333
- selection,
7334
- maskAutoComplete,
7335
- ...rest
7336
- } = props;
7337
- const maskedInputProps = useMaskedInputProps({
7338
- value,
7339
- mask,
7340
- maskAutoComplete,
7341
- obfuscationCharacter,
7342
- onChangeText,
7343
- placeholderFillCharacter,
7344
- showObfuscatedValue
7345
- });
7346
- return /*#__PURE__*/React__namespace.createElement(reactNative.TextInput, _extends({
7347
- placeholder: maskedInputProps.placeholder
7348
- }, rest, {
7349
- selection: maskedInputProps.selection || selection,
7350
- value: maskedInputProps.value,
7351
- onChangeText: maskedInputProps.onChangeText,
7352
- ref: ref
7353
- }));
7354
- });
7355
-
7356
- const EvervaultInputContext = React.createContext({
7357
- validationMode: "all",
7358
- });
7359
- function useForwardedInputRef(ref) {
7360
- const inputRef = React.useRef(null);
7361
- React.useImperativeHandle(ref, React.useCallback(() => ({
7362
- isFocused() {
7363
- return inputRef.current?.isFocused() ?? false;
7364
- },
7365
- focus() {
7366
- inputRef.current?.focus();
7367
- },
7368
- blur() {
7369
- inputRef.current?.blur();
7370
- },
7371
- clear() {
7372
- inputRef.current?.clear();
7373
- },
7374
- measure(callback) {
7375
- inputRef.current?.measure(callback);
7376
- },
7377
- measureInWindow(callback) {
7378
- inputRef.current?.measureInWindow(callback);
7379
- },
7380
- measureLayout(relativeToNativeComponentRef, onSuccess, onFail) {
7381
- inputRef.current?.measureLayout(relativeToNativeComponentRef, onSuccess, onFail);
7382
- },
7383
- }), [inputRef]));
7384
- return inputRef;
7385
- }
7386
- function mask(format) {
7387
- const maskArray = [];
7388
- let isObfuscated = false;
7389
- format.split("").forEach((char) => {
7390
- if (char === "[") {
7391
- isObfuscated = true;
7392
- return;
7393
- }
7394
- else if (char === "]") {
7395
- isObfuscated = false;
7396
- return;
7397
- }
7398
- let value = char;
7399
- if (char === "9") {
7400
- value = isObfuscated ? [/\d/] : /\d/;
7401
- }
7402
- maskArray.push(value);
7403
- });
7404
- return maskArray;
7405
- }
7406
- const EvervaultInput = React.forwardRef(function EvervaultInput({ name, mask, obfuscateValue, ...props }, ref) {
7407
- const { validationMode } = React.useContext(EvervaultInputContext);
7408
- const inputRef = useForwardedInputRef(ref);
7409
- const methods = useFormContext();
7410
- const { field, fieldState } = useController({
7411
- control: methods.control,
7412
- name,
7413
- shouldUnregister: true,
7414
- });
7415
- const obfuscationCharacter = React.useMemo(() => {
7416
- if (typeof obfuscateValue === "string") {
7417
- return obfuscateValue;
7418
- }
7419
- else {
7420
- return "•";
7421
- }
7422
- }, [obfuscateValue]);
7423
- return (jsxRuntime.jsx(MaskInput
7424
- // Overridable props
7425
- , {
7426
- // Overridable props
7427
- id: field.name, ...props,
7428
- // Strict props
7429
- ref: mergeRefs(inputRef, field.ref), editable: !field.disabled && (props.editable ?? true), onBlur: (evt) => {
7430
- const shouldValidate = validationMode === "onBlur" ||
7431
- validationMode === "onTouched" ||
7432
- validationMode === "all";
7433
- methods.setValue(field.name, field.value, {
7434
- shouldDirty: true,
7435
- shouldTouch: true,
7436
- shouldValidate,
7437
- });
7438
- props.onBlur?.(evt);
7439
- }, mask: mask, maskAutoComplete: !!mask, obfuscationCharacter: obfuscationCharacter, showObfuscatedValue: !!obfuscateValue, value: field.value, onChangeText: (masked, unmasked) => {
7440
- const shouldValidate = (validationMode === "onTouched" && fieldState.isTouched) ||
7441
- ((validationMode === "onChange" || validationMode === "all") &&
7442
- (!!fieldState.error || fieldState.isTouched));
7443
- methods.setValue(field.name, unmasked, {
7444
- shouldDirty: true,
7445
- shouldValidate,
7446
- });
7447
- },
7448
- // Remove unwanted props
7449
- defaultValue: undefined, onChange: undefined }));
7450
- });
7451
-
7452
- const DEFAULT_ACCEPTED_BRANDS = [];
7453
- const Card$1 = React.forwardRef(function Card({ children, defaultValues, onChange, onError, acceptedBrands = DEFAULT_ACCEPTED_BRANDS, validationMode = "all", }, ref) {
7454
- const evervault = useEvervault();
7455
- const resolver = React.useMemo(() => {
7456
- const schema = getCardFormSchema(acceptedBrands);
7457
- return s(schema);
7458
- }, [acceptedBrands]);
7459
- const methods = useForm({
7460
- defaultValues,
7461
- resolver,
7462
- mode: validationMode,
7463
- shouldUseNativeValidation: false,
7464
- });
7465
- const inputContext = React.useMemo(() => ({
7466
- validationMode,
7467
- }), [validationMode]);
7468
- // Use refs to prevent closures from being captured
7469
- const onChangeRef = React.useRef(onChange);
7470
- onChangeRef.current = onChange;
7471
- const onErrorRef = React.useRef(onError);
7472
- onErrorRef.current = onError;
7473
- React.useEffect(() => {
7474
- if (!onChange)
7475
- return;
7476
- let abortController;
7477
- function handleChange(values) {
7478
- if (abortController) {
7479
- abortController.abort();
7480
- }
7481
- abortController = new AbortController();
7482
- const signal = abortController.signal;
7483
- requestAnimationFrame(async () => {
7484
- try {
7485
- const payload = await formatPayload(values, {
7486
- encrypt: evervault.encrypt,
7487
- form: methods,
7488
- });
7489
- if (signal.aborted)
7490
- return;
7491
- onChangeRef.current?.(payload);
7492
- }
7493
- catch (error) {
7494
- onErrorRef.current?.(error);
7495
- }
7496
- });
7497
- }
7498
- handleChange(methods.getValues());
7499
- const subscription = methods.watch(handleChange);
7500
- return () => subscription.unsubscribe();
7501
- }, [evervault.encrypt]);
7502
- React.useImperativeHandle(ref, React.useCallback(() => ({
7503
- reset() {
7504
- methods.reset();
7505
- },
7506
- }), []));
7507
- return (jsxRuntime.jsx(FormProvider, { ...methods, children: jsxRuntime.jsx(EvervaultInputContext.Provider, { value: inputContext, children: children }) }));
7508
- });
7509
-
7510
- const CardHolder = React.forwardRef(function CardHolder(props, ref) {
7511
- return (jsxRuntime.jsx(EvervaultInput, { placeholder: "Johnny Appleseed", ...props, ref: ref, name: "name", inputMode: "text", autoComplete: reactNative.Platform.select({
7512
- ios: "cc-name",
7513
- default: "name",
7514
- }), keyboardType: "default" }));
7515
- });
7516
-
7517
- const CARD_EXPIRY_MASK = mask("99 / 99");
7518
- const CardExpiry = React.forwardRef(function CardExpiry(props, ref) {
7519
- return (jsxRuntime.jsx(EvervaultInput, { placeholder: "MM / YY", ...props, ref: ref, name: "expiry", mask: CARD_EXPIRY_MASK, inputMode: "numeric", autoComplete: "cc-exp", keyboardType: "number-pad" }));
7520
- });
7521
-
7522
- const DEFAULT_CARD_CVC_MASK = mask("[999]");
7523
- const CARD_CVC_MASKS = {
7524
- "american-express": mask("[9999]"),
7525
- };
7526
- const CardCvc = React.forwardRef(function CardCvc(props, ref) {
7527
- const methods = useFormContext();
7528
- const number = methods.watch("number");
7529
- const mask = React.useMemo(() => {
7530
- if (!number) {
7531
- return DEFAULT_CARD_CVC_MASK;
7532
- }
7533
- const brand = C(number).brand;
7534
- if (brand && CARD_CVC_MASKS[brand]) {
7535
- return CARD_CVC_MASKS[brand];
7536
- }
7537
- return DEFAULT_CARD_CVC_MASK;
7538
- }, [number]);
7539
- return (jsxRuntime.jsx(EvervaultInput, { placeholder: "CVC", ...props, ref: ref, name: "cvc", mask: mask, inputMode: "numeric", autoComplete: "cc-csc", keyboardType: "number-pad" }));
7540
- });
7541
-
7542
- const DEFAULT_CARD_NUMBER_MASK = mask("9999 99[99 9999 9999]");
7543
- const CARD_NUMBER_MASKS = {
7544
- unionpay: mask("9999 99[99 9999 9999 999]"),
7545
- "american-express": mask("9999 99[9999 99999]"),
7546
- };
7547
- const CardNumber = React.forwardRef(function CardNumber(props, ref) {
7548
- const mask = React.useCallback((text) => {
7549
- if (!text) {
7550
- return DEFAULT_CARD_NUMBER_MASK;
7551
- }
7552
- const brand = C(text).brand;
7553
- if (brand && CARD_NUMBER_MASKS[brand]) {
7554
- return CARD_NUMBER_MASKS[brand];
7555
- }
7556
- return DEFAULT_CARD_NUMBER_MASK;
7557
- }, []);
7558
- return (jsxRuntime.jsx(EvervaultInput, { placeholder: "1234 1234 1234 1234", ...props, ref: ref, name: "number", mask: mask, inputMode: "numeric", autoComplete: "cc-number", keyboardType: "number-pad" }));
7559
- });
7560
-
7561
- const Card = Object.assign(Card$1, {
7562
- Holder: CardHolder,
7563
- Expiry: CardExpiry,
7564
- Cvc: CardCvc,
7565
- Number: CardNumber,
7566
- });
7567
-
7568
- const ThreeDSecureContext = React.createContext(null);
7569
-
7570
- function ThreeDSecure$1({ state, children }) {
7571
- useEvervault();
7572
- if (!state.session)
7573
- return null;
7574
- return (jsxRuntime.jsx(ThreeDSecureContext.Provider, { value: state, children: state.isVisible && children }));
7575
- }
7576
-
7577
- const EV_API_DOMAIN = process.env.EV_API_DOMAIN || "api.evervault.com";
7578
- const CHALLENGE_DOMAIN_3DS = process.env.CHALLENGE_DOMAIN_3DS || "3ds.evervault.com";
7579
-
7580
- function ThreeDSecureFrame({ style }) {
7581
- const evervault = useEvervault();
7582
- const context = React.useContext(ThreeDSecureContext);
7583
- if (!context) {
7584
- throw new Error("`ThreeDSecure.Frame` must be used within a `ThreeDSecure` component.");
7585
- }
7586
- const uri = React.useMemo(() => {
7587
- if (!context.session)
7588
- return null;
7589
- const params = new URLSearchParams();
7590
- params.set("session", context.session.sessionId);
7591
- params.set("app", evervault.appId);
7592
- params.set("team", evervault.teamId);
7593
- return `https://${CHALLENGE_DOMAIN_3DS}/?${params.toString()}`;
7594
- }, [context.session, evervault.appId, evervault.teamId]);
7595
- if (!uri)
7596
- return null;
7597
- return (jsxRuntime.jsx(reactNativeWebview.WebView, { containerStyle: [defaultStyles.webView, style], source: { uri }, hideKeyboardAccessoryView: true, overScrollMode: "content" }));
7598
- }
7599
- const defaultStyles = reactNative.StyleSheet.create({
7600
- webView: {
7601
- flex: 1,
7602
- width: "100%",
7603
- },
7604
- });
7605
-
7606
- class ThreeDSecureEvent {
7607
- type;
7608
- session;
7609
- _defaultPrevented;
7610
- constructor(type, session, _defaultPrevented = false) {
7611
- this.type = type;
7612
- this.session = session;
7613
- this._defaultPrevented = _defaultPrevented;
7614
- }
7615
- preventDefault() {
7616
- this._defaultPrevented = true;
7617
- }
7618
- get defaultPrevented() {
7619
- return this._defaultPrevented;
7620
- }
7621
- }
7622
-
7623
- function stopPolling(intervalRef, setIsVisible) {
7624
- setIsVisible(false);
7625
- if (intervalRef.current) {
7626
- clearInterval(intervalRef.current);
7627
- intervalRef.current = null;
7628
- }
7629
- }
7630
- async function startSession(session, options, intervalRef, setIsVisible) {
7631
- try {
7632
- const sessionState = await session.get();
7633
- function fail() {
7634
- stopPolling(intervalRef, setIsVisible);
7635
- options?.onFailure?.(new Error("3DS session failed"));
7636
- }
7637
- switch (sessionState.status) {
7638
- case "success": {
7639
- stopPolling(intervalRef, setIsVisible);
7640
- options?.onSuccess?.();
7641
- break;
7642
- }
7643
- case "failure": {
7644
- fail();
7645
- break;
7646
- }
7647
- case "action-required": {
7648
- const failOnChallenge = typeof options?.failOnChallenge === "function"
7649
- ? await options.failOnChallenge()
7650
- : options?.failOnChallenge ?? false;
7651
- if (failOnChallenge) {
7652
- fail();
7653
- break;
7654
- }
7655
- const event = new ThreeDSecureEvent("requestChallenge", session);
7656
- options?.onRequestChallenge?.(event);
7657
- if (event.defaultPrevented) {
7658
- fail();
7659
- break;
7660
- }
7661
- setIsVisible(true);
7662
- pollSession(session, options, intervalRef, setIsVisible);
7663
- }
7664
- }
7665
- }
7666
- catch (error) {
7667
- console.error("Error checking session state", error);
7668
- options?.onError?.(new Error("Failed to check 3DS session state"));
7669
- }
7670
- }
7671
- function pollSession(session, options, intervalRef, setIsVisible, interval = 3000) {
7672
- function fail() {
7673
- stopPolling(intervalRef, setIsVisible);
7674
- options?.onFailure?.(new Error("3DS session failed"));
7675
- }
7676
- intervalRef.current = setInterval(async () => {
7677
- try {
7678
- const pollResponse = await session.get();
7679
- switch (pollResponse.status) {
7680
- case "success": {
7681
- stopPolling(intervalRef, setIsVisible);
7682
- options?.onSuccess?.();
7683
- break;
7684
- }
7685
- case "failure": {
7686
- fail();
7687
- break;
7688
- }
7689
- case "action-required": {
7690
- const failOnChallenge = typeof options?.failOnChallenge === "function"
7691
- ? await options.failOnChallenge()
7692
- : options?.failOnChallenge ?? false;
7693
- if (failOnChallenge) {
7694
- fail();
7695
- break;
7696
- }
7697
- const event = new ThreeDSecureEvent("requestChallenge", session);
7698
- options?.onRequestChallenge?.(event);
7699
- if (event.defaultPrevented) {
7700
- fail();
7701
- break;
7702
- }
7703
- setIsVisible(true);
7704
- }
7705
- }
7706
- }
7707
- catch (error) {
7708
- stopPolling(intervalRef, setIsVisible);
7709
- console.error("Error polling session", error);
7710
- options?.onError?.(new Error("Error polling 3DS session"));
7711
- }
7712
- }, interval);
7713
- }
7714
- function threeDSecureSession({ sessionId, appId, options, intervalRef, setIsVisible, }) {
7715
- async function get() {
7716
- try {
7717
- const response = await fetch(`https://${EV_API_DOMAIN}/frontend/3ds/browser-sessions/${sessionId}`, {
7718
- headers: {
7719
- "x-evervault-app-id": appId,
7720
- },
7721
- });
7722
- const result = (await response.json());
7723
- return result;
7724
- }
7725
- catch (error) {
7726
- console.error("Error fetching 3DS session status", error);
7727
- throw error;
7728
- }
7729
- }
7730
- async function cancel() {
7731
- try {
7732
- await fetch(`https://${EV_API_DOMAIN}/frontend/3ds/browser-sessions/${sessionId}`, {
7733
- method: "PATCH",
7734
- headers: {
7735
- "Content-Type": "application/json",
7736
- "x-evervault-app-id": appId,
7737
- },
7738
- body: JSON.stringify({ outcome: "cancelled" }),
7739
- });
7740
- options?.onFailure?.(new Error("3DS session cancelled by user"));
7741
- stopPolling(intervalRef, setIsVisible);
7742
- }
7743
- catch (error) {
7744
- console.error("Error cancelling 3DS session", error);
7745
- throw error;
7746
- }
7747
- }
7748
- return {
7749
- sessionId,
7750
- get,
7751
- cancel,
7752
- };
7753
- }
7754
-
7755
- function useThreeDSecure(options) {
7756
- const { appId } = useEvervault();
7757
- const intervalRef = React.useRef(null);
7758
- const [session, setSession] = React.useState(null);
7759
- const [isVisible, setIsVisible] = React.useState(false);
7760
- const failOnChallenge = options?.failOnChallenge ?? false;
7761
- const start = React.useCallback((sessionId, options) => {
7762
- const startOptions = {
7763
- ...options,
7764
- failOnChallenge: options?.failOnChallenge ?? failOnChallenge,
7765
- };
7766
- const session = threeDSecureSession({
7767
- sessionId,
7768
- appId,
7769
- options: startOptions,
7770
- intervalRef,
7771
- setIsVisible,
7772
- });
7773
- setSession(session);
7774
- startSession(session, startOptions, intervalRef, setIsVisible);
7775
- }, [appId, failOnChallenge]);
7776
- const cancel = React.useCallback(async () => {
7777
- if (session) {
7778
- await session.cancel();
7779
- }
7780
- else {
7781
- console.warn("No 3DS session to cancel");
7782
- }
7783
- }, [session]);
7784
- return React.useMemo(() => ({
7785
- start,
7786
- cancel,
7787
- session,
7788
- isVisible,
7789
- }), [start, cancel, session, isVisible]);
7790
- }
7791
-
7792
- const ThreeDSecure = Object.assign(ThreeDSecure$1, {
7793
- Frame: ThreeDSecureFrame,
7794
- });
7795
-
7796
- const verifyInstallation = sdk.verify;
7797
-
7798
- exports.Card = Card;
7799
- exports.CardCvc = CardCvc;
7800
- exports.CardExpiry = CardExpiry;
7801
- exports.CardHolder = CardHolder;
7802
- exports.CardNumber = CardNumber;
7803
- exports.EvervaultProvider = EvervaultProvider;
7804
- exports.ThreeDSecure = ThreeDSecure;
7805
- exports.useEvervault = useEvervault;
7806
- exports.useThreeDSecure = useThreeDSecure;
7807
- exports.verifyInstallation = verifyInstallation;
7808
- //# sourceMappingURL=index.cjs.js.map
4406
+ exports.BRAND = BRAND;
4407
+ exports.DIRTY = DIRTY;
4408
+ exports.EMPTY_PATH = EMPTY_PATH;
4409
+ exports.INVALID = INVALID;
4410
+ exports.NEVER = NEVER;
4411
+ exports.OK = OK;
4412
+ exports.ParseStatus = ParseStatus;
4413
+ exports.Schema = ZodType;
4414
+ exports.ZodAny = ZodAny;
4415
+ exports.ZodArray = ZodArray;
4416
+ exports.ZodBigInt = ZodBigInt;
4417
+ exports.ZodBoolean = ZodBoolean;
4418
+ exports.ZodBranded = ZodBranded;
4419
+ exports.ZodCatch = ZodCatch;
4420
+ exports.ZodDate = ZodDate;
4421
+ exports.ZodDefault = ZodDefault;
4422
+ exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion;
4423
+ exports.ZodEffects = ZodEffects;
4424
+ exports.ZodEnum = ZodEnum;
4425
+ exports.ZodError = ZodError;
4426
+ exports.ZodFunction = ZodFunction;
4427
+ exports.ZodIntersection = ZodIntersection;
4428
+ exports.ZodIssueCode = ZodIssueCode;
4429
+ exports.ZodLazy = ZodLazy;
4430
+ exports.ZodLiteral = ZodLiteral;
4431
+ exports.ZodMap = ZodMap;
4432
+ exports.ZodNaN = ZodNaN;
4433
+ exports.ZodNativeEnum = ZodNativeEnum;
4434
+ exports.ZodNever = ZodNever;
4435
+ exports.ZodNull = ZodNull;
4436
+ exports.ZodNullable = ZodNullable;
4437
+ exports.ZodNumber = ZodNumber;
4438
+ exports.ZodObject = ZodObject;
4439
+ exports.ZodOptional = ZodOptional;
4440
+ exports.ZodParsedType = ZodParsedType;
4441
+ exports.ZodPipeline = ZodPipeline;
4442
+ exports.ZodPromise = ZodPromise;
4443
+ exports.ZodReadonly = ZodReadonly;
4444
+ exports.ZodRecord = ZodRecord;
4445
+ exports.ZodSchema = ZodType;
4446
+ exports.ZodSet = ZodSet;
4447
+ exports.ZodString = ZodString;
4448
+ exports.ZodSymbol = ZodSymbol;
4449
+ exports.ZodTransformer = ZodEffects;
4450
+ exports.ZodTuple = ZodTuple;
4451
+ exports.ZodType = ZodType;
4452
+ exports.ZodUndefined = ZodUndefined;
4453
+ exports.ZodUnion = ZodUnion;
4454
+ exports.ZodUnknown = ZodUnknown;
4455
+ exports.ZodVoid = ZodVoid;
4456
+ exports.addIssueToContext = addIssueToContext;
4457
+ exports.any = anyType;
4458
+ exports.array = arrayType;
4459
+ exports.bigint = bigIntType;
4460
+ exports.boolean = booleanType;
4461
+ exports.coerce = coerce;
4462
+ exports.custom = custom;
4463
+ exports.date = dateType;
4464
+ exports.datetimeRegex = datetimeRegex;
4465
+ exports.default = z;
4466
+ exports.defaultErrorMap = errorMap;
4467
+ exports.discriminatedUnion = discriminatedUnionType;
4468
+ exports.effect = effectsType;
4469
+ exports.enum = enumType;
4470
+ exports.function = functionType;
4471
+ exports.getErrorMap = getErrorMap;
4472
+ exports.getParsedType = getParsedType;
4473
+ exports.instanceof = instanceOfType;
4474
+ exports.intersection = intersectionType;
4475
+ exports.isAborted = isAborted;
4476
+ exports.isAsync = isAsync;
4477
+ exports.isDirty = isDirty;
4478
+ exports.isValid = isValid;
4479
+ exports.late = late;
4480
+ exports.lazy = lazyType;
4481
+ exports.literal = literalType;
4482
+ exports.makeIssue = makeIssue;
4483
+ exports.map = mapType;
4484
+ exports.nan = nanType;
4485
+ exports.nativeEnum = nativeEnumType;
4486
+ exports.never = neverType;
4487
+ exports.null = nullType;
4488
+ exports.nullable = nullableType;
4489
+ exports.number = numberType;
4490
+ exports.object = objectType;
4491
+ exports.oboolean = oboolean;
4492
+ exports.onumber = onumber;
4493
+ exports.optional = optionalType;
4494
+ exports.ostring = ostring;
4495
+ exports.pipeline = pipelineType;
4496
+ exports.preprocess = preprocessType;
4497
+ exports.promise = promiseType;
4498
+ exports.quotelessJson = quotelessJson;
4499
+ exports.record = recordType;
4500
+ exports.set = setType;
4501
+ exports.setErrorMap = setErrorMap;
4502
+ exports.strictObject = strictObjectType;
4503
+ exports.string = stringType;
4504
+ exports.symbol = symbolType;
4505
+ exports.transformer = effectsType;
4506
+ exports.tuple = tupleType;
4507
+ exports.undefined = undefinedType;
4508
+ exports.union = unionType;
4509
+ exports.unknown = unknownType;
4510
+ exports.void = voidType;
4511
+ exports.z = z;