formo-react 0.0.0-stage → 0.3.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,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Formo model — IR JSON, version 1. A PUBLIC, VERSIONED CONTRACT.
|
|
3
|
+
*
|
|
4
|
+
* A neutral description of the *data* a form edits (not of the UI): what a
|
|
5
|
+
* backend (Laravel via Inertia props or a schema endpoint, Rails, an OpenAPI
|
|
6
|
+
* document…) or a frontend schema (JSON Schema, Zod) knows about a model.
|
|
7
|
+
* `formFromModel()` turns it into a Formo form definition.
|
|
8
|
+
*
|
|
9
|
+
* { "version": 1, "name": "user", "fields": [
|
|
10
|
+
* { "name": "email", "type": "string", "format": "email", "required": true, "constraints": { "maxLength": 255 } },
|
|
11
|
+
* { "name": "role", "type": "enum", "options": [{ "value": "admin", "label": "Administrator" }] }
|
|
12
|
+
* ] }
|
|
13
|
+
*
|
|
14
|
+
* Compatibility rules for `version: 1`:
|
|
15
|
+
* - Only additive changes: new optional keys, new `format` values. Readers ignore keys they don't know.
|
|
16
|
+
* - A `type` a reader doesn't know is read as `unknown` (with a warning), never an error.
|
|
17
|
+
* - Anything that changes the meaning of existing keys bumps `version`.
|
|
18
|
+
*
|
|
19
|
+
* The machine-readable contract is `docs/schema/formo-model-v1.schema.json`.
|
|
20
|
+
*
|
|
21
|
+
* Pure TypeScript: no Vue, no DOM — see `scripts/check-pure.ts`.
|
|
22
|
+
*/
|
|
23
|
+
export const MODEL_VERSION = 1;
|
|
24
|
+
/** Every `type` of version 1 */
|
|
25
|
+
export const MODEL_FIELD_TYPES = [
|
|
26
|
+
'string',
|
|
27
|
+
/** Long text (textarea) */
|
|
28
|
+
'text',
|
|
29
|
+
'integer',
|
|
30
|
+
'number',
|
|
31
|
+
'boolean',
|
|
32
|
+
/** `YYYY-MM-DD` */
|
|
33
|
+
'date',
|
|
34
|
+
/** Date and time */
|
|
35
|
+
'datetime',
|
|
36
|
+
/** `HH:MM[:SS]` */
|
|
37
|
+
'time',
|
|
38
|
+
/** One value out of `options` */
|
|
39
|
+
'enum',
|
|
40
|
+
'file',
|
|
41
|
+
/** Nested fields (a subform) */
|
|
42
|
+
'object',
|
|
43
|
+
/** A list: `items` describes one element (objects → repeatable rows, enums → several choices, files → multiple) */
|
|
44
|
+
'array',
|
|
45
|
+
/** A foreign key / related models (`relation` says which) */
|
|
46
|
+
'relation',
|
|
47
|
+
/** Anything else — skipped unless `ui` says how to render it */
|
|
48
|
+
'unknown',
|
|
49
|
+
];
|
|
50
|
+
/* -------------------------------------------------------------------------- */
|
|
51
|
+
/* Runtime attachments (not part of the JSON contract) */
|
|
52
|
+
/* -------------------------------------------------------------------------- */
|
|
53
|
+
/**
|
|
54
|
+
* Key of the validators a schema adapter (`fromZod`) attaches to a model. A
|
|
55
|
+
* symbol: `JSON.stringify()` leaves it out, spreads keep it.
|
|
56
|
+
*/
|
|
57
|
+
export const RUNTIME = Symbol.for('formo.model.runtime');
|
|
58
|
+
const seenWarnings = new Set();
|
|
59
|
+
/** Default: `console.warn`, once per message. Pass `onWarning` to collect or silence them */
|
|
60
|
+
export const consoleWarning = (warning) => {
|
|
61
|
+
const text = `[formo] ${warning.path ? `${warning.path}: ` : ''}${warning.message}`;
|
|
62
|
+
if (seenWarnings.has(text))
|
|
63
|
+
return;
|
|
64
|
+
seenWarnings.add(text);
|
|
65
|
+
globalThis.console?.warn(text);
|
|
66
|
+
};
|
|
67
|
+
const TYPES = new Set(MODEL_FIELD_TYPES);
|
|
68
|
+
function fail(path, message) {
|
|
69
|
+
throw new Error(`[formo] Invalid Formo model${path ? ` at ${path}` : ''}: ${message}`);
|
|
70
|
+
}
|
|
71
|
+
function readField(raw, path, warn, isItem) {
|
|
72
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
73
|
+
fail(path, 'a field must be an object');
|
|
74
|
+
const field = { ...raw };
|
|
75
|
+
if (!isItem) {
|
|
76
|
+
if (typeof field.name !== 'string' || !field.name)
|
|
77
|
+
fail(path, 'every field needs a `name`');
|
|
78
|
+
if (/[.*\s[\]]/.test(field.name))
|
|
79
|
+
fail(path, `"${field.name}" is not a valid field name (no dots, spaces, brackets or *)`);
|
|
80
|
+
}
|
|
81
|
+
if (typeof field.type !== 'string' || !TYPES.has(field.type)) {
|
|
82
|
+
warn({ path, code: 'unknown-type', message: `type "${String(field.type)}" isn't part of Formo model v1 — read as "unknown"` });
|
|
83
|
+
field.type = 'unknown';
|
|
84
|
+
}
|
|
85
|
+
if (field.fields !== undefined) {
|
|
86
|
+
if (!Array.isArray(field.fields))
|
|
87
|
+
fail(path, '`fields` must be an array');
|
|
88
|
+
field.fields = readFields(field.fields, path, warn);
|
|
89
|
+
}
|
|
90
|
+
if (field.items !== undefined)
|
|
91
|
+
field.items = readField(field.items, `${path}.*`, warn, true);
|
|
92
|
+
if (field.options !== undefined && !Array.isArray(field.options))
|
|
93
|
+
fail(path, '`options` must be an array');
|
|
94
|
+
return field;
|
|
95
|
+
}
|
|
96
|
+
function readFields(list, prefix, warn) {
|
|
97
|
+
const names = new Set();
|
|
98
|
+
return list.map((raw, i) => {
|
|
99
|
+
const name = raw && typeof raw === 'object' ? raw.name : undefined;
|
|
100
|
+
const field = readField(raw, prefix ? `${prefix}.${name ?? i}` : String(name ?? i), warn, false);
|
|
101
|
+
if (names.has(field.name))
|
|
102
|
+
fail(prefix, `duplicate field "${field.name}"`);
|
|
103
|
+
names.add(field.name);
|
|
104
|
+
return field;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Read a Formo model (an object or its JSON): checks the version and the
|
|
109
|
+
* structure, and returns a copy (runtime attachments kept).
|
|
110
|
+
*
|
|
111
|
+
* parseModel(props.userForm) // Inertia prop
|
|
112
|
+
* parseModel(await (await fetch('/formo/models/user')).json())
|
|
113
|
+
*/
|
|
114
|
+
export function parseModel(input, onWarning = consoleWarning) {
|
|
115
|
+
const raw = typeof input === 'string' ? JSON.parse(input) : input;
|
|
116
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
117
|
+
fail('', 'expected an object');
|
|
118
|
+
const model = raw;
|
|
119
|
+
if (!('version' in model))
|
|
120
|
+
fail('', 'missing `version` (expected `"version": 1`)');
|
|
121
|
+
if (model.version !== MODEL_VERSION) {
|
|
122
|
+
throw new Error(`[formo] Unsupported Formo model version ${JSON.stringify(model.version)} — this formo-vue reads version ${MODEL_VERSION}`);
|
|
123
|
+
}
|
|
124
|
+
if (!Array.isArray(model.fields))
|
|
125
|
+
fail('', '`fields` must be an array');
|
|
126
|
+
return { ...model, fields: readFields(model.fields, '', onWarning) };
|
|
127
|
+
}
|
|
128
|
+
export function isFormoModel(value) {
|
|
129
|
+
return !!value && typeof value === 'object' && value.version === MODEL_VERSION && Array.isArray(value.fields);
|
|
130
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type FormoModel, type WarningHandler } from './ir';
|
|
2
|
+
/**
|
|
3
|
+
* JSON Schema (draft-07 → 2020-12, and OpenAPI 3.0 / 3.1 schema objects) → Formo model.
|
|
4
|
+
*
|
|
5
|
+
* const model = fromJsonSchema(await (await fetch('/schemas/user.json')).json(), { name: 'user' })
|
|
6
|
+
*
|
|
7
|
+
* Understood: `properties` / `required`, `$ref` + `$defs` / `definitions` (local refs), `allOf`,
|
|
8
|
+
* nullable unions (`type: ['string', 'null']`, `anyOf` with `{ type: 'null' }`, OpenAPI's
|
|
9
|
+
* `nullable`), labelled enums (`oneOf: [{ const, title }]`, `x-enumNames`), `title` → label,
|
|
10
|
+
* `description` → help, `default`, `examples` → placeholder, `readOnly` / `writeOnly`,
|
|
11
|
+
* string `format`s, length / range / items / pattern constraints, `dependentRequired`
|
|
12
|
+
* (→ `required_with`), and `x-formo` (Formo definition keys, merged last).
|
|
13
|
+
* `if` / `then` / `else`, `not`, `oneOf` of objects… are reported and skipped.
|
|
14
|
+
*/
|
|
15
|
+
export type JsonSchema = Record<string, any> | boolean;
|
|
16
|
+
export interface FromJsonSchemaOptions {
|
|
17
|
+
/** The model's name (suggested form alias) */
|
|
18
|
+
name?: string;
|
|
19
|
+
/** JSON pointer (`#/$defs/User`) or `$defs` / `definitions` name of the object to read */
|
|
20
|
+
root?: string;
|
|
21
|
+
/** Document `$ref`s resolve against (default: the schema itself) — OpenAPI documents */
|
|
22
|
+
document?: Record<string, any>;
|
|
23
|
+
onWarning?: WarningHandler;
|
|
24
|
+
}
|
|
25
|
+
export declare function fromJsonSchema(schema: JsonSchema, options?: FromJsonSchemaOptions): FormoModel;
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import { isPlainObject } from '../core/utils';
|
|
2
|
+
import { MODEL_VERSION, consoleWarning, } from './ir';
|
|
3
|
+
const FORMATS = {
|
|
4
|
+
email: { type: 'string', format: 'email' },
|
|
5
|
+
'idn-email': { type: 'string', format: 'email' },
|
|
6
|
+
uri: { type: 'string', format: 'url' },
|
|
7
|
+
url: { type: 'string', format: 'url' },
|
|
8
|
+
iri: { type: 'string', format: 'url' },
|
|
9
|
+
'uri-reference': { type: 'string', format: 'url' },
|
|
10
|
+
date: { type: 'date' },
|
|
11
|
+
'date-time': { type: 'datetime' },
|
|
12
|
+
datetime: { type: 'datetime' },
|
|
13
|
+
time: { type: 'time' },
|
|
14
|
+
binary: { type: 'file' },
|
|
15
|
+
password: { type: 'string', format: 'password' },
|
|
16
|
+
textarea: { type: 'text' },
|
|
17
|
+
uuid: { type: 'string', format: 'uuid' },
|
|
18
|
+
color: { type: 'string', format: 'color' },
|
|
19
|
+
tel: { type: 'string', format: 'tel' },
|
|
20
|
+
phone: { type: 'string', format: 'tel' },
|
|
21
|
+
e164: { type: 'string', format: 'tel' },
|
|
22
|
+
ipv4: { type: 'string', format: 'ip' },
|
|
23
|
+
ipv6: { type: 'string', format: 'ip' },
|
|
24
|
+
ip: { type: 'string', format: 'ip' },
|
|
25
|
+
};
|
|
26
|
+
/** Bounds that mean "it's an integer", not a real constraint (Zod's `z.int()`, `z.int32()`) */
|
|
27
|
+
const NOT_A_BOUND = new Set([Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, 2147483647, -2147483648]);
|
|
28
|
+
const UNSUPPORTED = ['if', 'then', 'else', 'not', 'dependentSchemas', 'patternProperties', 'unevaluatedProperties'];
|
|
29
|
+
/** `#/$defs/User` → the schema */
|
|
30
|
+
function pointer(refRoot, ref) {
|
|
31
|
+
if (!ref.startsWith('#'))
|
|
32
|
+
return undefined;
|
|
33
|
+
const parts = ref.slice(1).split('/').filter(Boolean).map((p) => decodeURIComponent(p).replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
34
|
+
let cur = refRoot;
|
|
35
|
+
for (const part of parts) {
|
|
36
|
+
if (cur === null || typeof cur !== 'object')
|
|
37
|
+
return undefined;
|
|
38
|
+
cur = cur[part];
|
|
39
|
+
}
|
|
40
|
+
return cur;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Resolve `$ref`s and merge `allOf`. `stack` holds the refs being expanded above
|
|
44
|
+
* this schema (it grows as properties nest): meeting one again is a cycle.
|
|
45
|
+
*/
|
|
46
|
+
function resolve(schema, reader, path, stack) {
|
|
47
|
+
if (schema === true || schema === undefined)
|
|
48
|
+
return { schema: {}, stack };
|
|
49
|
+
if (schema === false)
|
|
50
|
+
return { schema: { not: {} }, stack };
|
|
51
|
+
let s = schema;
|
|
52
|
+
while (typeof s.$ref === 'string') {
|
|
53
|
+
const ref = s.$ref;
|
|
54
|
+
if (stack.includes(ref)) {
|
|
55
|
+
reader.warn({ path, code: 'recursive-ref', message: `${ref} refers to itself — not expanded` });
|
|
56
|
+
return { schema: { __recursive: true }, stack };
|
|
57
|
+
}
|
|
58
|
+
const target = pointer(reader.refRoot, ref);
|
|
59
|
+
if (!isPlainObject(target)) {
|
|
60
|
+
reader.warn({ path, code: 'unresolved-ref', message: `can't resolve ${ref} (only local #/ refs are supported)` });
|
|
61
|
+
return { schema: {}, stack };
|
|
62
|
+
}
|
|
63
|
+
stack = [...stack, ref];
|
|
64
|
+
const { $ref: _ignored, ...siblings } = s;
|
|
65
|
+
s = { ...target, ...siblings };
|
|
66
|
+
}
|
|
67
|
+
if (Array.isArray(s.allOf)) {
|
|
68
|
+
const { allOf, ...rest } = s;
|
|
69
|
+
let merged = {};
|
|
70
|
+
for (const part of [...allOf, rest]) {
|
|
71
|
+
const { schema: r } = resolve(part, reader, path, stack);
|
|
72
|
+
merged = {
|
|
73
|
+
...merged,
|
|
74
|
+
...r,
|
|
75
|
+
properties: { ...merged.properties, ...r.properties },
|
|
76
|
+
required: [...(merged.required ?? []), ...(r.required ?? [])],
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
if (!Object.keys(merged.properties).length)
|
|
80
|
+
delete merged.properties;
|
|
81
|
+
if (!merged.required.length)
|
|
82
|
+
delete merged.required;
|
|
83
|
+
s = merged;
|
|
84
|
+
}
|
|
85
|
+
return { schema: s, stack };
|
|
86
|
+
}
|
|
87
|
+
const isNullSchema = (s) => isPlainObject(s) && (s.type === 'null' || (Array.isArray(s.enum) && s.enum.length === 1 && s.enum[0] === null));
|
|
88
|
+
/** Peel `null` out of unions: returns the non-null schema and whether null was allowed */
|
|
89
|
+
function unwrapNullable(s, reader, path, stack) {
|
|
90
|
+
let nullable = s.nullable === true || s['x-nullable'] === true;
|
|
91
|
+
let schema = s;
|
|
92
|
+
if (Array.isArray(s.type) && s.type.includes('null')) {
|
|
93
|
+
nullable = true;
|
|
94
|
+
const types = s.type.filter((t) => t !== 'null');
|
|
95
|
+
schema = { ...s, type: types.length === 1 ? types[0] : types };
|
|
96
|
+
}
|
|
97
|
+
for (const key of ['anyOf', 'oneOf']) {
|
|
98
|
+
const list = schema[key];
|
|
99
|
+
if (!Array.isArray(list) || !list.some(isNullSchema))
|
|
100
|
+
continue;
|
|
101
|
+
nullable = true;
|
|
102
|
+
const rest = list.filter((m) => !isNullSchema(m));
|
|
103
|
+
const { [key]: _drop, ...siblings } = schema;
|
|
104
|
+
schema = rest.length === 1 ? { ...resolve(rest[0], reader, path, stack).schema, ...siblings } : { ...siblings, [key]: rest };
|
|
105
|
+
}
|
|
106
|
+
if (Array.isArray(schema.enum) && schema.enum.includes(null)) {
|
|
107
|
+
nullable = true;
|
|
108
|
+
schema = { ...schema, enum: schema.enum.filter((v) => v !== null) };
|
|
109
|
+
}
|
|
110
|
+
return { schema, nullable };
|
|
111
|
+
}
|
|
112
|
+
const scalar = (v) => v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';
|
|
113
|
+
/** `enum` (+ `x-enumNames`), `const`, or `oneOf` / `anyOf` of `{ const, title }` → options */
|
|
114
|
+
function readOptions(s, reader, path, stack) {
|
|
115
|
+
const labels = s['x-enumNames'] ?? s.enumNames ?? s['x-enum-varnames'];
|
|
116
|
+
if (Array.isArray(s.enum)) {
|
|
117
|
+
return s.enum.filter(scalar).map((value, i) => {
|
|
118
|
+
const option = { value };
|
|
119
|
+
if (typeof labels?.[i] === 'string')
|
|
120
|
+
option.label = labels[i];
|
|
121
|
+
return option;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
for (const key of ['oneOf', 'anyOf']) {
|
|
125
|
+
const list = s[key];
|
|
126
|
+
if (!Array.isArray(list) || !list.length)
|
|
127
|
+
continue;
|
|
128
|
+
const members = list.map((m) => resolve(m, reader, path, stack).schema);
|
|
129
|
+
if (!members.every((m) => 'const' in m || (Array.isArray(m.enum) && m.enum.length === 1)))
|
|
130
|
+
continue;
|
|
131
|
+
return members.map((m) => {
|
|
132
|
+
const value = ('const' in m ? m.const : m.enum[0]);
|
|
133
|
+
const option = { value };
|
|
134
|
+
if (typeof m.title === 'string')
|
|
135
|
+
option.label = m.title;
|
|
136
|
+
else if (typeof m.description === 'string')
|
|
137
|
+
option.label = m.description;
|
|
138
|
+
return option;
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
function typeOf(s) {
|
|
144
|
+
if (typeof s.type === 'string')
|
|
145
|
+
return s.type;
|
|
146
|
+
if (s.properties)
|
|
147
|
+
return 'object';
|
|
148
|
+
if (s.items || s.prefixItems)
|
|
149
|
+
return 'array';
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
function readConstraints(s, type) {
|
|
153
|
+
const c = {};
|
|
154
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) && !NOT_A_BOUND.has(v) ? v : undefined);
|
|
155
|
+
if (type === 'string' || type === 'text') {
|
|
156
|
+
if (num(s.minLength) !== undefined)
|
|
157
|
+
c.minLength = s.minLength;
|
|
158
|
+
if (num(s.maxLength) !== undefined)
|
|
159
|
+
c.maxLength = s.maxLength;
|
|
160
|
+
if (typeof s.pattern === 'string')
|
|
161
|
+
c.pattern = s.pattern;
|
|
162
|
+
}
|
|
163
|
+
if (type === 'integer' || type === 'number') {
|
|
164
|
+
// draft-04 / OpenAPI 3.0: boolean `exclusiveMinimum` modifies `minimum`
|
|
165
|
+
if (num(s.minimum) !== undefined) {
|
|
166
|
+
if (s.exclusiveMinimum === true)
|
|
167
|
+
c.exclusiveMin = s.minimum;
|
|
168
|
+
else
|
|
169
|
+
c.min = s.minimum;
|
|
170
|
+
}
|
|
171
|
+
if (num(s.maximum) !== undefined) {
|
|
172
|
+
if (s.exclusiveMaximum === true)
|
|
173
|
+
c.exclusiveMax = s.maximum;
|
|
174
|
+
else
|
|
175
|
+
c.max = s.maximum;
|
|
176
|
+
}
|
|
177
|
+
if (num(s.exclusiveMinimum) !== undefined) {
|
|
178
|
+
// Integers: `> 0` is `>= 1` — keeps Formo's min_value messages
|
|
179
|
+
if (type === 'integer')
|
|
180
|
+
c.min = Math.floor(s.exclusiveMinimum) + 1;
|
|
181
|
+
else
|
|
182
|
+
c.exclusiveMin = s.exclusiveMinimum;
|
|
183
|
+
}
|
|
184
|
+
if (num(s.exclusiveMaximum) !== undefined) {
|
|
185
|
+
if (type === 'integer')
|
|
186
|
+
c.max = Math.ceil(s.exclusiveMaximum) - 1;
|
|
187
|
+
else
|
|
188
|
+
c.exclusiveMax = s.exclusiveMaximum;
|
|
189
|
+
}
|
|
190
|
+
if (num(s.multipleOf) !== undefined)
|
|
191
|
+
c.step = s.multipleOf;
|
|
192
|
+
}
|
|
193
|
+
if (type === 'file') {
|
|
194
|
+
if (typeof s.contentMediaType === 'string')
|
|
195
|
+
c.mimeTypes = s.contentMediaType.split(',').map((m) => m.trim());
|
|
196
|
+
}
|
|
197
|
+
return c;
|
|
198
|
+
}
|
|
199
|
+
function withConstraints(field, c) {
|
|
200
|
+
if (Object.keys(c).length)
|
|
201
|
+
field.constraints = { ...field.constraints, ...c };
|
|
202
|
+
return field;
|
|
203
|
+
}
|
|
204
|
+
function readField(name, raw, required, reader, path, parentStack) {
|
|
205
|
+
const { schema: resolved, stack } = resolve(raw, reader, path, parentStack);
|
|
206
|
+
const { schema: s, nullable } = unwrapNullable(resolved, reader, path, stack);
|
|
207
|
+
const field = { type: 'unknown' };
|
|
208
|
+
if (name !== undefined)
|
|
209
|
+
field.name = name;
|
|
210
|
+
for (const key of UNSUPPORTED) {
|
|
211
|
+
if (key in s)
|
|
212
|
+
reader.warn({ path, code: 'unsupported-keyword', message: `\`${key}\` isn't supported — ignored` });
|
|
213
|
+
}
|
|
214
|
+
if (typeof s.title === 'string')
|
|
215
|
+
field.label = s.title;
|
|
216
|
+
if (typeof s.description === 'string')
|
|
217
|
+
field.description = s.description;
|
|
218
|
+
if (Array.isArray(s.examples) && typeof s.examples[0] === 'string')
|
|
219
|
+
field.placeholder = s.examples[0];
|
|
220
|
+
else if (typeof s.example === 'string')
|
|
221
|
+
field.placeholder = s.example;
|
|
222
|
+
if ('default' in s)
|
|
223
|
+
field.default = s.default;
|
|
224
|
+
if (s.readOnly === true)
|
|
225
|
+
field.readOnly = true;
|
|
226
|
+
if (s.writeOnly === true)
|
|
227
|
+
field.writeOnly = true;
|
|
228
|
+
if (required)
|
|
229
|
+
field.required = true;
|
|
230
|
+
if (nullable)
|
|
231
|
+
field.nullable = true;
|
|
232
|
+
const ui = s['x-formo'] ?? s.formo;
|
|
233
|
+
if (isPlainObject(ui))
|
|
234
|
+
field.ui = { ...ui };
|
|
235
|
+
if (s.__recursive)
|
|
236
|
+
return field;
|
|
237
|
+
const options = readOptions(s, reader, path, stack);
|
|
238
|
+
let type = typeOf(s);
|
|
239
|
+
if (!type && options?.length)
|
|
240
|
+
type = typeof options[0].value === 'number' ? 'number' : 'string';
|
|
241
|
+
// A single constant true checkbox: "must be accepted"
|
|
242
|
+
if (type === 'boolean' && (s.const === true || (options?.length === 1 && options[0].value === true))) {
|
|
243
|
+
field.type = 'boolean';
|
|
244
|
+
field.constraints = { accepted: true };
|
|
245
|
+
return field;
|
|
246
|
+
}
|
|
247
|
+
if (options && type !== 'array' && type !== 'object') {
|
|
248
|
+
field.type = 'enum';
|
|
249
|
+
field.options = options;
|
|
250
|
+
return field;
|
|
251
|
+
}
|
|
252
|
+
switch (type) {
|
|
253
|
+
case 'string': {
|
|
254
|
+
const mapped = typeof s.format === 'string' ? FORMATS[s.format] : undefined;
|
|
255
|
+
field.type = mapped?.type ?? 'string';
|
|
256
|
+
if (mapped?.format)
|
|
257
|
+
field.format = mapped.format;
|
|
258
|
+
else if (!mapped && typeof s.format === 'string')
|
|
259
|
+
field.format = s.format;
|
|
260
|
+
if (s.contentEncoding === 'binary' || (s.contentEncoding === 'base64' && typeof s.contentMediaType === 'string'))
|
|
261
|
+
field.type = 'file';
|
|
262
|
+
const c = readConstraints(s, field.type);
|
|
263
|
+
// A known format already validates the shape: its pattern (Zod emits one for emails…) would duplicate it
|
|
264
|
+
if (mapped && c.pattern)
|
|
265
|
+
delete c.pattern;
|
|
266
|
+
return withConstraints(field, c);
|
|
267
|
+
}
|
|
268
|
+
case 'integer':
|
|
269
|
+
case 'number':
|
|
270
|
+
field.type = type;
|
|
271
|
+
return withConstraints(field, readConstraints(s, type));
|
|
272
|
+
case 'boolean':
|
|
273
|
+
field.type = 'boolean';
|
|
274
|
+
return field;
|
|
275
|
+
case 'object': {
|
|
276
|
+
field.type = 'object';
|
|
277
|
+
field.fields = readProperties(s, reader, path, stack);
|
|
278
|
+
return field;
|
|
279
|
+
}
|
|
280
|
+
case 'array': {
|
|
281
|
+
field.type = 'array';
|
|
282
|
+
if (Array.isArray(s.items) || s.prefixItems) {
|
|
283
|
+
reader.warn({ path, code: 'unsupported-keyword', message: 'tuples (`prefixItems` / `items: [...]`) are not supported' });
|
|
284
|
+
field.items = { type: 'unknown' };
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
field.items = readField(undefined, s.items ?? {}, false, reader, `${path}.*`, stack);
|
|
288
|
+
}
|
|
289
|
+
const c = {};
|
|
290
|
+
if (typeof s.minItems === 'number')
|
|
291
|
+
c.minItems = s.minItems;
|
|
292
|
+
if (typeof s.maxItems === 'number')
|
|
293
|
+
c.maxItems = s.maxItems;
|
|
294
|
+
return withConstraints(field, c);
|
|
295
|
+
}
|
|
296
|
+
default:
|
|
297
|
+
if (Array.isArray(s.type))
|
|
298
|
+
reader.warn({ path, code: 'unsupported-type', message: `several types (${s.type.join(', ')}) — read as "unknown"` });
|
|
299
|
+
else if (s.oneOf || s.anyOf)
|
|
300
|
+
reader.warn({ path, code: 'unsupported-keyword', message: '`oneOf` / `anyOf` of different shapes — read as "unknown"' });
|
|
301
|
+
return field;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function readProperties(s, reader, prefix, stack) {
|
|
305
|
+
const properties = isPlainObject(s.properties) ? s.properties : {};
|
|
306
|
+
const required = new Set(Array.isArray(s.required) ? s.required : []);
|
|
307
|
+
const fields = [];
|
|
308
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
309
|
+
const path = prefix ? `${prefix}.${name}` : name;
|
|
310
|
+
if (/[.*\s[\]]/.test(name)) {
|
|
311
|
+
reader.warn({ path, code: 'invalid-name', message: 'property names with dots, spaces, brackets or * can\'t be form fields — skipped' });
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
fields.push(readField(name, property, required.has(name), reader, path, stack));
|
|
315
|
+
}
|
|
316
|
+
// { dependentRequired: { credit_card: ['billing_address'] } } → billing_address: required_with:credit_card
|
|
317
|
+
const dependent = { ...(isPlainObject(s.dependencies) ? s.dependencies : {}), ...(isPlainObject(s.dependentRequired) ? s.dependentRequired : {}) };
|
|
318
|
+
for (const [trigger, targets] of Object.entries(dependent)) {
|
|
319
|
+
if (!Array.isArray(targets))
|
|
320
|
+
continue;
|
|
321
|
+
for (const target of targets) {
|
|
322
|
+
const field = fields.find((f) => f.name === target);
|
|
323
|
+
if (!field)
|
|
324
|
+
continue;
|
|
325
|
+
const rule = `required_with:${trigger}`;
|
|
326
|
+
field.rules = [...(field.rules ?? []), rule];
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return fields;
|
|
330
|
+
}
|
|
331
|
+
export function fromJsonSchema(schema, options = {}) {
|
|
332
|
+
const refRoot = options.document ?? (isPlainObject(schema) ? schema : {});
|
|
333
|
+
const reader = { refRoot, warn: options.onWarning ?? consoleWarning };
|
|
334
|
+
let root = schema;
|
|
335
|
+
if (options.root) {
|
|
336
|
+
const ref = options.root.startsWith('#') ? options.root : ['$defs', 'definitions'].map((k) => `#/${k}/${options.root}`).find((r) => pointer(refRoot, r));
|
|
337
|
+
root = ref ? { $ref: ref } : {};
|
|
338
|
+
if (!ref)
|
|
339
|
+
reader.warn({ path: '', code: 'unresolved-ref', message: `no "${options.root}" in $defs / definitions` });
|
|
340
|
+
}
|
|
341
|
+
const { schema: resolved, stack } = resolve(root, reader, '', []);
|
|
342
|
+
const { schema: s } = unwrapNullable(resolved, reader, '', stack);
|
|
343
|
+
if (typeOf(s) !== 'object')
|
|
344
|
+
throw new Error('[formo] fromJsonSchema: the root schema must describe an object');
|
|
345
|
+
const model = { version: MODEL_VERSION, fields: readProperties(s, reader, '', stack) };
|
|
346
|
+
if (options.name)
|
|
347
|
+
model.name = options.name;
|
|
348
|
+
if (typeof s.title === 'string')
|
|
349
|
+
model.label = s.title;
|
|
350
|
+
return model;
|
|
351
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type FormoModel, type WarningHandler } from './ir';
|
|
2
|
+
/**
|
|
3
|
+
* Laravel validation rules → Formo model. Pass what a FormRequest has — through
|
|
4
|
+
* Inertia props or a schema endpoint — and get the fields, their types, labels
|
|
5
|
+
* and client-side rules:
|
|
6
|
+
*
|
|
7
|
+
* ```php
|
|
8
|
+
* // In a controller (Inertia): rules as strings — Rule::in() & co. are Stringable
|
|
9
|
+
* return Inertia::render('Users/Edit', [
|
|
10
|
+
* 'user' => $user,
|
|
11
|
+
* 'userForm' => FormoRules::from(UpdateUserRequest::createFrom(request())), // see docs/schema.md
|
|
12
|
+
* ]);
|
|
13
|
+
* ```
|
|
14
|
+
* ```ts
|
|
15
|
+
* const model = fromLaravel(props.userForm) // { rules, attributes, messages }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* - Types come from the rules: `string`, `integer`, `numeric`, `boolean`, `date`,
|
|
19
|
+
* `email`, `file` / `image` / `mimes`, `array`, `in:`, `exists:` on `*_id` (a relation)…
|
|
20
|
+
* - `min` / `max` / `between` / `size` follow the field's type, like Laravel
|
|
21
|
+
* (length, value, item count, or kilobytes)
|
|
22
|
+
* - `address.street` → a subform, `phones.*.number` → repeatable rows, `tags.*` with `in:` → checkboxes
|
|
23
|
+
* - `confirmed` adds the `password_confirmation` field Laravel expects
|
|
24
|
+
* - `required_if` / `required_with`… / `exclude_if`, `same`, `different`, `gt`… run client-side
|
|
25
|
+
* - `unique`, `exists`, `current_password`… are server-only: listed in `serverRules`, never run
|
|
26
|
+
* - `attributes()` become labels, `messages()` error messages (Laravel placeholders work)
|
|
27
|
+
*/
|
|
28
|
+
export interface LaravelRulesInput {
|
|
29
|
+
/** `rules()`: `{ email: 'required|email|max:255', 'phones.*.number': ['required', 'string'] }` */
|
|
30
|
+
rules: Record<string, string | unknown[]>;
|
|
31
|
+
/** `attributes()`: labels — `{ email: 'e-mail address', 'phones.*.number': 'number' }` */
|
|
32
|
+
attributes?: Record<string, string>;
|
|
33
|
+
/** `messages()`: `{ 'email.required': 'We need your email', 'min.string': '…' }` */
|
|
34
|
+
messages?: Record<string, string>;
|
|
35
|
+
/** Suggested form alias */
|
|
36
|
+
name?: string;
|
|
37
|
+
label?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface FromLaravelOptions {
|
|
40
|
+
/**
|
|
41
|
+
* Custom rules your app also registers client-side (`createFormo({ rules })`):
|
|
42
|
+
* passed through as they are instead of being reported as server-only
|
|
43
|
+
*/
|
|
44
|
+
clientRules?: string[];
|
|
45
|
+
onWarning?: WarningHandler;
|
|
46
|
+
}
|
|
47
|
+
interface LaravelRule {
|
|
48
|
+
name: string;
|
|
49
|
+
params: string[];
|
|
50
|
+
raw: string;
|
|
51
|
+
}
|
|
52
|
+
/** `a,"b, c",d` → ['a', 'b, c', 'd'] (Laravel reads params with str_getcsv; Rule::in() quotes its values) */
|
|
53
|
+
export declare function parseCsv(input: string): string[];
|
|
54
|
+
/** `'min:3'` → `{ name: 'min', params: ['3'] }` (regex patterns keep their commas) */
|
|
55
|
+
export declare function parseLaravelRule(text: string): LaravelRule;
|
|
56
|
+
export declare function fromLaravel(input: LaravelRulesInput, options?: FromLaravelOptions): FormoModel;
|
|
57
|
+
export {};
|