@k8ordo/form 2.3.1 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -3
- package/dist/async-check.d.mts +2 -1
- package/dist/derive/attributes.mjs +14 -15
- package/dist/derive/form-fields.d.mts +8 -9
- package/dist/derive/form-fields.mjs +76 -21
- package/dist/derive/messages.d.mts +2 -2
- package/dist/derive/messages.mjs +2 -2
- package/dist/index.d.mts +5 -3
- package/dist/index.mjs +1 -1
- package/dist/parse/parse-form.d.mts +2 -2
- package/dist/parse/parse-form.mjs +9 -9
- package/dist/paths.d.mts +36 -21
- package/dist/rules/define-form.d.mts +1 -1
- package/dist/rules/rules.d.mts +15 -10
- package/dist/rules/rules.mjs +2 -9
- package/dist/schema/object-schema.d.mts +2 -24
- package/dist/schema/object-schema.mjs +1 -3
- package/dist/schema/walk.d.mts +5 -2
- package/dist/schema/walk.mjs +34 -22
- package/dist/server.d.mts +5 -4
- package/dist/server.mjs +3 -3
- package/dist/types.d.mts +88 -15
- package/dist/use-form.d.mts +33 -13
- package/dist/use-form.mjs +7 -5
- package/docs/GUIDE.md +261 -93
- package/docs/llms.txt +26 -9
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -54,10 +54,9 @@ export const talkSchema = z.object({
|
|
|
54
54
|
// src/routes/talks/new/page.tsx — Server Component
|
|
55
55
|
import { formFields } from '@k8ordo/form/server';
|
|
56
56
|
|
|
57
|
-
const talkFields = formFields(talkSchema); // derived once, plain data
|
|
58
|
-
|
|
59
57
|
export default function Page() {
|
|
60
|
-
|
|
58
|
+
// derived in the render, so its messages follow the request; plain data
|
|
59
|
+
return <TalkForm action={createTalk} fields={formFields(talkSchema)} />;
|
|
61
60
|
}
|
|
62
61
|
```
|
|
63
62
|
|
|
@@ -65,6 +64,14 @@ export default function Page() {
|
|
|
65
64
|
// src/components/talk-form.tsx
|
|
66
65
|
'use client';
|
|
67
66
|
import { useForm } from '@k8ordo/form';
|
|
67
|
+
import type { FormFields, FormState } from '@k8ordo/form';
|
|
68
|
+
|
|
69
|
+
import type { talkSchema } from '../lib/schema'; // type-only: zod stays out
|
|
70
|
+
|
|
71
|
+
type TalkFormProps = {
|
|
72
|
+
action: (state: FormState, formData: FormData) => Promise<FormState>;
|
|
73
|
+
fields: FormFields<typeof talkSchema>; // what formFields(talkSchema) returns
|
|
74
|
+
};
|
|
68
75
|
|
|
69
76
|
export const TalkForm = ({ action, fields }: TalkFormProps) => {
|
|
70
77
|
const [state, formAction] = useActionState(action, {});
|
package/dist/async-check.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ObjectSchema } from "./schema/object-schema.mjs";
|
|
1
2
|
import { UseFormReturn } from "./use-form.mjs";
|
|
2
3
|
/**
|
|
3
4
|
* Ask the server about one field while the person is still filling the form.
|
|
@@ -17,4 +18,4 @@ export type AsyncCheck = {
|
|
|
17
18
|
/** True while an answer is outstanding, for disabling submit. */
|
|
18
19
|
isChecking: boolean;
|
|
19
20
|
};
|
|
20
|
-
export declare const useAsyncCheck: (check: (value: string) => Promise<string | undefined>, revalidate: UseFormReturn['revalidate']) => AsyncCheck;
|
|
21
|
+
export declare const useAsyncCheck: (check: (value: string) => Promise<string | undefined>, revalidate: UseFormReturn<ObjectSchema>['revalidate']) => AsyncCheck;
|
|
@@ -57,15 +57,15 @@ const isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(v
|
|
|
57
57
|
* the browser ignores wholesale (zod's own email regex is one).
|
|
58
58
|
*/
|
|
59
59
|
const patternVerdict = (source, flags) => {
|
|
60
|
-
if (flags !== void 0 && flags !== "" && flags !== "u") return
|
|
61
|
-
if (!source.startsWith("^") || !source.endsWith("$")) return "
|
|
60
|
+
if (flags !== void 0 && flags !== "" && flags !== "u") return `the pattern attribute has no flag '${flags}', so the browser would judge the value differently`;
|
|
61
|
+
if (!source.startsWith("^") || !source.endsWith("$")) return "the pattern attribute matches the whole value while a zod regex matches a part of it, so a regex not wrapped in ^…$ would mean something else in the browser";
|
|
62
62
|
return (() => {
|
|
63
63
|
try {
|
|
64
64
|
return new RegExp(source, "v").flags === "v";
|
|
65
65
|
} catch {
|
|
66
66
|
return false;
|
|
67
67
|
}
|
|
68
|
-
})() ? void 0 : "
|
|
68
|
+
})() ? void 0 : "browsers compile pattern with the v flag and silently ignore a regex that does not compile with it";
|
|
69
69
|
};
|
|
70
70
|
/** Whether a JSON Schema `format` names what a control submits, not a refinement of it. */
|
|
71
71
|
const namesAControl = (format) => Object.hasOwn(FORMAT_TO_INPUT_TYPE, format);
|
|
@@ -86,12 +86,12 @@ const attributesFor = (name, schema, required, hints = {}) => {
|
|
|
86
86
|
input.accept = accept.join(",");
|
|
87
87
|
dropped.push({
|
|
88
88
|
field: name,
|
|
89
|
-
reason: "accept
|
|
89
|
+
reason: "accept only narrows what the file picker offers; the browser does not check the type of the file chosen"
|
|
90
90
|
});
|
|
91
91
|
}
|
|
92
92
|
if (schema.minLength !== void 0 || schema.maxLength !== void 0) dropped.push({
|
|
93
93
|
field: name,
|
|
94
|
-
reason: "
|
|
94
|
+
reason: "no HTML attribute bounds the size of a file (minlength / maxlength do not apply to type=\"file\")"
|
|
95
95
|
});
|
|
96
96
|
return {
|
|
97
97
|
input,
|
|
@@ -99,10 +99,9 @@ const attributesFor = (name, schema, required, hints = {}) => {
|
|
|
99
99
|
};
|
|
100
100
|
}
|
|
101
101
|
if (schema.anyOf !== void 0) {
|
|
102
|
-
input.type = "text";
|
|
103
102
|
dropped.push({
|
|
104
103
|
field: name,
|
|
105
|
-
reason: "nullable
|
|
104
|
+
reason: "constraints inside a nullable or a union have no attribute, since no single branch is the one to check"
|
|
106
105
|
});
|
|
107
106
|
return {
|
|
108
107
|
input,
|
|
@@ -128,7 +127,7 @@ const attributesFor = (name, schema, required, hints = {}) => {
|
|
|
128
127
|
if (schema.type === "integer") input.min = schema.exclusiveMinimum + 1;
|
|
129
128
|
else dropped.push({
|
|
130
129
|
field: name,
|
|
131
|
-
reason: `exclusiveMinimum ${String(schema.exclusiveMinimum)}
|
|
130
|
+
reason: `exclusiveMinimum ${String(schema.exclusiveMinimum)} cannot be expressed: the min attribute includes its bound`
|
|
132
131
|
});
|
|
133
132
|
}
|
|
134
133
|
if (isFiniteNumber(schema.maximum) && !JS_SAFE_INTEGER_BOUNDS.has(schema.maximum)) input.max = schema.maximum;
|
|
@@ -136,7 +135,7 @@ const attributesFor = (name, schema, required, hints = {}) => {
|
|
|
136
135
|
if (schema.type === "integer") input.max = schema.exclusiveMaximum - 1;
|
|
137
136
|
else dropped.push({
|
|
138
137
|
field: name,
|
|
139
|
-
reason: `exclusiveMaximum ${String(schema.exclusiveMaximum)}
|
|
138
|
+
reason: `exclusiveMaximum ${String(schema.exclusiveMaximum)} cannot be expressed: the max attribute includes its bound`
|
|
140
139
|
});
|
|
141
140
|
}
|
|
142
141
|
return {
|
|
@@ -145,28 +144,28 @@ const attributesFor = (name, schema, required, hints = {}) => {
|
|
|
145
144
|
};
|
|
146
145
|
}
|
|
147
146
|
if (schema.type !== "string") {
|
|
148
|
-
input.type = "text";
|
|
149
147
|
dropped.push({
|
|
150
148
|
field: name,
|
|
151
|
-
reason: "
|
|
149
|
+
reason: "the schema exposes no constraints (a transform, a pipe or a custom check), so the field is a bare text input and the browser checks nothing on it"
|
|
152
150
|
});
|
|
153
151
|
return {
|
|
154
152
|
input,
|
|
155
153
|
dropped
|
|
156
154
|
};
|
|
157
155
|
}
|
|
158
|
-
|
|
156
|
+
const type = schema.format === void 0 ? void 0 : FORMAT_TO_INPUT_TYPE[schema.format];
|
|
157
|
+
if (type !== void 0 && type !== "text") input.type = type;
|
|
159
158
|
if (isFiniteNumber(schema.minLength) && schema.minLength > 0) input.minLength = schema.minLength;
|
|
160
159
|
if (isFiniteNumber(schema.maxLength)) input.maxLength = schema.maxLength;
|
|
161
160
|
const patterns = schema.pattern === void 0 ? (schema.allOf ?? []).flatMap((branch) => branch.pattern === void 0 ? [] : [branch.pattern]) : [schema.pattern];
|
|
162
|
-
if (TYPES_WITHOUT_PATTERN.has(input.type)) {
|
|
161
|
+
if (input.type !== void 0 && TYPES_WITHOUT_PATTERN.has(input.type)) {
|
|
163
162
|
if (patterns.filter((pattern) => !((input.type === "date" || input.type === "datetime-local") && pattern === hints.ofFormat)).length > 0) dropped.push({
|
|
164
163
|
field: name,
|
|
165
|
-
reason: `pattern
|
|
164
|
+
reason: `pattern is ignored on type="${input.type}"`
|
|
166
165
|
});
|
|
167
166
|
} else if (patterns.length > 1) dropped.push({
|
|
168
167
|
field: name,
|
|
169
|
-
reason: `
|
|
168
|
+
reason: `the pattern attribute holds one regex, so the browser checks none of the ${String(patterns.length)} stacked ones`
|
|
170
169
|
});
|
|
171
170
|
else if (patterns[0] !== void 0) {
|
|
172
171
|
const verdict = patternVerdict(patterns[0], hints.flags);
|
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import { FormFields } from "../types.mjs";
|
|
2
|
-
import { ArrayPathsOf, FieldPathsOf, StringCheckboxPathsOf } from "../paths.mjs";
|
|
3
|
-
import { ObjectSchema } from "../schema/object-schema.mjs";
|
|
4
1
|
import { FormDefinition } from "../rules/define-form.mjs";
|
|
2
|
+
import { ObjectSchema } from "../schema/object-schema.mjs";
|
|
3
|
+
import { FormFields } from "../types.mjs";
|
|
5
4
|
/**
|
|
6
5
|
* Derive input attributes and messages from one zod object schema.
|
|
7
6
|
*
|
|
8
|
-
* Call this on the server
|
|
9
|
-
* result is plain data, so it crosses to
|
|
10
|
-
* enters the bundle. Messages are read when
|
|
11
|
-
*
|
|
12
|
-
*
|
|
7
|
+
* Call this on the server, during the render of the Server Component that
|
|
8
|
+
* hands its result to the form. The result is plain data, so it crosses to
|
|
9
|
+
* the client as props and zod never enters the bundle. Messages are read when
|
|
10
|
+
* it runs — zod's, and a rule's function message — so a call in the render
|
|
11
|
+
* words them for the request being answered.
|
|
13
12
|
*/
|
|
14
|
-
export declare const formFields: <
|
|
13
|
+
export declare const formFields: <Source extends ObjectSchema | FormDefinition>(input: Source) => FormFields<Source>;
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { deriveRule } from "../rules/rules.mjs";
|
|
2
1
|
import { asDefinition } from "../rules/define-form.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import { attributesFor, emptySubmissionOf, namesAControl } from "./attributes.mjs";
|
|
2
|
+
import { deriveRule } from "../rules/rules.mjs";
|
|
5
3
|
import { schemaMap, unwrap } from "../schema/walk.mjs";
|
|
4
|
+
import { attributesFor, emptySubmissionOf, namesAControl } from "./attributes.mjs";
|
|
6
5
|
import { messagesFor } from "./messages.mjs";
|
|
7
|
-
import { $ZodCheckStringFormat } from "zod/v4/core";
|
|
6
|
+
import { $ZodCheckStringFormat, safeParse } from "zod/v4/core";
|
|
8
7
|
// src/derive/form-fields.ts
|
|
9
8
|
/**
|
|
10
9
|
* Object-level checks — `.refine()` and friends — vanish from the JSON Schema
|
|
@@ -40,7 +39,49 @@ const DATETIME_LOCAL_PROBE = "2000-01-01T00:00";
|
|
|
40
39
|
* that fails the probe is a check the control ignores, not a shape the control
|
|
41
40
|
* cannot produce.
|
|
42
41
|
*/
|
|
43
|
-
const refusesDatetimeLocal = (schema) =>
|
|
42
|
+
const refusesDatetimeLocal = (schema) => safeParse(schema, DATETIME_LOCAL_PROBE).error?.issues.some((issue) => issue.code === "invalid_format" && issue.format === "datetime") ?? false;
|
|
43
|
+
/**
|
|
44
|
+
* zod's own wording for a checkbox group with `count` boxes checked, as the
|
|
45
|
+
* issue with `code` on the array itself. The boxes are the group's own
|
|
46
|
+
* options, so the count is the only thing that can fail.
|
|
47
|
+
*/
|
|
48
|
+
const countMessage = (array, options, count, code) => safeParse(array, Array.from({ length: count }, (_, index) => options[index % options.length])).error?.issues.find((issue) => issue.code === code && issue.path.length === 0)?.message;
|
|
49
|
+
const boxesChecked = (count) => `${String(count)} ${count === 1 ? "box is" : "boxes are"} checked`;
|
|
50
|
+
/**
|
|
51
|
+
* A checkbox group's `.min()` / `.max()` has no attribute — `required` on a
|
|
52
|
+
* box would require that box — so it crosses as rules the browser runs, the
|
|
53
|
+
* same way a declared rule does.
|
|
54
|
+
*/
|
|
55
|
+
const countRulesOf = (name, bounds, options) => {
|
|
56
|
+
const rules = [];
|
|
57
|
+
const dropped = [];
|
|
58
|
+
if (bounds.minItems !== void 0 && bounds.minItems > 0) {
|
|
59
|
+
const checked = bounds.minItems - 1;
|
|
60
|
+
const message = countMessage(bounds.array, options, checked, "too_small");
|
|
61
|
+
if (message === void 0) dropped.push(`zod gives no message for .min(${String(bounds.minItems)}) when ${boxesChecked(checked)}, so the browser does not check the lower bound`);
|
|
62
|
+
else rules.push({
|
|
63
|
+
kind: "minChecked",
|
|
64
|
+
field: name,
|
|
65
|
+
min: bounds.minItems,
|
|
66
|
+
message
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
if (bounds.maxItems !== void 0 && bounds.maxItems < options.length) {
|
|
70
|
+
const checked = bounds.maxItems + 1;
|
|
71
|
+
const message = countMessage(bounds.array, options, checked, "too_big");
|
|
72
|
+
if (message === void 0) dropped.push(`zod gives no message for .max(${String(bounds.maxItems)}) when ${boxesChecked(checked)}, so the browser does not check the upper bound`);
|
|
73
|
+
else rules.push({
|
|
74
|
+
kind: "maxChecked",
|
|
75
|
+
field: name,
|
|
76
|
+
max: bounds.maxItems,
|
|
77
|
+
message
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
rules,
|
|
82
|
+
dropped
|
|
83
|
+
};
|
|
84
|
+
};
|
|
44
85
|
/**
|
|
45
86
|
* Schemas whose `dropped` list has already been reported. `formFields` is not
|
|
46
87
|
* memoized, so a schema derived in every request would otherwise warn on
|
|
@@ -60,26 +101,27 @@ const warnDropped = (schema, dropped) => {
|
|
|
60
101
|
warned.add(schema);
|
|
61
102
|
const lines = dropped.map(({ field, reason }) => ` - ${field}: ${reason}`);
|
|
62
103
|
console.warn([
|
|
63
|
-
"
|
|
104
|
+
"formFields: these checks run on the server only; the browser does not run them:",
|
|
64
105
|
...lines,
|
|
65
|
-
"
|
|
106
|
+
" formFields returns the same list as dropped."
|
|
66
107
|
].join("\n"));
|
|
67
108
|
};
|
|
68
109
|
/**
|
|
69
110
|
* Derive input attributes and messages from one zod object schema.
|
|
70
111
|
*
|
|
71
|
-
* Call this on the server
|
|
72
|
-
* result is plain data, so it crosses to
|
|
73
|
-
* enters the bundle. Messages are read when
|
|
74
|
-
*
|
|
75
|
-
*
|
|
112
|
+
* Call this on the server, during the render of the Server Component that
|
|
113
|
+
* hands its result to the form. The result is plain data, so it crosses to
|
|
114
|
+
* the client as props and zod never enters the bundle. Messages are read when
|
|
115
|
+
* it runs — zod's, and a rule's function message — so a call in the render
|
|
116
|
+
* words them for the request being answered.
|
|
76
117
|
*/
|
|
77
118
|
const formFields = (input) => {
|
|
78
119
|
const { schema, rules } = asDefinition(input);
|
|
79
|
-
const map = schemaMap(schema);
|
|
120
|
+
const map = schemaMap(schema, "formFields");
|
|
80
121
|
const fields = {};
|
|
81
122
|
const arrays = {};
|
|
82
123
|
const dropped = [];
|
|
124
|
+
const countRules = [];
|
|
83
125
|
for (const array of map.arrays) arrays[array.path] = {
|
|
84
126
|
path: array.path,
|
|
85
127
|
minItems: array.minItems,
|
|
@@ -95,7 +137,7 @@ const formFields = (input) => {
|
|
|
95
137
|
format = void 0;
|
|
96
138
|
formatDropped.push({
|
|
97
139
|
field: leaf.name,
|
|
98
|
-
reason:
|
|
140
|
+
reason: `this date-time format rejects what a datetime-local control submits (${DATETIME_LOCAL_PROBE}, with no seconds and no time zone), so the field falls back to a text input; z.iso.datetime({ local: true }) keeps datetime-local`
|
|
99
141
|
});
|
|
100
142
|
}
|
|
101
143
|
const { pattern } = leaf.json;
|
|
@@ -113,14 +155,27 @@ const formFields = (input) => {
|
|
|
113
155
|
...attributes.input,
|
|
114
156
|
value: leaf.checkedValue
|
|
115
157
|
};
|
|
116
|
-
if (leaf.group !== void 0
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
158
|
+
if (leaf.group !== void 0) {
|
|
159
|
+
if (leaf.arrayPath === null) {
|
|
160
|
+
const count = countRulesOf(leaf.name, leaf.group, leaf.json.enum ?? []);
|
|
161
|
+
countRules.push(...count.rules);
|
|
162
|
+
for (const reason of count.dropped) dropped.push({
|
|
163
|
+
field: leaf.path,
|
|
164
|
+
reason
|
|
165
|
+
});
|
|
166
|
+
} else if (leaf.group.minItems !== void 0 || leaf.group.maxItems !== void 0) dropped.push({
|
|
167
|
+
field: leaf.path,
|
|
168
|
+
reason: "a checkbox group inside repeated rows has no fixed name for a rule to target, so the browser does not check how many boxes are checked"
|
|
169
|
+
});
|
|
170
|
+
}
|
|
120
171
|
const derived = {
|
|
121
172
|
input: fieldInput,
|
|
122
173
|
messages: messagesFor(leaf.zod, fieldInput, leaf.required, emptySubmissionOf(leaf.kind)),
|
|
123
|
-
secret
|
|
174
|
+
secret,
|
|
175
|
+
...leaf.group !== void 0 && { group: {
|
|
176
|
+
minItems: leaf.group.minItems,
|
|
177
|
+
maxItems: leaf.group.maxItems
|
|
178
|
+
} }
|
|
124
179
|
};
|
|
125
180
|
const array = leaf.arrayPath === null ? void 0 : arrays[leaf.arrayPath];
|
|
126
181
|
if (array === void 0) fields[leaf.path] = derived;
|
|
@@ -133,13 +188,13 @@ const formFields = (input) => {
|
|
|
133
188
|
const objectChecks = objectLevelCheckCount(schema);
|
|
134
189
|
if (objectChecks > 0) dropped.push({
|
|
135
190
|
field: "(schema)",
|
|
136
|
-
reason: `${String(objectChecks)}
|
|
191
|
+
reason: objectChecks === 1 ? "an object-level check (.refine() and the like) has no HTML constraint attribute, so the browser does not run it" : `${String(objectChecks)} object-level checks (.refine() and the like) have no HTML constraint attribute, so the browser does not run them`
|
|
137
192
|
});
|
|
138
193
|
warnDropped(schema, dropped);
|
|
139
194
|
return {
|
|
140
195
|
fields,
|
|
141
196
|
arrays,
|
|
142
|
-
rules: rules.map((rule) => deriveRule(rule)),
|
|
197
|
+
rules: [...rules.map((rule) => deriveRule(rule)), ...countRules],
|
|
143
198
|
dropped
|
|
144
199
|
};
|
|
145
200
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AnyFieldInput, ValidityFlag } from "../types.mjs";
|
|
2
2
|
import { $ZodType } from "zod/v4/core";
|
|
3
3
|
/**
|
|
4
4
|
* Run each probe through the field's own schema and keep the message zod
|
|
@@ -6,4 +6,4 @@ import { $ZodType } from "zod/v4/core";
|
|
|
6
6
|
* flag — the browser's own wording is never used, since it is locale-dependent
|
|
7
7
|
* and cannot be controlled.
|
|
8
8
|
*/
|
|
9
|
-
export declare const messagesFor: (schema: $ZodType, input:
|
|
9
|
+
export declare const messagesFor: (schema: $ZodType, input: AnyFieldInput, required: boolean, emptySubmission: unknown) => Partial<Record<ValidityFlag, string>>;
|
package/dist/derive/messages.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { safeParse } from "zod/v4/core";
|
|
2
2
|
// src/derive/messages.ts
|
|
3
3
|
const repeat = (length) => "a".repeat(Math.max(length, 0));
|
|
4
4
|
const probesFor = (input, required, emptySubmission) => {
|
|
@@ -66,7 +66,7 @@ const probesFor = (input, required, emptySubmission) => {
|
|
|
66
66
|
const messagesFor = (schema, input, required, emptySubmission) => {
|
|
67
67
|
const messages = {};
|
|
68
68
|
for (const probe of probesFor(input, required, emptySubmission)) {
|
|
69
|
-
const result =
|
|
69
|
+
const result = safeParse(schema, probe.value);
|
|
70
70
|
if (result.success) continue;
|
|
71
71
|
const issue = probe.codes.map((code) => result.error.issues.find((candidate) => candidate.code === code)).find((found) => found !== void 0) ?? result.error.issues[0];
|
|
72
72
|
if (issue !== void 0) messages[probe.flag] = issue.message;
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { DerivedRule, Rule, RuleMessage } from "./rules/rules.mjs";
|
|
2
|
-
import { DerivedArray, DerivedField, DroppedCheck, FieldInput, FormFields, FormState, StringCheckboxInput, ValidityFlag } from "./types.mjs";
|
|
3
1
|
import { ArrayView, FieldView, FormErrorView, RowView, UseFormReturn, useForm } from "./use-form.mjs";
|
|
4
2
|
import { AsyncCheck, useAsyncCheck } from "./async-check.mjs";
|
|
5
3
|
import { HiddenValue } from "./hidden-value.mjs";
|
|
6
|
-
|
|
4
|
+
import { FormDefinition } from "./rules/define-form.mjs";
|
|
5
|
+
import { DerivedRule, Rule, RuleMessage } from "./rules/rules.mjs";
|
|
6
|
+
import { ObjectSchema } from "./schema/object-schema.mjs";
|
|
7
|
+
import { CheckboxGroupInput, CheckboxInput, DerivedArray, DerivedField, DroppedCheck, FieldInput, FileInput, FormFields, FormState, NumberInput, StringCheckboxInput, ValidityFlag } from "./types.mjs";
|
|
8
|
+
export { type ArrayView, type AsyncCheck, type CheckboxGroupInput, type CheckboxInput, type DerivedArray, type DerivedField, type DerivedRule, type DroppedCheck, type FieldInput, type FieldView, type FileInput, type FormDefinition, type FormErrorView, type FormFields, type FormState, HiddenValue, type NumberInput, type ObjectSchema, type RowView, type Rule, type RuleMessage, type StringCheckboxInput, type UseFormReturn, type ValidityFlag, useAsyncCheck, useForm };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { FormState } from "../types.mjs";
|
|
2
|
-
import { ObjectSchema } from "../schema/object-schema.mjs";
|
|
3
1
|
import { FormDefinition } from "../rules/define-form.mjs";
|
|
2
|
+
import { ObjectSchema } from "../schema/object-schema.mjs";
|
|
3
|
+
import { FormState } from "../types.mjs";
|
|
4
4
|
import { output } from "zod/v4/core";
|
|
5
5
|
export type ParseResult<Output> = {
|
|
6
6
|
success: true;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { breachOf } from "../rules/rules.mjs";
|
|
2
1
|
import { asDefinition } from "../rules/define-form.mjs";
|
|
3
|
-
import {
|
|
2
|
+
import { breachOf } from "../rules/rules.mjs";
|
|
4
3
|
import { INDEX, schemaMap } from "../schema/walk.mjs";
|
|
5
4
|
import { nameOf, setPath } from "./paths.mjs";
|
|
5
|
+
import { safeParse } from "zod/v4/core";
|
|
6
6
|
// src/parse/parse-form.ts
|
|
7
7
|
/**
|
|
8
8
|
* The submitted names are the only source for row counts, and anyone can POST
|
|
@@ -42,7 +42,7 @@ const isUntouched = (kind, value) => {
|
|
|
42
42
|
};
|
|
43
43
|
const describeMissing = (missing) => {
|
|
44
44
|
const shown = missing.slice(0, 5).join(", ");
|
|
45
|
-
return missing.length > 5 ? `${shown} …
|
|
45
|
+
return missing.length > 5 ? `${shown} … and ${String(missing.length - 5)} more` : shown;
|
|
46
46
|
};
|
|
47
47
|
/**
|
|
48
48
|
* Turn FormData into the shape the schema expects, then validate it.
|
|
@@ -55,10 +55,10 @@ const describeMissing = (missing) => {
|
|
|
55
55
|
*/
|
|
56
56
|
const parseForm = (input, formData) => {
|
|
57
57
|
const { schema, rules } = asDefinition(input);
|
|
58
|
-
const map = schemaMap(schema);
|
|
58
|
+
const map = schemaMap(schema, "parseForm");
|
|
59
59
|
const raw = {};
|
|
60
60
|
const missing = [];
|
|
61
|
-
const
|
|
61
|
+
const unechoed = /* @__PURE__ */ new Set();
|
|
62
62
|
const groups = /* @__PURE__ */ new Set();
|
|
63
63
|
const rows = rowCounts(formData, map.arrays);
|
|
64
64
|
for (const array of map.arrays) setPath(raw, array.path, Array.from({ length: rows[array.path] ?? 0 }));
|
|
@@ -66,7 +66,7 @@ const parseForm = (input, formData) => {
|
|
|
66
66
|
for (const leaf of map.leaves) {
|
|
67
67
|
const names = leaf.arrayPath === null ? [leaf.name] : Array.from({ length: rows[leaf.arrayPath] ?? 0 }, (_, index) => leaf.name.replace(INDEX, String(index)));
|
|
68
68
|
for (const name of names) {
|
|
69
|
-
if (leaf.json.input === "password")
|
|
69
|
+
if (leaf.json.input === "password" || leaf.kind === "file") unechoed.add(name);
|
|
70
70
|
if (leaf.group !== void 0) {
|
|
71
71
|
groups.add(name);
|
|
72
72
|
setPath(raw, name, strings(name));
|
|
@@ -89,8 +89,8 @@ const parseForm = (input, formData) => {
|
|
|
89
89
|
setPath(raw, name, isUntouched(leaf.kind, value) ? void 0 : value);
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
|
-
if (missing.length > 0) throw new Error(`
|
|
93
|
-
const result =
|
|
92
|
+
if (missing.length > 0) throw new Error(`parseForm: the submission has no entry for these fields of the schema: ${describeMissing(missing)}. Render each one, with the name from its input.`);
|
|
93
|
+
const result = safeParse(schema, raw);
|
|
94
94
|
const breaches = {};
|
|
95
95
|
for (const rule of rules) {
|
|
96
96
|
if (Object.hasOwn(breaches, rule.field)) continue;
|
|
@@ -100,7 +100,7 @@ const parseForm = (input, formData) => {
|
|
|
100
100
|
const values = {};
|
|
101
101
|
for (const name of groups) values[name] = strings(name);
|
|
102
102
|
for (const [name, value] of formData.entries()) {
|
|
103
|
-
if (typeof value !== "string" ||
|
|
103
|
+
if (typeof value !== "string" || unechoed.has(name) || groups.has(name)) continue;
|
|
104
104
|
const existing = values[name];
|
|
105
105
|
if (existing === void 0) values[name] = value;
|
|
106
106
|
else if (typeof existing === "string") values[name] = [existing, value];
|
package/dist/paths.d.mts
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* Dotted paths derived from a zod object type, so `field('titel')` fails to
|
|
3
|
-
* compile rather than at runtime. Arrays of objects are reached through
|
|
4
|
-
* `array()`, so they are excluded from the field paths and listed separately —
|
|
5
|
-
* except an array of enums, which is a checkbox group: one shared name, so it
|
|
6
|
-
* is a field.
|
|
7
|
-
*
|
|
8
|
-
* Wrappers (`.optional()`, `.nullable()`, `.default()`, …) are peeled the same
|
|
9
|
-
* way the runtime walk peels them, so the two advertise the same paths — except
|
|
10
|
-
* where the walk refuses the schema outright, as it does a nullable object.
|
|
11
|
-
*/
|
|
1
|
+
import { CheckboxGroupInput, CheckboxInput, FieldInput, FileInput, NumberInput, StringCheckboxInput } from "./types.mjs";
|
|
12
2
|
type Join<Prefix extends string, Key extends string> = Prefix extends '' ? Key : `${Prefix}.${Key}`;
|
|
13
3
|
/**
|
|
14
4
|
* Wrappers keep their inner schema on the shared core definition; following it
|
|
@@ -42,16 +32,23 @@ type IsEnum<Schema> = Unwrap<Schema> extends {
|
|
|
42
32
|
};
|
|
43
33
|
};
|
|
44
34
|
} ? true : false;
|
|
45
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Each field path paired with the type of its `input`. One walk yields both,
|
|
37
|
+
* so the paths `field()` accepts and the inputs it returns cannot disagree.
|
|
38
|
+
*/
|
|
39
|
+
type FieldEntriesOf<Schema, Prefix extends string = ''> = Unwrap<Schema> extends (infer Bare) ? IsArray<Bare> extends true ? IsEnum<ArrayElement<Bare>> extends true ? [Prefix, CheckboxGroupInput] : never : Bare extends {
|
|
46
40
|
shape: infer Shape;
|
|
47
|
-
} ? { [Key in keyof Shape & string]:
|
|
41
|
+
} ? { [Key in keyof Shape & string]: FieldEntriesOf<Shape[Key], Join<Prefix, Key>>; }[keyof Shape & string] : [Prefix, LeafInputOf<Schema>] : never;
|
|
42
|
+
export type FieldPathsOf<Schema> = FieldEntriesOf<Schema>[0];
|
|
43
|
+
export type FieldInputsOf<Schema> = { [Entry in FieldEntriesOf<Schema> as Entry[0]]: Entry[1]; };
|
|
48
44
|
/**
|
|
49
45
|
* No recursion into an array's element: a repeat inside a repeat has no
|
|
50
46
|
* unambiguous name, and the runtime walk refuses it too.
|
|
51
47
|
*/
|
|
52
|
-
|
|
48
|
+
type ArrayEntriesOf<Schema, Prefix extends string = ''> = Unwrap<Schema> extends (infer Bare) ? IsArray<Bare> extends true ? IsEnum<ArrayElement<Bare>> extends true ? never : Prefix extends '' ? never : [Prefix, FieldInputsOf<ArrayElement<Bare>>] : Bare extends {
|
|
53
49
|
shape: infer Shape;
|
|
54
|
-
} ? { [Key in keyof Shape & string]:
|
|
50
|
+
} ? { [Key in keyof Shape & string]: ArrayEntriesOf<Shape[Key], Join<Prefix, Key>>; }[keyof Shape & string] : never : never;
|
|
51
|
+
export type ArrayInputsOf<Schema> = { [Entry in ArrayEntriesOf<Schema> as Entry[0]]: Entry[1]; };
|
|
55
52
|
/**
|
|
56
53
|
* The one control whose `input` carries a `value` is a checkbox whose schema
|
|
57
54
|
* reads the submitted string (`z.stringbool()`). The runtime walk finds it by
|
|
@@ -74,11 +71,29 @@ type EncodesTrueAsString<Schema> = Schema extends {
|
|
|
74
71
|
};
|
|
75
72
|
} ? [In] extends [string] ? [Output] extends [boolean] ? true : false : false : false;
|
|
76
73
|
/**
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
74
|
+
* `Unwrap` without `.nullable()`, which turns a leaf's JSON node into a union
|
|
75
|
+
* and so the control into a bare text input — the leaf no longer derives the
|
|
76
|
+
* control its own type names.
|
|
80
77
|
*/
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
78
|
+
type UnwrapLeaf<Schema> = Schema extends {
|
|
79
|
+
_zod: {
|
|
80
|
+
def: {
|
|
81
|
+
type: 'nullable';
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
} ? Schema : Schema extends {
|
|
85
|
+
_zod: {
|
|
86
|
+
def: {
|
|
87
|
+
innerType: infer Inner;
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
} ? UnwrapLeaf<Inner> : Schema;
|
|
91
|
+
type InputOfType<Type> = [Type] extends ['number'] ? NumberInput : [Type] extends ['boolean'] ? CheckboxInput : [Type] extends ['file'] ? FileInput : FieldInput;
|
|
92
|
+
type LeafInputOf<Schema> = UnwrapLeaf<Schema> extends (infer Leaf) ? EncodesTrueAsString<Leaf> extends true ? StringCheckboxInput : Leaf extends {
|
|
93
|
+
_zod: {
|
|
94
|
+
def: {
|
|
95
|
+
type: infer Type;
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
} ? InputOfType<Type> : FieldInput : never;
|
|
84
99
|
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Rule } from "./rules.mjs";
|
|
2
1
|
import { FieldPathsOf } from "../paths.mjs";
|
|
3
2
|
import { ObjectSchema } from "../schema/object-schema.mjs";
|
|
3
|
+
import { Rule } from "./rules.mjs";
|
|
4
4
|
/**
|
|
5
5
|
* A schema plus the checks HTML cannot express. Declaring them together is
|
|
6
6
|
* what keeps the client and the server working from one source: `formFields`
|
package/dist/rules/rules.d.mts
CHANGED
|
@@ -20,19 +20,26 @@ export type Rule<Field extends string = string> = RuleOf<Field, RuleMessage>;
|
|
|
20
20
|
export type RuleMessage = string | (() => string);
|
|
21
21
|
/**
|
|
22
22
|
* A rule as it crosses to the client. A function cannot cross the RSC
|
|
23
|
-
* boundary, so `formFields` has already called it.
|
|
23
|
+
* boundary, so `formFields` has already called it. Besides the declared rules,
|
|
24
|
+
* `formFields` adds the count a checkbox group's array schema allows
|
|
25
|
+
* (`.min()` / `.max()`), worded by zod.
|
|
24
26
|
*/
|
|
25
|
-
export type DerivedRule = RuleOf<string, string
|
|
27
|
+
export type DerivedRule = RuleOf<string, string> | {
|
|
28
|
+
kind: 'minChecked';
|
|
29
|
+
field: string;
|
|
30
|
+
min: number;
|
|
31
|
+
message: string;
|
|
32
|
+
} | {
|
|
33
|
+
kind: 'maxChecked';
|
|
34
|
+
field: string;
|
|
35
|
+
max: number;
|
|
36
|
+
message: string;
|
|
37
|
+
};
|
|
26
38
|
type RuleOf<Field extends string, Message> = {
|
|
27
39
|
kind: 'sameAs';
|
|
28
40
|
field: Field;
|
|
29
41
|
other: Field;
|
|
30
42
|
message: Message;
|
|
31
|
-
} | {
|
|
32
|
-
kind: 'minChecked';
|
|
33
|
-
field: Field;
|
|
34
|
-
min: number;
|
|
35
|
-
message: Message;
|
|
36
43
|
} | {
|
|
37
44
|
kind: 'requiredWhen';
|
|
38
45
|
field: Field;
|
|
@@ -44,12 +51,10 @@ type RuleOf<Field extends string, Message> = {
|
|
|
44
51
|
export type Values = (name: string) => string[];
|
|
45
52
|
/** The value must equal another field's. Password confirmation, and the like. */
|
|
46
53
|
export declare const sameAs: <Field extends string>(field: Field, other: Field, message: RuleMessage) => Rule<Field>;
|
|
47
|
-
/** At least `min` boxes sharing this name must be checked. */
|
|
48
|
-
export declare const minChecked: <Field extends string>(field: Field, min: number, message: RuleMessage) => Rule<Field>;
|
|
49
54
|
/** Required only while another field holds a particular value. */
|
|
50
55
|
export declare const requiredWhen: <Field extends string>(field: Field, when: Field, equals: string, message: RuleMessage) => Rule<Field>;
|
|
51
56
|
/** The rule with its message called, ready to cross to the client. */
|
|
52
57
|
export declare const deriveRule: (rule: Rule) => DerivedRule;
|
|
53
58
|
/** The message when the rule is broken, or undefined when it holds. */
|
|
54
|
-
export declare const breachOf: (rule: Rule, values: Values) => string | undefined;
|
|
59
|
+
export declare const breachOf: (rule: Rule | DerivedRule, values: Values) => string | undefined;
|
|
55
60
|
export {};
|
package/dist/rules/rules.mjs
CHANGED
|
@@ -6,13 +6,6 @@ const sameAs = (field, other, message) => ({
|
|
|
6
6
|
other,
|
|
7
7
|
message
|
|
8
8
|
});
|
|
9
|
-
/** At least `min` boxes sharing this name must be checked. */
|
|
10
|
-
const minChecked = (field, min, message) => ({
|
|
11
|
-
kind: "minChecked",
|
|
12
|
-
field,
|
|
13
|
-
min,
|
|
14
|
-
message
|
|
15
|
-
});
|
|
16
9
|
/** Required only while another field holds a particular value. */
|
|
17
10
|
const requiredWhen = (field, when, equals, message) => ({
|
|
18
11
|
kind: "requiredWhen",
|
|
@@ -26,8 +19,8 @@ const holds = (rule, values) => {
|
|
|
26
19
|
switch (rule.kind) {
|
|
27
20
|
case "sameAs": return first(values, rule.field) === first(values, rule.other);
|
|
28
21
|
case "minChecked": return values(rule.field).length >= rule.min;
|
|
22
|
+
case "maxChecked": return values(rule.field).length <= rule.max;
|
|
29
23
|
case "requiredWhen": return first(values, rule.when) !== rule.equals || first(values, rule.field) !== "";
|
|
30
|
-
default: return true;
|
|
31
24
|
}
|
|
32
25
|
};
|
|
33
26
|
const textOf = (message) => typeof message === "function" ? message() : message;
|
|
@@ -38,4 +31,4 @@ const deriveRule = (rule) => ({
|
|
|
38
31
|
});
|
|
39
32
|
/** The message when the rule is broken, or undefined when it holds. */
|
|
40
33
|
const breachOf = (rule, values) => holds(rule, values) ? void 0 : textOf(rule.message);
|
|
41
|
-
export { breachOf, deriveRule,
|
|
34
|
+
export { breachOf, deriveRule, requiredWhen, sameAs };
|