formo-react 0.0.0-stage → 0.2.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/LICENSE +201 -0
- package/README.md +21 -2
- package/dist/components/FormoBlueprint.d.ts +5 -0
- package/dist/components/FormoBlueprint.js +30 -0
- package/dist/components/FormoButton.d.ts +6 -0
- package/dist/components/FormoButton.js +23 -0
- package/dist/components/FormoCheckbox.d.ts +7 -0
- package/dist/components/FormoCheckbox.js +10 -0
- package/dist/components/FormoChecklist.d.ts +5 -0
- package/dist/components/FormoChecklist.js +15 -0
- package/dist/components/FormoChoices.d.ts +8 -0
- package/dist/components/FormoChoices.js +33 -0
- package/dist/components/FormoContext.d.ts +27 -0
- package/dist/components/FormoContext.js +69 -0
- package/dist/components/FormoErrors.d.ts +5 -0
- package/dist/components/FormoErrors.js +14 -0
- package/dist/components/FormoField.d.ts +17 -0
- package/dist/components/FormoField.js +148 -0
- package/dist/components/FormoForm.d.ts +15 -0
- package/dist/components/FormoForm.js +76 -0
- package/dist/components/FormoGroup.d.ts +5 -0
- package/dist/components/FormoGroup.js +15 -0
- package/dist/components/FormoHelp.d.ts +6 -0
- package/dist/components/FormoHelp.js +9 -0
- package/dist/components/FormoInput.d.ts +6 -0
- package/dist/components/FormoInput.js +24 -0
- package/dist/components/FormoLabel.d.ts +6 -0
- package/dist/components/FormoLabel.js +9 -0
- package/dist/components/FormoProvider.d.ts +11 -0
- package/dist/components/FormoProvider.js +13 -0
- package/dist/components/FormoRest.d.ts +6 -0
- package/dist/components/FormoRest.js +23 -0
- package/dist/components/FormoSelect.d.ts +6 -0
- package/dist/components/FormoSelect.js +36 -0
- package/dist/components/FormoUneditable.d.ts +6 -0
- package/dist/components/FormoUneditable.js +12 -0
- package/dist/core/builder.d.ts +42 -0
- package/dist/core/builder.js +166 -0
- package/dist/core/controls.d.ts +27 -0
- package/dist/core/controls.js +24 -0
- package/dist/core/fields.d.ts +63 -0
- package/dist/core/fields.js +177 -0
- package/dist/core/messages.d.ts +35 -0
- package/dist/core/messages.js +69 -0
- package/dist/core/normalize.d.ts +35 -0
- package/dist/core/normalize.js +234 -0
- package/dist/core/options.d.ts +44 -0
- package/dist/core/options.js +146 -0
- package/dist/core/rules.d.ts +41 -0
- package/dist/core/rules.js +230 -0
- package/dist/core/store.d.ts +155 -0
- package/dist/core/store.js +830 -0
- package/dist/core/theme.d.ts +20 -0
- package/dist/core/theme.js +21 -0
- package/dist/core/tree.d.ts +74 -0
- package/dist/core/tree.js +119 -0
- package/dist/core/utils.d.ts +35 -0
- package/dist/core/utils.js +206 -0
- package/dist/hooks/subscriptions.d.ts +38 -0
- package/dist/hooks/subscriptions.js +65 -0
- package/dist/hooks/useFormo.d.ts +18 -0
- package/dist/hooks/useFormo.js +25 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +27 -0
- package/dist/schema/form.d.ts +92 -0
- package/dist/schema/form.js +304 -0
- package/dist/schema/index.d.ts +22 -0
- package/dist/schema/index.js +21 -0
- package/dist/schema/ir.d.ts +189 -0
- package/dist/schema/ir.js +130 -0
- package/dist/schema/json-schema.d.ts +25 -0
- package/dist/schema/json-schema.js +351 -0
- package/dist/schema/laravel.d.ts +57 -0
- package/dist/schema/laravel.js +555 -0
- package/dist/schema/openapi.d.ts +24 -0
- package/dist/schema/openapi.js +67 -0
- package/dist/schema/policy.d.ts +60 -0
- package/dist/schema/policy.js +315 -0
- package/dist/schema/spec.d.ts +75 -0
- package/dist/schema/spec.js +1 -0
- package/dist/schema/values.d.ts +35 -0
- package/dist/schema/values.js +151 -0
- package/dist/schema/zod.d.ts +79 -0
- package/dist/schema/zod.js +236 -0
- package/dist/types.d.ts +400 -0
- package/dist/types.js +1 -0
- package/package.json +70 -4
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { type FormoModel, type WarningHandler } from './ir';
|
|
2
|
+
/**
|
|
3
|
+
* Zod (v4) object schema → Formo model. No dependency on Zod: the schema is read
|
|
4
|
+
* through its JSON Schema (`z.toJSONSchema`) and run through `safeParseAsync`.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { z } from 'zod'
|
|
8
|
+
* const User = z.object({
|
|
9
|
+
* name: z.string().min(2).meta({ title: 'Full name' }),
|
|
10
|
+
* email: z.email(),
|
|
11
|
+
* password: z.string().min(8).refine((v) => /\d/.test(v), 'Add a number'),
|
|
12
|
+
* password_confirmation: z.string(),
|
|
13
|
+
* }).refine((u) => u.password === u.password_confirmation, { path: ['password_confirmation'], message: 'Passwords differ' })
|
|
14
|
+
*
|
|
15
|
+
* const form = useFormo(formFromModel(fromZod(User, { toJSONSchema: z.toJSONSchema })))
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* With `validation: 'derived'` (the default), Formo rules come from the schema's
|
|
19
|
+
* constraints — Formo's messages, checklists, locales, Laravel lang files — and
|
|
20
|
+
* what Formo can't express still runs through Zod: a field's `.refine()` /
|
|
21
|
+
* `.superRefine()` as its last rule, object-level refinements when the form is
|
|
22
|
+
* submitted (their `path` puts the error on the right field).
|
|
23
|
+
* `validation: 'schema'` makes Zod the only validator.
|
|
24
|
+
*
|
|
25
|
+
* Empty inputs are read the Zod way before parsing: `''` / `null` → `undefined`
|
|
26
|
+
* (or `null` for `.nullable()` fields), so `.optional()` fields accept empty inputs.
|
|
27
|
+
*/
|
|
28
|
+
export interface FromZodOptions {
|
|
29
|
+
/** The model's name (suggested form alias) */
|
|
30
|
+
name?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Zod's JSON Schema converter — `z.toJSONSchema`. Optional when the schema
|
|
33
|
+
* can produce its JSON Schema itself (Standard JSON Schema / `.toJSONSchema()`)
|
|
34
|
+
*/
|
|
35
|
+
toJSONSchema?: (schema: any, params?: any) => unknown;
|
|
36
|
+
onWarning?: WarningHandler;
|
|
37
|
+
/**
|
|
38
|
+
* Called whenever a Zod refinement (`.refine()`, `.superRefine()`, `z.custom()`)
|
|
39
|
+
* fails — a field's while it's validated, an object-level one on the field its
|
|
40
|
+
* `path` names. For debugging, logging, analytics (the playground tags errors with it)
|
|
41
|
+
*/
|
|
42
|
+
onRefinement?: (refinement: ZodRefinement) => void;
|
|
43
|
+
}
|
|
44
|
+
export interface ZodRefinement {
|
|
45
|
+
/** Form path the error is shown on (`password`, `phones[0].number`, `''` for the form) */
|
|
46
|
+
path: string;
|
|
47
|
+
message: string;
|
|
48
|
+
/** `field`: the field's own refinement · `form`: an object-level one */
|
|
49
|
+
level: 'field' | 'form';
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* What's used from a Zod schema (duck-typed). Method syntax on purpose: Zod's
|
|
53
|
+
* own signatures are narrower (literal `target`s, extra params) and must fit.
|
|
54
|
+
*/
|
|
55
|
+
export interface ZodLikeSchema {
|
|
56
|
+
safeParseAsync?(value: unknown): Promise<{
|
|
57
|
+
success: boolean;
|
|
58
|
+
error?: {
|
|
59
|
+
issues: readonly ZodLikeIssue[];
|
|
60
|
+
};
|
|
61
|
+
}>;
|
|
62
|
+
'~standard'?: {
|
|
63
|
+
validate(value: unknown): unknown;
|
|
64
|
+
jsonSchema?: {
|
|
65
|
+
input?(options: {
|
|
66
|
+
target: string;
|
|
67
|
+
}): unknown;
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
[key: string]: any;
|
|
71
|
+
}
|
|
72
|
+
export interface ZodLikeIssue {
|
|
73
|
+
code?: string;
|
|
74
|
+
path?: ReadonlyArray<PropertyKey | {
|
|
75
|
+
key: PropertyKey;
|
|
76
|
+
}>;
|
|
77
|
+
message: string;
|
|
78
|
+
}
|
|
79
|
+
export declare function fromZod(schema: ZodLikeSchema, options?: FromZodOptions): FormoModel;
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { isEmptyValue, isPlainObject, joinPath } from '../core/utils';
|
|
2
|
+
import { RUNTIME, consoleWarning, } from './ir';
|
|
3
|
+
import { fromJsonSchema } from './json-schema';
|
|
4
|
+
const WRAPPERS = new Set(['optional', 'nullable', 'default', 'prefault', 'catch', 'readonly', 'nonoptional', 'lazy']);
|
|
5
|
+
const defOf = (schema) => {
|
|
6
|
+
const def = schema?._zod?.def;
|
|
7
|
+
return def && typeof def === 'object' ? def : undefined;
|
|
8
|
+
};
|
|
9
|
+
/** Peel optional / nullable / default… and pipes (their input side) */
|
|
10
|
+
function unwrap(schema) {
|
|
11
|
+
let cur = schema;
|
|
12
|
+
for (let i = 0; i < 32; i++) {
|
|
13
|
+
const def = defOf(cur);
|
|
14
|
+
if (!def)
|
|
15
|
+
return cur;
|
|
16
|
+
if (WRAPPERS.has(def.type) && def.innerType)
|
|
17
|
+
cur = def.innerType;
|
|
18
|
+
else if (def.type === 'lazy' && typeof def.getter === 'function')
|
|
19
|
+
cur = def.getter();
|
|
20
|
+
else if (def.type === 'pipe' && def.in)
|
|
21
|
+
cur = def.in;
|
|
22
|
+
else
|
|
23
|
+
return cur;
|
|
24
|
+
}
|
|
25
|
+
return cur;
|
|
26
|
+
}
|
|
27
|
+
/** Every schema along the wrappers — refinements can sit on any of them */
|
|
28
|
+
function chain(schema, out = [], depth = 0) {
|
|
29
|
+
const def = defOf(schema);
|
|
30
|
+
if (!def || depth > 32)
|
|
31
|
+
return out;
|
|
32
|
+
out.push(schema);
|
|
33
|
+
if (WRAPPERS.has(def.type) && def.innerType)
|
|
34
|
+
chain(def.innerType, out, depth + 1);
|
|
35
|
+
if (def.type === 'pipe') {
|
|
36
|
+
chain(def.in, out, depth + 1);
|
|
37
|
+
chain(def.out, out, depth + 1);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
/** Has `.refine()` / `.superRefine()` / `z.custom()`? `undefined`: can't tell (not a Zod 4 schema) */
|
|
42
|
+
function hasRefinements(schema) {
|
|
43
|
+
if (!defOf(schema))
|
|
44
|
+
return undefined;
|
|
45
|
+
return chain(schema).some((s) => {
|
|
46
|
+
const def = defOf(s);
|
|
47
|
+
if (def.type === 'custom')
|
|
48
|
+
return true;
|
|
49
|
+
return Array.isArray(def.checks) && def.checks.some((check) => (check?._zod?.def?.check ?? check?.def?.check) === 'custom');
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function shapeOf(schema) {
|
|
53
|
+
const inner = unwrap(schema);
|
|
54
|
+
const def = defOf(inner);
|
|
55
|
+
const shape = def?.type === 'object' ? def.shape : inner?.shape;
|
|
56
|
+
return shape && typeof shape === 'object' ? shape : undefined;
|
|
57
|
+
}
|
|
58
|
+
function elementOf(schema) {
|
|
59
|
+
const inner = unwrap(schema);
|
|
60
|
+
const def = defOf(inner);
|
|
61
|
+
return def?.type === 'array' ? def.element : inner?.element;
|
|
62
|
+
}
|
|
63
|
+
const isDate = (schema) => defOf(unwrap(schema))?.type === 'date';
|
|
64
|
+
/* ---- Parsing with form values ------------------------------------------------ */
|
|
65
|
+
function coerce(c, value) {
|
|
66
|
+
if (value === '' || value === null || value === undefined)
|
|
67
|
+
return c?.nullable ? null : undefined;
|
|
68
|
+
if (!c)
|
|
69
|
+
return value;
|
|
70
|
+
if (c.date && typeof value === 'string') {
|
|
71
|
+
const date = new Date(value);
|
|
72
|
+
return Number.isNaN(date.getTime()) ? value : date;
|
|
73
|
+
}
|
|
74
|
+
if (c.fields && isPlainObject(value)) {
|
|
75
|
+
const out = { ...value };
|
|
76
|
+
for (const [key, child] of Object.entries(c.fields))
|
|
77
|
+
out[key] = coerce(child, value[key]);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
if (c.items && Array.isArray(value))
|
|
81
|
+
return value.map((v) => coerce(c.items, v));
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
async function parse(schema, value) {
|
|
85
|
+
if (typeof schema.safeParseAsync === 'function') {
|
|
86
|
+
const result = await schema.safeParseAsync(value);
|
|
87
|
+
return result.success ? [] : (result.error?.issues ?? []);
|
|
88
|
+
}
|
|
89
|
+
const standard = schema['~standard'];
|
|
90
|
+
if (standard) {
|
|
91
|
+
const result = (await standard.validate(value));
|
|
92
|
+
return result?.issues ?? [];
|
|
93
|
+
}
|
|
94
|
+
throw new Error('[formo] fromZod: the schema has neither safeParseAsync() nor ~standard.validate()');
|
|
95
|
+
}
|
|
96
|
+
/** Keep only refinement issues (Standard Schema issues carry no code: keep them) */
|
|
97
|
+
const isRefinement = (issue) => issue.code === undefined || issue.code === 'custom';
|
|
98
|
+
function fieldRule(schema, c, only, name, report) {
|
|
99
|
+
return async (value, _params, ctx) => {
|
|
100
|
+
// Like every Formo rule but `required`: refinements don't run on empty values
|
|
101
|
+
if (only === 'refinements' && isEmptyValue(value))
|
|
102
|
+
return true;
|
|
103
|
+
const issues = await parse(schema, coerce(c, value));
|
|
104
|
+
const issue = only === 'all' ? issues[0] : issues.find(isRefinement);
|
|
105
|
+
if (issue && isRefinement(issue))
|
|
106
|
+
report?.({ path: ctx?.path ?? name, message: issue.message, level: 'field' });
|
|
107
|
+
return issue ? issue.message : true;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** An issue path → the form path of the closest rendered field (`undefined`: nothing to show it on) */
|
|
111
|
+
function issueTarget(path, form) {
|
|
112
|
+
const segments = (path ?? []).map((p) => (typeof p === 'object' && p !== null && 'key' in p ? p.key : p));
|
|
113
|
+
if (!segments.length)
|
|
114
|
+
return '';
|
|
115
|
+
for (let n = segments.length; n > 0; n--) {
|
|
116
|
+
const target = segments.slice(0, n).reduce((acc, s) => joinPath(acc, typeof s === 'number' ? s : String(s)), '');
|
|
117
|
+
if (form.isIgnored(target))
|
|
118
|
+
return undefined;
|
|
119
|
+
if (form.find(target)?.path === target)
|
|
120
|
+
return target;
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
function formCallback(schema, c, only, report) {
|
|
125
|
+
const callback = async ({ values, form }) => {
|
|
126
|
+
const issues = await parse(schema, coerce(c, values));
|
|
127
|
+
const shown = new Set();
|
|
128
|
+
for (const issue of issues) {
|
|
129
|
+
if (only === 'refinements' && !isRefinement(issue))
|
|
130
|
+
continue;
|
|
131
|
+
const target = issueTarget(issue.path, form);
|
|
132
|
+
if (target === undefined || shown.has(target))
|
|
133
|
+
continue;
|
|
134
|
+
shown.add(target);
|
|
135
|
+
form.setError(target, issue.message);
|
|
136
|
+
if (isRefinement(issue))
|
|
137
|
+
report?.({ path: target, message: issue.message, level: 'form' });
|
|
138
|
+
}
|
|
139
|
+
return shown.size ? false : undefined;
|
|
140
|
+
};
|
|
141
|
+
// Named, so definitions read well in devtools / the playground
|
|
142
|
+
Object.defineProperty(callback, 'name', { value: only === 'refinements' ? 'zodObjectRefinements' : 'zodSchema' });
|
|
143
|
+
return callback;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Does anything need a form-level pass — an object-level refinement on the
|
|
147
|
+
* schema, a nested object, a list or a row? (Fields' own refinements run as
|
|
148
|
+
* their rules.) `true` when it can't tell.
|
|
149
|
+
*/
|
|
150
|
+
function hasObjectRefinements(schema, depth = 0) {
|
|
151
|
+
if (depth > 32 || hasRefinements(schema) !== false)
|
|
152
|
+
return true;
|
|
153
|
+
const shape = shapeOf(schema);
|
|
154
|
+
if (!shape)
|
|
155
|
+
return false;
|
|
156
|
+
return Object.values(shape).some((child) => {
|
|
157
|
+
const type = defOf(unwrap(child))?.type;
|
|
158
|
+
if (type === 'object')
|
|
159
|
+
return hasObjectRefinements(child, depth + 1);
|
|
160
|
+
if (type === 'array') {
|
|
161
|
+
const element = elementOf(child);
|
|
162
|
+
return defOf(unwrap(element))?.type === 'object' && (hasRefinements(child) !== false || hasObjectRefinements(element, depth + 1));
|
|
163
|
+
}
|
|
164
|
+
return false;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/* ---- Model ------------------------------------------------------------------- */
|
|
168
|
+
function toJsonSchema(schema, options) {
|
|
169
|
+
const params = { io: 'input', unrepresentable: 'any' };
|
|
170
|
+
const attempts = [];
|
|
171
|
+
if (options.toJSONSchema)
|
|
172
|
+
attempts.push(() => options.toJSONSchema(schema, params));
|
|
173
|
+
if (typeof schema.toJSONSchema === 'function')
|
|
174
|
+
attempts.push(() => schema.toJSONSchema(params));
|
|
175
|
+
const standard = schema['~standard']?.jsonSchema;
|
|
176
|
+
if (typeof standard?.input === 'function')
|
|
177
|
+
attempts.push(() => standard.input({ target: 'draft-2020-12' }));
|
|
178
|
+
let lastError;
|
|
179
|
+
for (const attempt of attempts) {
|
|
180
|
+
try {
|
|
181
|
+
const json = attempt();
|
|
182
|
+
if (isPlainObject(json))
|
|
183
|
+
return json;
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
lastError = error;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const reason = lastError instanceof Error ? ` (${lastError.message})` : '';
|
|
190
|
+
throw new Error(`[formo] fromZod: can't get this schema's JSON Schema${reason} — pass { toJSONSchema: z.toJSONSchema }`);
|
|
191
|
+
}
|
|
192
|
+
/** Walk the model next to the Zod shape: attach validators, note how to coerce values */
|
|
193
|
+
function attach(fields, shape, report) {
|
|
194
|
+
const coercions = {};
|
|
195
|
+
for (const field of fields) {
|
|
196
|
+
const name = field.name;
|
|
197
|
+
const schema = name !== undefined ? shape?.[name] : undefined;
|
|
198
|
+
if (!schema || name === undefined)
|
|
199
|
+
continue;
|
|
200
|
+
const c = {};
|
|
201
|
+
if (field.nullable)
|
|
202
|
+
c.nullable = true;
|
|
203
|
+
// z.date(): not representable in JSON Schema, but a date input for a form
|
|
204
|
+
if (field.type === 'unknown' && isDate(schema))
|
|
205
|
+
field.type = 'date';
|
|
206
|
+
if (isDate(schema))
|
|
207
|
+
c.date = true;
|
|
208
|
+
if (field.type === 'object') {
|
|
209
|
+
c.fields = attach(field.fields ?? [], shapeOf(schema), report);
|
|
210
|
+
}
|
|
211
|
+
else if (field.type === 'array' && field.items?.type === 'object') {
|
|
212
|
+
c.items = { fields: attach(field.items.fields ?? [], shapeOf(elementOf(schema)), report) };
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
const refine = hasRefinements(schema) !== false;
|
|
216
|
+
field[RUNTIME] = {
|
|
217
|
+
validate: fieldRule(schema, c, 'all', name, report),
|
|
218
|
+
...(refine ? { refine: fieldRule(schema, c, 'refinements', name, report) } : {}),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
coercions[name] = c;
|
|
222
|
+
}
|
|
223
|
+
return coercions;
|
|
224
|
+
}
|
|
225
|
+
export function fromZod(schema, options = {}) {
|
|
226
|
+
const warn = options.onWarning ?? consoleWarning;
|
|
227
|
+
const model = fromJsonSchema(toJsonSchema(schema, options), { name: options.name, onWarning: warn });
|
|
228
|
+
model.meta = { source: 'zod' };
|
|
229
|
+
const root = { fields: attach(model.fields, shapeOf(schema), options.onRefinement) };
|
|
230
|
+
model[RUNTIME] = {
|
|
231
|
+
// Only when there are object-level refinements: otherwise no extra parse on every submit
|
|
232
|
+
...(hasObjectRefinements(schema) ? { refine: formCallback(schema, root, 'refinements', options.onRefinement) } : {}),
|
|
233
|
+
validate: formCallback(schema, root, 'all', options.onRefinement),
|
|
234
|
+
};
|
|
235
|
+
return model;
|
|
236
|
+
}
|