@conform-to/dom 1.1.5 → 1.2.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.
package/dom.d.ts CHANGED
@@ -2,10 +2,7 @@
2
2
  * Element that user can interact with,
3
3
  * includes `<input>`, `<select>` and `<textarea>`.
4
4
  */
5
- export type FieldElement =
6
- | HTMLInputElement
7
- | HTMLSelectElement
8
- | HTMLTextAreaElement;
5
+ export type FieldElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
9
6
  /**
10
7
  * HTML Element that can be used as a form control,
11
8
  * includes `<input>`, `<select>`, `<textarea>` and `<button>`.
@@ -23,9 +20,7 @@ export declare function isFormControl(element: unknown): element is FormControl;
23
20
  * A type guard to check if the provided element is a field element, which
24
21
  * is a form control excluding submit, button and reset type.
25
22
  */
26
- export declare function isFieldElement(
27
- element: unknown,
28
- ): element is FieldElement;
23
+ export declare function isFieldElement(element: unknown): element is FieldElement;
29
24
  /**
30
25
  * Resolves the action from the submit event
31
26
  * with respect to the submitter `formaction` attribute.
@@ -35,21 +30,14 @@ export declare function getFormAction(event: SubmitEvent): string;
35
30
  * Resolves the encoding type from the submit event
36
31
  * with respect to the submitter `formenctype` attribute.
37
32
  */
38
- export declare function getFormEncType(
39
- event: SubmitEvent,
40
- ): 'application/x-www-form-urlencoded' | 'multipart/form-data';
33
+ export declare function getFormEncType(event: SubmitEvent): 'application/x-www-form-urlencoded' | 'multipart/form-data';
41
34
  /**
42
35
  * Resolves the method from the submit event
43
36
  * with respect to the submitter `formmethod` attribute.
44
37
  */
45
- export declare function getFormMethod(
46
- event: SubmitEvent,
47
- ): 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
38
+ export declare function getFormMethod(event: SubmitEvent): 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
48
39
  /**
49
40
  * Trigger a form submit event with an optional submitter.
50
41
  * If the submitter is not mounted, it will be appended to the form and removed after submission.
51
42
  */
52
- export declare function requestSubmit(
53
- form: HTMLFormElement | null | undefined,
54
- submitter: Submitter | null,
55
- ): void;
43
+ export declare function requestSubmit(form: HTMLFormElement | null | undefined, submitter: Submitter | null): void;
package/form.d.ts CHANGED
@@ -1,246 +1,147 @@
1
1
  import { getFormAction, getFormEncType, getFormMethod } from './dom';
2
- import {
3
- type Intent,
4
- type Submission,
5
- type SubmissionResult,
6
- } from './submission';
7
- type BaseCombine<
8
- T,
9
- K extends PropertyKey = T extends unknown ? keyof T : never,
10
- > = T extends unknown ? T & Partial<Record<Exclude<K, keyof T>, never>> : never;
2
+ import { type Intent, type Submission, type SubmissionResult } from './submission';
3
+ type BaseCombine<T, K extends PropertyKey = T extends unknown ? keyof T : never> = T extends unknown ? T & Partial<Record<Exclude<K, keyof T>, never>> : never;
11
4
  export type Combine<T> = {
12
- [K in keyof BaseCombine<T>]: BaseCombine<T>[K];
5
+ [K in keyof BaseCombine<T>]: BaseCombine<T>[K];
13
6
  };
14
- export type DefaultValue<Schema> = Schema extends
15
- | string
16
- | number
17
- | boolean
18
- | Date
19
- | bigint
20
- | null
21
- | undefined
22
- ? Schema | string | null | undefined
23
- : Schema extends File
24
- ? null | undefined
25
- : Schema extends Array<infer Item>
26
- ? Array<DefaultValue<Item>> | null | undefined
27
- : Schema extends Record<string, any>
28
- ?
29
- | {
30
- [Key in keyof Schema]?: DefaultValue<Schema[Key]>;
31
- }
32
- | null
33
- | undefined
34
- : string | null | undefined;
35
- export type FormValue<Schema> = Schema extends
36
- | string
37
- | number
38
- | boolean
39
- | Date
40
- | bigint
41
- | null
42
- | undefined
43
- ? string | undefined
44
- : Schema extends File
45
- ? File | undefined
46
- : Schema extends File[]
47
- ? File | Array<File> | undefined
48
- : Schema extends Array<infer Item>
49
- ? string | Array<FormValue<Item>> | undefined
50
- : Schema extends Record<string, any>
51
- ?
52
- | {
53
- [Key in keyof Schema]?: FormValue<Schema[Key]>;
54
- }
55
- | null
56
- | undefined
57
- : unknown;
7
+ export type DefaultValue<Schema> = Schema extends string | number | boolean | Date | bigint | null | undefined ? Schema | string | null | undefined : Schema extends File ? null | undefined : Schema extends Array<infer Item> ? Array<DefaultValue<Item>> | null | undefined : Schema extends Record<string, any> ? {
8
+ [Key in keyof Schema]?: DefaultValue<Schema[Key]>;
9
+ } | null | undefined : string | null | undefined;
10
+ export type FormValue<Schema> = Schema extends string | number | boolean | Date | bigint | null | undefined ? string | undefined : Schema extends File ? File | undefined : Schema extends File[] ? File | Array<File> | undefined : Schema extends Array<infer Item> ? string | Array<FormValue<Item>> | undefined : Schema extends Record<string, any> ? {
11
+ [Key in keyof Schema]?: FormValue<Schema[Key]>;
12
+ } | undefined : unknown;
58
13
  declare const error: unique symbol;
59
14
  declare const field: unique symbol;
60
15
  declare const form: unique symbol;
61
- export type FormId<
62
- Schema extends Record<string, unknown> = Record<string, unknown>,
63
- Error = string[],
64
- > = string & {
65
- [error]?: Error;
66
- [form]?: Schema;
16
+ export type FormId<Schema extends Record<string, unknown> = Record<string, unknown>, Error = string[]> = string & {
17
+ [error]?: Error;
18
+ [form]?: Schema;
67
19
  };
68
- export type FieldName<
69
- FieldSchema,
70
- FormSchema extends Record<string, unknown> = Record<string, unknown>,
71
- Error = string[],
72
- > = string & {
73
- [field]?: FieldSchema;
74
- [error]?: Error;
75
- [form]?: FormSchema;
20
+ export type FieldName<FieldSchema, FormSchema extends Record<string, unknown> = Record<string, unknown>, Error = string[]> = string & {
21
+ [field]?: FieldSchema;
22
+ [error]?: Error;
23
+ [form]?: FormSchema;
76
24
  };
77
25
  export type Constraint = {
78
- required?: boolean;
79
- minLength?: number;
80
- maxLength?: number;
81
- min?: string | number;
82
- max?: string | number;
83
- step?: string | number;
84
- multiple?: boolean;
85
- pattern?: string;
26
+ required?: boolean;
27
+ minLength?: number;
28
+ maxLength?: number;
29
+ min?: string | number;
30
+ max?: string | number;
31
+ step?: string | number;
32
+ multiple?: boolean;
33
+ pattern?: string;
86
34
  };
87
35
  export type FormMeta<FormError> = {
88
- formId: string;
89
- isValueUpdated: boolean;
90
- submissionStatus?: 'error' | 'success';
91
- defaultValue: Record<string, unknown>;
92
- initialValue: Record<string, unknown>;
93
- value: Record<string, unknown>;
94
- error: Record<string, FormError>;
95
- constraint: Record<string, Constraint>;
96
- key: Record<string, string | undefined>;
97
- validated: Record<string, boolean>;
36
+ formId: string;
37
+ isValueUpdated: boolean;
38
+ submissionStatus?: 'error' | 'success';
39
+ defaultValue: Record<string, unknown>;
40
+ initialValue: Record<string, unknown>;
41
+ value: Record<string, unknown>;
42
+ error: Record<string, FormError>;
43
+ constraint: Record<string, Constraint>;
44
+ key: Record<string, string | undefined>;
45
+ validated: Record<string, boolean>;
98
46
  };
99
- export type FormState<FormError> = Omit<
100
- FormMeta<FormError>,
101
- 'formId' | 'isValueUpdated'
102
- > & {
103
- valid: Record<string, boolean>;
104
- dirty: Record<string, boolean>;
47
+ export type FormState<FormError> = Omit<FormMeta<FormError>, 'formId' | 'isValueUpdated'> & {
48
+ valid: Record<string, boolean>;
49
+ dirty: Record<string, boolean>;
105
50
  };
106
51
  export type FormOptions<Schema, FormError = string[], FormValue = Schema> = {
107
- /**
108
- * The id of the form.
109
- */
110
- formId: string;
111
- /**
112
- * An object representing the initial value of the form.
113
- */
114
- defaultValue?: DefaultValue<Schema>;
115
- /**
116
- * An object describing the constraint of each field
117
- */
118
- constraint?: Record<string, Constraint>;
119
- /**
120
- * An object describing the result of the last submission
121
- */
122
- lastResult?: SubmissionResult<FormError> | null | undefined;
123
- /**
124
- * Define when conform should start validation.
125
- * Support "onSubmit", "onInput", "onBlur".
126
- *
127
- * @default "onSubmit"
128
- */
129
- shouldValidate?: 'onSubmit' | 'onBlur' | 'onInput';
130
- /**
131
- * Define when conform should revalidate again.
132
- * Support "onSubmit", "onInput", "onBlur".
133
- *
134
- * @default Same as shouldValidate, or "onSubmit" if shouldValidate is not provided.
135
- */
136
- shouldRevalidate?: 'onSubmit' | 'onBlur' | 'onInput';
137
- /**
138
- * Define if conform should considered the field for dirty state.
139
- * e.g. Excluding form fields that are not managed by Conform, such as CSRF token
140
- */
141
- shouldDirtyConsider?: (name: string) => boolean;
142
- /**
143
- * A function to be called when the form should be (re)validated.
144
- */
145
- onValidate?: (context: {
146
- form: HTMLFormElement;
147
- submitter: HTMLInputElement | HTMLButtonElement | null;
148
- formData: FormData;
149
- }) => Submission<Schema, FormError, FormValue>;
52
+ /**
53
+ * The id of the form.
54
+ */
55
+ formId: string;
56
+ /**
57
+ * An object representing the initial value of the form.
58
+ */
59
+ defaultValue?: DefaultValue<Schema>;
60
+ /**
61
+ * An object describing the constraint of each field
62
+ */
63
+ constraint?: Record<string, Constraint>;
64
+ /**
65
+ * An object describing the result of the last submission
66
+ */
67
+ lastResult?: SubmissionResult<FormError> | null | undefined;
68
+ /**
69
+ * Define when conform should start validation.
70
+ * Support "onSubmit", "onInput", "onBlur".
71
+ *
72
+ * @default "onSubmit"
73
+ */
74
+ shouldValidate?: 'onSubmit' | 'onBlur' | 'onInput';
75
+ /**
76
+ * Define when conform should revalidate again.
77
+ * Support "onSubmit", "onInput", "onBlur".
78
+ *
79
+ * @default Same as shouldValidate, or "onSubmit" if shouldValidate is not provided.
80
+ */
81
+ shouldRevalidate?: 'onSubmit' | 'onBlur' | 'onInput';
82
+ /**
83
+ * Define if conform should considered the field for dirty state.
84
+ * e.g. Excluding form fields that are not managed by Conform, such as CSRF token
85
+ */
86
+ shouldDirtyConsider?: (name: string) => boolean;
87
+ /**
88
+ * A function to be called when the form should be (re)validated.
89
+ */
90
+ onValidate?: (context: {
91
+ form: HTMLFormElement;
92
+ submitter: HTMLInputElement | HTMLButtonElement | null;
93
+ formData: FormData;
94
+ }) => Submission<Schema, FormError, FormValue>;
150
95
  };
151
96
  export type SubscriptionSubject = {
152
- [key in
153
- | 'error'
154
- | 'initialValue'
155
- | 'value'
156
- | 'key'
157
- | 'valid'
158
- | 'dirty']?: SubscriptionScope;
97
+ [key in 'error' | 'initialValue' | 'value' | 'key' | 'valid' | 'dirty']?: SubscriptionScope;
159
98
  } & {
160
- formId?: boolean;
161
- status?: boolean;
99
+ formId?: boolean;
100
+ status?: boolean;
162
101
  };
163
102
  export type SubscriptionScope = {
164
- prefix?: string[];
165
- name?: string[];
103
+ prefix?: string[];
104
+ name?: string[];
166
105
  };
167
106
  export type ControlButtonProps = {
168
- name: string;
169
- value: string;
170
- form: string;
171
- formNoValidate: boolean;
107
+ name: string;
108
+ value: string;
109
+ form: string;
110
+ formNoValidate: boolean;
172
111
  };
173
- export type FormContext<
174
- Schema extends Record<string, any> = any,
175
- FormError = string[],
176
- FormValue = Schema,
177
- > = {
178
- getFormId(): string;
179
- submit(event: SubmitEvent): {
180
- formData: FormData;
181
- action: ReturnType<typeof getFormAction>;
182
- encType: ReturnType<typeof getFormEncType>;
183
- method: ReturnType<typeof getFormMethod>;
184
- submission?: Submission<Schema, FormError, FormValue>;
185
- };
186
- onReset(event: Event): void;
187
- onInput(event: Event): void;
188
- onBlur(event: Event): void;
189
- onUpdate(options: Partial<FormOptions<Schema, FormError, FormValue>>): void;
190
- observe(): () => void;
191
- subscribe(
192
- callback: () => void,
193
- getSubject?: () => SubscriptionSubject | undefined,
194
- ): () => void;
195
- getState(): FormState<FormError>;
196
- getSerializedState(): string;
112
+ export type FormContext<Schema extends Record<string, any> = any, FormError = string[], FormValue = Schema> = {
113
+ getFormId(): string;
114
+ submit(event: SubmitEvent): {
115
+ formData: FormData;
116
+ action: ReturnType<typeof getFormAction>;
117
+ encType: ReturnType<typeof getFormEncType>;
118
+ method: ReturnType<typeof getFormMethod>;
119
+ submission?: Submission<Schema, FormError, FormValue>;
120
+ };
121
+ onReset(event: Event): void;
122
+ onInput(event: Event): void;
123
+ onBlur(event: Event): void;
124
+ onUpdate(options: Partial<FormOptions<Schema, FormError, FormValue>>): void;
125
+ observe(): () => void;
126
+ subscribe(callback: () => void, getSubject?: () => SubscriptionSubject | undefined): () => void;
127
+ getState(): FormState<FormError>;
128
+ getSerializedState(): string;
197
129
  } & {
198
- [Type in Intent['type']]: {} extends Extract<
199
- Intent,
200
- {
201
- type: Type;
202
- }
203
- >['payload']
204
- ? (<FieldSchema = Schema>(
205
- payload?: Extract<
206
- Intent<FieldSchema>,
207
- {
208
- type: Type;
209
- }
210
- >['payload'],
211
- ) => void) & {
212
- getButtonProps<FieldSchema = Schema>(
213
- payload?: Extract<
214
- Intent<FieldSchema>,
215
- {
216
- type: Type;
217
- }
218
- >['payload'],
219
- ): ControlButtonProps;
220
- }
221
- : (<FieldSchema = Schema>(
222
- payload: Extract<
223
- Intent<FieldSchema>,
224
- {
225
- type: Type;
226
- }
227
- >['payload'],
228
- ) => void) & {
229
- getButtonProps<FieldSchema = Schema>(
230
- payload: Extract<
231
- Intent<FieldSchema>,
232
- {
233
- type: Type;
234
- }
235
- >['payload'],
236
- ): ControlButtonProps;
237
- };
130
+ [Type in Intent['type']]: {} extends Extract<Intent, {
131
+ type: Type;
132
+ }>['payload'] ? (<FieldSchema = Schema>(payload?: Extract<Intent<FieldSchema>, {
133
+ type: Type;
134
+ }>['payload']) => void) & {
135
+ getButtonProps<FieldSchema = Schema>(payload?: Extract<Intent<FieldSchema>, {
136
+ type: Type;
137
+ }>['payload']): ControlButtonProps;
138
+ } : (<FieldSchema = Schema>(payload: Extract<Intent<FieldSchema>, {
139
+ type: Type;
140
+ }>['payload']) => void) & {
141
+ getButtonProps<FieldSchema = Schema>(payload: Extract<Intent<FieldSchema>, {
142
+ type: Type;
143
+ }>['payload']): ControlButtonProps;
144
+ };
238
145
  };
239
- export declare function createFormContext<
240
- Schema extends Record<string, any>,
241
- FormError = string[],
242
- FormValue = Schema,
243
- >(
244
- options: FormOptions<Schema, FormError, FormValue>,
245
- ): FormContext<Schema, FormError, FormValue>;
146
+ export declare function createFormContext<Schema extends Record<string, any>, FormError = string[], FormValue = Schema>(options: FormOptions<Schema, FormError, FormValue>): FormContext<Schema, FormError, FormValue>;
246
147
  export {};
package/form.js CHANGED
@@ -22,9 +22,7 @@ function createFormMeta(options, initialized) {
22
22
  value: initialValue,
23
23
  constraint: (_options$constraint = options.constraint) !== null && _options$constraint !== void 0 ? _options$constraint : {},
24
24
  validated: (_lastResult$state$val = lastResult === null || lastResult === void 0 || (_lastResult$state = lastResult.state) === null || _lastResult$state === void 0 ? void 0 : _lastResult$state.validated) !== null && _lastResult$state$val !== void 0 ? _lastResult$state$val : {},
25
- key: !initialized ? getDefaultKey(defaultValue) : _rollupPluginBabelHelpers.objectSpread2({
26
- '': util.generateId()
27
- }, getDefaultKey(defaultValue)),
25
+ key: getDefaultKey(defaultValue),
28
26
  // The `lastResult` should comes from the server which we won't expect the error to be null
29
27
  // We can consider adding a warning if it happens
30
28
  error: (_ref = lastResult === null || lastResult === void 0 ? void 0 : lastResult.error) !== null && _ref !== void 0 ? _ref : {}
@@ -43,7 +41,9 @@ function getDefaultKey(defaultValue, prefix) {
43
41
  }
44
42
  }
45
43
  return result;
46
- }, {});
44
+ }, {
45
+ [prefix !== null && prefix !== void 0 ? prefix : '']: util.generateId()
46
+ });
47
47
  }
48
48
  function setFieldsValidated(meta, fields) {
49
49
  for (var _name of Object.keys(meta.error).concat(fields !== null && fields !== void 0 ? fields : [])) {
@@ -147,9 +147,7 @@ function updateValue(meta, name, value) {
147
147
  if (name === '') {
148
148
  meta.initialValue = value;
149
149
  meta.value = value;
150
- meta.key = _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, getDefaultKey(value)), {}, {
151
- '': util.generateId()
152
- });
150
+ meta.key = getDefaultKey(value);
153
151
  return;
154
152
  }
155
153
  meta.initialValue = util.clone(meta.initialValue);
package/form.mjs CHANGED
@@ -18,9 +18,7 @@ function createFormMeta(options, initialized) {
18
18
  value: initialValue,
19
19
  constraint: (_options$constraint = options.constraint) !== null && _options$constraint !== void 0 ? _options$constraint : {},
20
20
  validated: (_lastResult$state$val = lastResult === null || lastResult === void 0 || (_lastResult$state = lastResult.state) === null || _lastResult$state === void 0 ? void 0 : _lastResult$state.validated) !== null && _lastResult$state$val !== void 0 ? _lastResult$state$val : {},
21
- key: !initialized ? getDefaultKey(defaultValue) : _objectSpread2({
22
- '': generateId()
23
- }, getDefaultKey(defaultValue)),
21
+ key: getDefaultKey(defaultValue),
24
22
  // The `lastResult` should comes from the server which we won't expect the error to be null
25
23
  // We can consider adding a warning if it happens
26
24
  error: (_ref = lastResult === null || lastResult === void 0 ? void 0 : lastResult.error) !== null && _ref !== void 0 ? _ref : {}
@@ -39,7 +37,9 @@ function getDefaultKey(defaultValue, prefix) {
39
37
  }
40
38
  }
41
39
  return result;
42
- }, {});
40
+ }, {
41
+ [prefix !== null && prefix !== void 0 ? prefix : '']: generateId()
42
+ });
43
43
  }
44
44
  function setFieldsValidated(meta, fields) {
45
45
  for (var _name of Object.keys(meta.error).concat(fields !== null && fields !== void 0 ? fields : [])) {
@@ -143,9 +143,7 @@ function updateValue(meta, name, value) {
143
143
  if (name === '') {
144
144
  meta.initialValue = value;
145
145
  meta.value = value;
146
- meta.key = _objectSpread2(_objectSpread2({}, getDefaultKey(value)), {}, {
147
- '': generateId()
148
- });
146
+ meta.key = getDefaultKey(value);
149
147
  return;
150
148
  }
151
149
  meta.initialValue = clone(meta.initialValue);
package/index.d.ts CHANGED
@@ -1,26 +1,4 @@
1
- export {
2
- type Combine,
3
- type Constraint,
4
- type ControlButtonProps,
5
- type FormId,
6
- type FieldName,
7
- type DefaultValue,
8
- type FormValue,
9
- type FormOptions,
10
- type FormState,
11
- type FormContext,
12
- type SubscriptionSubject,
13
- type SubscriptionScope,
14
- createFormContext as unstable_createFormContext,
15
- } from './form';
1
+ export { type Combine, type Constraint, type ControlButtonProps, type FormId, type FieldName, type DefaultValue, type FormValue, type FormOptions, type FormState, type FormContext, type SubscriptionSubject, type SubscriptionScope, createFormContext as unstable_createFormContext, } from './form';
16
2
  export { type FieldElement, isFieldElement } from './dom';
17
- export {
18
- type Submission,
19
- type SubmissionResult,
20
- type Intent,
21
- INTENT,
22
- STATE,
23
- serializeIntent,
24
- parse,
25
- } from './submission';
3
+ export { type Submission, type SubmissionResult, type Intent, INTENT, STATE, serializeIntent, parse, } from './submission';
26
4
  export { getPaths, formatPaths, isPrefix } from './formdata';
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "A set of opinionated helpers built on top of the Constraint Validation API",
4
4
  "homepage": "https://conform.guide",
5
5
  "license": "MIT",
6
- "version": "1.1.5",
6
+ "version": "1.2.1",
7
7
  "main": "index.js",
8
8
  "module": "index.mjs",
9
9
  "types": "index.d.ts",
package/submission.d.ts CHANGED
@@ -2,9 +2,12 @@ import type { DefaultValue, FieldName, FormValue } from './form';
2
2
  export type SubmissionState = {
3
3
  validated: Record<string, boolean>;
4
4
  };
5
+ export type SubmissionPayload<Entry extends FormDataEntryValue> = Entry | SubmissionPayload<Entry>[] | {
6
+ [key: string]: SubmissionPayload<Entry>;
7
+ };
5
8
  export type SubmissionContext<Value = null, FormError = string[]> = {
6
9
  intent: Intent | null;
7
- payload: Record<string, unknown>;
10
+ payload: Record<string, SubmissionPayload<FormDataEntryValue>>;
8
11
  fields: Set<string>;
9
12
  value?: Value;
10
13
  error?: Record<string, FormError | null> | null;
@@ -12,19 +15,19 @@ export type SubmissionContext<Value = null, FormError = string[]> = {
12
15
  };
13
16
  export type Submission<Schema, FormError = string[], FormValue = Schema> = {
14
17
  status: 'success';
15
- payload: Record<string, unknown>;
18
+ payload: Record<string, SubmissionPayload<FormDataEntryValue>>;
16
19
  value: FormValue;
17
20
  reply(options?: ReplyOptions<FormError>): SubmissionResult<FormError>;
18
21
  } | {
19
22
  status: 'error' | undefined;
20
- payload: Record<string, unknown>;
23
+ payload: Record<string, SubmissionPayload<FormDataEntryValue>>;
21
24
  error: Record<string, FormError | null> | null;
22
25
  reply(options?: ReplyOptions<FormError>): SubmissionResult<FormError>;
23
26
  };
24
27
  export type SubmissionResult<FormError = string[]> = {
25
28
  status?: 'error' | 'success';
26
29
  intent?: Intent;
27
- initialValue?: Record<string, unknown> | null;
30
+ initialValue?: Record<string, SubmissionPayload<string>> | null;
28
31
  fields?: string[];
29
32
  error?: Record<string, FormError | null>;
30
33
  state?: SubmissionState;
package/submission.js CHANGED
@@ -115,7 +115,7 @@ function createSubmission(context) {
115
115
  };
116
116
  }
117
117
  function replySubmission(context) {
118
- var _context$intent, _context$intent$paylo, _options$formErrors, _normalize;
118
+ var _context$intent, _context$intent$paylo, _options$formErrors, _ref;
119
119
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
120
120
  if ('resetForm' in options && options.resetForm || ((_context$intent = context.intent) === null || _context$intent === void 0 ? void 0 : _context$intent.type) === 'reset' && ((_context$intent$paylo = context.intent.payload.name) !== null && _context$intent$paylo !== void 0 ? _context$intent$paylo : '') === '') {
121
121
  return {
@@ -134,12 +134,17 @@ function replySubmission(context) {
134
134
  '': (_options$formErrors = options.formErrors) !== null && _options$formErrors !== void 0 ? _options$formErrors : null
135
135
  }, options.fieldErrors)) : null;
136
136
  var error = context.error || extraError ? _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, context.error), extraError) : undefined;
137
+ var initialValue = (_ref = formdata.normalize(context.payload,
138
+ // We can't serialize the file and send it back from the server, but we can preserve it in the client
139
+ typeof document !== 'undefined'
140
+ // We need the file on the client because it's treated as the form value
141
+ // But we will exclude the File type for now as it's only used by the internal
142
+ // form state and we will remove the need to preserve the file on the client soon
143
+ )) !== null && _ref !== void 0 ? _ref : {};
137
144
  return {
138
145
  status: context.intent ? undefined : error ? 'error' : 'success',
139
146
  intent: context.intent ? context.intent : undefined,
140
- initialValue: (_normalize = formdata.normalize(context.payload,
141
- // We can't serialize the file and send it back from the server, but we can preserve it in the client
142
- typeof document !== 'undefined')) !== null && _normalize !== void 0 ? _normalize : {},
147
+ initialValue,
143
148
  error,
144
149
  state: context.state,
145
150
  fields: Array.from(context.fields)
@@ -209,9 +214,9 @@ function setState(state, name, valueFn) {
209
214
  var keys = Object.keys(state).sort((prev, next) => next.localeCompare(prev));
210
215
  var target = {};
211
216
  var _loop2 = function _loop2() {
212
- var value = state[key];
213
- if (formdata.isPrefix(key, name) && key !== name) {
214
- formdata.setValue(target, key, currentValue => {
217
+ var value = state[_key];
218
+ if (formdata.isPrefix(_key, name) && _key !== name) {
219
+ formdata.setValue(target, _key, currentValue => {
215
220
  if (typeof currentValue === 'undefined') {
216
221
  return value;
217
222
  }
@@ -225,10 +230,10 @@ function setState(state, name, valueFn) {
225
230
  });
226
231
 
227
232
  // Remove the value from the data
228
- delete state[key];
233
+ delete state[_key];
229
234
  }
230
235
  };
231
- for (var key of keys) {
236
+ for (var _key of keys) {
232
237
  _loop2();
233
238
  }
234
239
  var result = valueFn(formdata.getValue(target, name));
@@ -266,8 +271,8 @@ function setListState(state, intent, getDefaultValue) {
266
271
  function serialize(defaultValue) {
267
272
  if (formdata.isPlainObject(defaultValue)) {
268
273
  // @ts-expect-error FIXME
269
- return Object.entries(defaultValue).reduce((result, _ref) => {
270
- var [key, value] = _ref;
274
+ return Object.entries(defaultValue).reduce((result, _ref2) => {
275
+ var [key, value] = _ref2;
271
276
  result[key] = serialize(value);
272
277
  return result;
273
278
  }, {});
package/submission.mjs CHANGED
@@ -111,7 +111,7 @@ function createSubmission(context) {
111
111
  };
112
112
  }
113
113
  function replySubmission(context) {
114
- var _context$intent, _context$intent$paylo, _options$formErrors, _normalize;
114
+ var _context$intent, _context$intent$paylo, _options$formErrors, _ref;
115
115
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
116
116
  if ('resetForm' in options && options.resetForm || ((_context$intent = context.intent) === null || _context$intent === void 0 ? void 0 : _context$intent.type) === 'reset' && ((_context$intent$paylo = context.intent.payload.name) !== null && _context$intent$paylo !== void 0 ? _context$intent$paylo : '') === '') {
117
117
  return {
@@ -130,12 +130,17 @@ function replySubmission(context) {
130
130
  '': (_options$formErrors = options.formErrors) !== null && _options$formErrors !== void 0 ? _options$formErrors : null
131
131
  }, options.fieldErrors)) : null;
132
132
  var error = context.error || extraError ? _objectSpread2(_objectSpread2({}, context.error), extraError) : undefined;
133
+ var initialValue = (_ref = normalize(context.payload,
134
+ // We can't serialize the file and send it back from the server, but we can preserve it in the client
135
+ typeof document !== 'undefined'
136
+ // We need the file on the client because it's treated as the form value
137
+ // But we will exclude the File type for now as it's only used by the internal
138
+ // form state and we will remove the need to preserve the file on the client soon
139
+ )) !== null && _ref !== void 0 ? _ref : {};
133
140
  return {
134
141
  status: context.intent ? undefined : error ? 'error' : 'success',
135
142
  intent: context.intent ? context.intent : undefined,
136
- initialValue: (_normalize = normalize(context.payload,
137
- // We can't serialize the file and send it back from the server, but we can preserve it in the client
138
- typeof document !== 'undefined')) !== null && _normalize !== void 0 ? _normalize : {},
143
+ initialValue,
139
144
  error,
140
145
  state: context.state,
141
146
  fields: Array.from(context.fields)
@@ -205,9 +210,9 @@ function setState(state, name, valueFn) {
205
210
  var keys = Object.keys(state).sort((prev, next) => next.localeCompare(prev));
206
211
  var target = {};
207
212
  var _loop2 = function _loop2() {
208
- var value = state[key];
209
- if (isPrefix(key, name) && key !== name) {
210
- setValue(target, key, currentValue => {
213
+ var value = state[_key];
214
+ if (isPrefix(_key, name) && _key !== name) {
215
+ setValue(target, _key, currentValue => {
211
216
  if (typeof currentValue === 'undefined') {
212
217
  return value;
213
218
  }
@@ -221,10 +226,10 @@ function setState(state, name, valueFn) {
221
226
  });
222
227
 
223
228
  // Remove the value from the data
224
- delete state[key];
229
+ delete state[_key];
225
230
  }
226
231
  };
227
- for (var key of keys) {
232
+ for (var _key of keys) {
228
233
  _loop2();
229
234
  }
230
235
  var result = valueFn(getValue(target, name));
@@ -262,8 +267,8 @@ function setListState(state, intent, getDefaultValue) {
262
267
  function serialize(defaultValue) {
263
268
  if (isPlainObject(defaultValue)) {
264
269
  // @ts-expect-error FIXME
265
- return Object.entries(defaultValue).reduce((result, _ref) => {
266
- var [key, value] = _ref;
270
+ return Object.entries(defaultValue).reduce((result, _ref2) => {
271
+ var [key, value] = _ref2;
267
272
  result[key] = serialize(value);
268
273
  return result;
269
274
  }, {});
package/util.d.ts CHANGED
@@ -1,6 +1,3 @@
1
- export declare function invariant(
2
- expectedCondition: boolean,
3
- message: string,
4
- ): asserts expectedCondition;
1
+ export declare function invariant(expectedCondition: boolean, message: string): asserts expectedCondition;
5
2
  export declare function generateId(): string;
6
3
  export declare function clone<Data>(data: Data): Data;
package/README DELETED
@@ -1,37 +0,0 @@
1
-
2
-
3
- ███████╗ ██████╗ ███╗ ██╗ ████████╗ ██████╗ ███████╗ ███╗ ███╗
4
- ██╔═════╝ ██╔═══██╗ ████╗ ██║ ██╔═════╝ ██╔═══██╗ ██╔═══██╗ ████████║
5
- ██║ ██║ ██║ ██╔██╗██║ ███████╗ ██║ ██║ ███████╔╝ ██╔██╔██║
6
- ██║ ██║ ██║ ██║╚████║ ██╔════╝ ██║ ██║ ██╔═══██╗ ██║╚═╝██║
7
- ╚███████╗ ╚██████╔╝ ██║ ╚███║ ██║ ╚██████╔╝ ██║ ██║ ██║ ██║
8
- ╚══════╝ ╚═════╝ ╚═╝ ╚══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
9
-
10
-
11
- Version 1.1.3 / License MIT / Copyright (c) 2024 Edmund Hung
12
-
13
- A type-safe form validation library utilizing web fundamentals to progressively enhance HTML Forms with full support for server frameworks like Remix and Next.js.
14
-
15
- # Getting Started
16
-
17
- Check out the overview and tutorial at our website https://conform.guide
18
-
19
- # Features
20
-
21
- - Progressive enhancement first APIs
22
- - Type-safe field inference
23
- - Fine-grained subscription
24
- - Built-in accessibility helpers
25
- - Automatic type coercion with Zod
26
-
27
- # Documentation
28
-
29
- - Validation: https://conform.guide/validation
30
- - Nested object and Array: https://conform.guide/complex-structures
31
- - UI Integrations: https://conform.guide/integration/ui-libraries
32
- - Intent button: https://conform.guide/intent-button
33
- - Accessibility Guide: https://conform.guide/accessibility
34
-
35
- # Support
36
-
37
- To report a bug, please open an issue on the repository at https://github.com/edmundhung/conform. For feature requests and questions, you can post them in the Discussions section.
package/intent.d.ts DELETED
@@ -1,114 +0,0 @@
1
- import { type Pretty } from './types.js';
2
- export interface IntentButtonProps {
3
- name: typeof INTENT;
4
- value: string;
5
- formNoValidate?: boolean;
6
- }
7
- export type ListIntentPayload<Schema = unknown> =
8
- | {
9
- name: string;
10
- operation: 'insert';
11
- defaultValue?: Schema;
12
- index?: number;
13
- }
14
- | {
15
- name: string;
16
- operation: 'prepend';
17
- defaultValue?: Schema;
18
- }
19
- | {
20
- name: string;
21
- operation: 'append';
22
- defaultValue?: Schema;
23
- }
24
- | {
25
- name: string;
26
- operation: 'replace';
27
- defaultValue: Schema;
28
- index: number;
29
- }
30
- | {
31
- name: string;
32
- operation: 'remove';
33
- index: number;
34
- }
35
- | {
36
- name: string;
37
- operation: 'reorder';
38
- from: number;
39
- to: number;
40
- };
41
- type ExtractListIntentPayload<Operation, Schema = unknown> = Pretty<
42
- Omit<
43
- Extract<
44
- ListIntentPayload<Schema>,
45
- {
46
- operation: Operation;
47
- }
48
- >,
49
- 'name' | 'operation'
50
- >
51
- >;
52
- type ListIntent<Operation> =
53
- {} extends ExtractListIntentPayload<Operation>
54
- ? <Schema>(
55
- name: string,
56
- payload?: ExtractListIntentPayload<Operation, Schema>,
57
- ) => IntentButtonProps
58
- : <Schema>(
59
- name: string,
60
- payload: ExtractListIntentPayload<Operation, Schema>,
61
- ) => IntentButtonProps;
62
- /**
63
- * Helpers to configure an intent button for modifying a list
64
- *
65
- * @see https://conform.guide/api/react#list
66
- */
67
- export declare const list: {
68
- /**
69
- * @deprecated You can use `insert` without specifying an index instead
70
- */
71
- append: ListIntent<'append'>;
72
- /**
73
- * @deprecated You can use `insert` with zero index instead
74
- */
75
- prepend: ListIntent<'prepend'>;
76
- insert: ListIntent<'insert'>;
77
- replace: ListIntent<'replace'>;
78
- remove: ListIntent<'remove'>;
79
- reorder: ListIntent<'reorder'>;
80
- };
81
- export declare const INTENT = '__intent__';
82
- /**
83
- * Returns the intent from the form data or search params.
84
- * It throws an error if multiple intent is set.
85
- */
86
- export declare function getIntent(payload: FormData | URLSearchParams): string;
87
- /**
88
- * Returns the properties required to configure an intent button for validation
89
- *
90
- * @see https://conform.guide/api/react#validate
91
- */
92
- export declare function validate(field: string): IntentButtonProps;
93
- export declare function requestIntent(
94
- form: HTMLFormElement | null | undefined,
95
- buttonProps: {
96
- value: string;
97
- formNoValidate?: boolean;
98
- },
99
- ): void;
100
- export declare function parseIntent<Schema>(intent: string):
101
- | {
102
- type: 'validate';
103
- payload: string;
104
- }
105
- | {
106
- type: 'list';
107
- payload: ListIntentPayload<Schema>;
108
- }
109
- | null;
110
- export declare function updateList<Schema>(
111
- list: Array<Schema>,
112
- payload: ListIntentPayload<Schema>,
113
- ): Array<Schema>;
114
- export {};
package/intent.js DELETED
@@ -1,136 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js');
6
- var dom = require('./dom.js');
7
-
8
- /**
9
- * Helpers to configure an intent button for modifying a list
10
- *
11
- * @see https://conform.guide/api/react#list
12
- */
13
- var list = new Proxy({}, {
14
- get(_target, operation) {
15
- return function (name) {
16
- var payload = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
17
- return {
18
- name: INTENT,
19
- value: "list/".concat(JSON.stringify(_rollupPluginBabelHelpers.objectSpread2({
20
- name,
21
- operation
22
- }, payload))),
23
- formNoValidate: true
24
- };
25
- };
26
- }
27
- });
28
- var INTENT = '__intent__';
29
-
30
- /**
31
- * Returns the intent from the form data or search params.
32
- * It throws an error if multiple intent is set.
33
- */
34
- function getIntent(payload) {
35
- if (!payload.has(INTENT)) {
36
- return 'submit';
37
- }
38
- var [intent, secondIntent, ...rest] = payload.getAll(INTENT);
39
-
40
- // The submitter value is included in the formData directly on Safari 15.6.
41
- // This causes the intent to be duplicated in the payload.
42
- // We will ignore the second intent if it is the same as the first one.
43
- if (typeof intent !== 'string' || secondIntent && intent !== secondIntent || rest.length > 0) {
44
- throw new Error('The intent could only be set on a button');
45
- }
46
- return intent;
47
- }
48
-
49
- /**
50
- * Returns the properties required to configure an intent button for validation
51
- *
52
- * @see https://conform.guide/api/react#validate
53
- */
54
- function validate(field) {
55
- return {
56
- name: INTENT,
57
- value: "validate/".concat(field),
58
- formNoValidate: true
59
- };
60
- }
61
- function requestIntent(form, buttonProps) {
62
- if (!form) {
63
- // eslint-disable-next-line no-console
64
- console.warn('No form element is provided');
65
- return;
66
- }
67
- var submitter = dom.createSubmitter({
68
- name: INTENT,
69
- value: buttonProps.value,
70
- hidden: true,
71
- formNoValidate: buttonProps.formNoValidate
72
- });
73
- dom.requestSubmit(form, submitter);
74
- }
75
- function parseIntent(intent) {
76
- var seperatorIndex = intent.indexOf('/');
77
- if (seperatorIndex > -1) {
78
- var type = intent.slice(0, seperatorIndex);
79
- var _payload = intent.slice(seperatorIndex + 1);
80
- if (typeof _payload !== 'undefined') {
81
- try {
82
- switch (type) {
83
- case 'validate':
84
- return {
85
- type,
86
- payload: _payload
87
- };
88
- case 'list':
89
- return {
90
- type,
91
- payload: JSON.parse(_payload)
92
- };
93
- }
94
- } catch (error) {
95
- throw new Error("Failed parsing intent: ".concat(intent), {
96
- cause: error
97
- });
98
- }
99
- }
100
- }
101
- return null;
102
- }
103
- function updateList(list, payload) {
104
- var _payload$index;
105
- switch (payload.operation) {
106
- case 'prepend':
107
- list.unshift(payload.defaultValue);
108
- break;
109
- case 'append':
110
- list.push(payload.defaultValue);
111
- break;
112
- case 'insert':
113
- list.splice((_payload$index = payload.index) !== null && _payload$index !== void 0 ? _payload$index : list.length, 0, payload.defaultValue);
114
- break;
115
- case 'replace':
116
- list.splice(payload.index, 1, payload.defaultValue);
117
- break;
118
- case 'remove':
119
- list.splice(payload.index, 1);
120
- break;
121
- case 'reorder':
122
- list.splice(payload.to, 0, ...list.splice(payload.from, 1));
123
- break;
124
- default:
125
- throw new Error('Unknown list intent received');
126
- }
127
- return list;
128
- }
129
-
130
- exports.INTENT = INTENT;
131
- exports.getIntent = getIntent;
132
- exports.list = list;
133
- exports.parseIntent = parseIntent;
134
- exports.requestIntent = requestIntent;
135
- exports.updateList = updateList;
136
- exports.validate = validate;
package/intent.mjs DELETED
@@ -1,126 +0,0 @@
1
- import { objectSpread2 as _objectSpread2 } from './_virtual/_rollupPluginBabelHelpers.mjs';
2
- import { createSubmitter, requestSubmit } from './dom.mjs';
3
-
4
- /**
5
- * Helpers to configure an intent button for modifying a list
6
- *
7
- * @see https://conform.guide/api/react#list
8
- */
9
- var list = new Proxy({}, {
10
- get(_target, operation) {
11
- return function (name) {
12
- var payload = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
13
- return {
14
- name: INTENT,
15
- value: "list/".concat(JSON.stringify(_objectSpread2({
16
- name,
17
- operation
18
- }, payload))),
19
- formNoValidate: true
20
- };
21
- };
22
- }
23
- });
24
- var INTENT = '__intent__';
25
-
26
- /**
27
- * Returns the intent from the form data or search params.
28
- * It throws an error if multiple intent is set.
29
- */
30
- function getIntent(payload) {
31
- if (!payload.has(INTENT)) {
32
- return 'submit';
33
- }
34
- var [intent, secondIntent, ...rest] = payload.getAll(INTENT);
35
-
36
- // The submitter value is included in the formData directly on Safari 15.6.
37
- // This causes the intent to be duplicated in the payload.
38
- // We will ignore the second intent if it is the same as the first one.
39
- if (typeof intent !== 'string' || secondIntent && intent !== secondIntent || rest.length > 0) {
40
- throw new Error('The intent could only be set on a button');
41
- }
42
- return intent;
43
- }
44
-
45
- /**
46
- * Returns the properties required to configure an intent button for validation
47
- *
48
- * @see https://conform.guide/api/react#validate
49
- */
50
- function validate(field) {
51
- return {
52
- name: INTENT,
53
- value: "validate/".concat(field),
54
- formNoValidate: true
55
- };
56
- }
57
- function requestIntent(form, buttonProps) {
58
- if (!form) {
59
- // eslint-disable-next-line no-console
60
- console.warn('No form element is provided');
61
- return;
62
- }
63
- var submitter = createSubmitter({
64
- name: INTENT,
65
- value: buttonProps.value,
66
- hidden: true,
67
- formNoValidate: buttonProps.formNoValidate
68
- });
69
- requestSubmit(form, submitter);
70
- }
71
- function parseIntent(intent) {
72
- var seperatorIndex = intent.indexOf('/');
73
- if (seperatorIndex > -1) {
74
- var type = intent.slice(0, seperatorIndex);
75
- var _payload = intent.slice(seperatorIndex + 1);
76
- if (typeof _payload !== 'undefined') {
77
- try {
78
- switch (type) {
79
- case 'validate':
80
- return {
81
- type,
82
- payload: _payload
83
- };
84
- case 'list':
85
- return {
86
- type,
87
- payload: JSON.parse(_payload)
88
- };
89
- }
90
- } catch (error) {
91
- throw new Error("Failed parsing intent: ".concat(intent), {
92
- cause: error
93
- });
94
- }
95
- }
96
- }
97
- return null;
98
- }
99
- function updateList(list, payload) {
100
- var _payload$index;
101
- switch (payload.operation) {
102
- case 'prepend':
103
- list.unshift(payload.defaultValue);
104
- break;
105
- case 'append':
106
- list.push(payload.defaultValue);
107
- break;
108
- case 'insert':
109
- list.splice((_payload$index = payload.index) !== null && _payload$index !== void 0 ? _payload$index : list.length, 0, payload.defaultValue);
110
- break;
111
- case 'replace':
112
- list.splice(payload.index, 1, payload.defaultValue);
113
- break;
114
- case 'remove':
115
- list.splice(payload.index, 1);
116
- break;
117
- case 'reorder':
118
- list.splice(payload.to, 0, ...list.splice(payload.from, 1));
119
- break;
120
- default:
121
- throw new Error('Unknown list intent received');
122
- }
123
- return list;
124
- }
125
-
126
- export { INTENT, getIntent, list, parseIntent, requestIntent, updateList, validate };
package/parse.d.ts DELETED
@@ -1,50 +0,0 @@
1
- export type Submission<Schema = any> = {
2
- intent: string;
3
- payload: Record<string, unknown>;
4
- error: Record<string, string[]>;
5
- value?: Schema | null;
6
- };
7
- export declare const VALIDATION_UNDEFINED = '__undefined__';
8
- export declare const VALIDATION_SKIPPED = '__skipped__';
9
- export declare function parse(payload: FormData | URLSearchParams): Submission;
10
- export declare function parse<Schema>(
11
- payload: FormData | URLSearchParams,
12
- options?: {
13
- resolve?: (
14
- payload: Record<string, any>,
15
- intent: string,
16
- ) => {
17
- value?: Schema;
18
- error?: Record<string, string[]>;
19
- };
20
- },
21
- ): Submission<Schema>;
22
- export declare function parse<Schema>(
23
- payload: FormData | URLSearchParams,
24
- options?: {
25
- resolve?: (
26
- payload: Record<string, any>,
27
- intent: string,
28
- ) => Promise<{
29
- value?: Schema;
30
- error?: Record<string, string[]>;
31
- }>;
32
- },
33
- ): Promise<Submission<Schema>>;
34
- export declare function parse<Schema>(
35
- payload: FormData | URLSearchParams,
36
- options?: {
37
- resolve?: (
38
- payload: Record<string, any>,
39
- intent: string,
40
- ) =>
41
- | {
42
- value?: Schema;
43
- error?: Record<string, string[]>;
44
- }
45
- | Promise<{
46
- value?: Schema;
47
- error?: Record<string, string[]>;
48
- }>;
49
- },
50
- ): Submission<Schema> | Promise<Submission<Schema>>;
package/parse.js DELETED
@@ -1,43 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var _rollupPluginBabelHelpers = require('./_virtual/_rollupPluginBabelHelpers.js');
6
- var formdata = require('./formdata.js');
7
- var intent = require('./intent.js');
8
-
9
- var VALIDATION_UNDEFINED = '__undefined__';
10
- var VALIDATION_SKIPPED = '__skipped__';
11
- function parse(payload, options) {
12
- var submission = {
13
- intent: intent.getIntent(payload),
14
- payload: formdata.resolve(payload, {
15
- ignoreKeys: [intent.INTENT]
16
- }),
17
- error: {}
18
- };
19
- var intent$1 = intent.parseIntent(submission.intent);
20
- if (intent$1 && intent$1.type === 'list') {
21
- formdata.setValue(submission.payload, intent$1.payload.name, list => {
22
- if (typeof list !== 'undefined' && !Array.isArray(list)) {
23
- throw new Error('The list intent can only be applied to a list');
24
- }
25
- return intent.updateList(list !== null && list !== void 0 ? list : [], intent$1.payload);
26
- });
27
- }
28
- if (typeof (options === null || options === void 0 ? void 0 : options.resolve) === 'undefined') {
29
- return submission;
30
- }
31
- var result = options.resolve(submission.payload, submission.intent);
32
- var mergeResolveResult = resolved => {
33
- return _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, submission), resolved);
34
- };
35
- if (result instanceof Promise) {
36
- return result.then(mergeResolveResult);
37
- }
38
- return mergeResolveResult(result);
39
- }
40
-
41
- exports.VALIDATION_SKIPPED = VALIDATION_SKIPPED;
42
- exports.VALIDATION_UNDEFINED = VALIDATION_UNDEFINED;
43
- exports.parse = parse;
package/parse.mjs DELETED
@@ -1,37 +0,0 @@
1
- import { objectSpread2 as _objectSpread2 } from './_virtual/_rollupPluginBabelHelpers.mjs';
2
- import { resolve, setValue } from './formdata.mjs';
3
- import { getIntent, parseIntent, updateList, INTENT } from './intent.mjs';
4
-
5
- var VALIDATION_UNDEFINED = '__undefined__';
6
- var VALIDATION_SKIPPED = '__skipped__';
7
- function parse(payload, options) {
8
- var submission = {
9
- intent: getIntent(payload),
10
- payload: resolve(payload, {
11
- ignoreKeys: [INTENT]
12
- }),
13
- error: {}
14
- };
15
- var intent = parseIntent(submission.intent);
16
- if (intent && intent.type === 'list') {
17
- setValue(submission.payload, intent.payload.name, list => {
18
- if (typeof list !== 'undefined' && !Array.isArray(list)) {
19
- throw new Error('The list intent can only be applied to a list');
20
- }
21
- return updateList(list !== null && list !== void 0 ? list : [], intent.payload);
22
- });
23
- }
24
- if (typeof (options === null || options === void 0 ? void 0 : options.resolve) === 'undefined') {
25
- return submission;
26
- }
27
- var result = options.resolve(submission.payload, submission.intent);
28
- var mergeResolveResult = resolved => {
29
- return _objectSpread2(_objectSpread2({}, submission), resolved);
30
- };
31
- if (result instanceof Promise) {
32
- return result.then(mergeResolveResult);
33
- }
34
- return mergeResolveResult(result);
35
- }
36
-
37
- export { VALIDATION_SKIPPED, VALIDATION_UNDEFINED, parse };
package/types.d.ts DELETED
@@ -1,23 +0,0 @@
1
- export type Pretty<T> = {
2
- [K in keyof T]: T[K];
3
- } & {};
4
- export type FieldConstraint<Schema = any> = {
5
- required?: boolean;
6
- minLength?: number;
7
- maxLength?: number;
8
- min?: Schema extends number ? number : string | number;
9
- max?: Schema extends number ? number : string | number;
10
- step?: Schema extends number ? number : string | number;
11
- multiple?: boolean;
12
- pattern?: string;
13
- };
14
- export type KeysOf<T> = T extends any ? keyof T : never;
15
- export type ResolveType<T, K extends KeysOf<T>> = T extends {
16
- [k in K]?: any;
17
- }
18
- ? T[K]
19
- : undefined;
20
- export type FieldsetConstraint<Schema extends Record<string, any> | undefined> =
21
- {
22
- [Key in KeysOf<Schema>]?: FieldConstraint<ResolveType<Schema, Key>>;
23
- };