ovr 6.1.0 → 6.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/dist/LICENSE.md +2 -0
- package/dist/app/index.d.ts.map +1 -1
- package/dist/app/index.js +13 -9
- package/dist/context/index.d.ts +33 -9
- package/dist/context/index.d.ts.map +1 -1
- package/dist/context/index.js +61 -17
- package/dist/cookie/index.d.ts +1 -1
- package/dist/cookie/index.d.ts.map +1 -1
- package/dist/cookie/index.js +2 -2
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/middleware/index.d.ts +12 -3
- package/dist/middleware/index.d.ts.map +1 -1
- package/dist/multipart/index.d.ts +5 -0
- package/dist/multipart/index.d.ts.map +1 -1
- package/dist/multipart/index.js +20 -22
- package/dist/render/index.d.ts +1 -0
- package/dist/render/index.d.ts.map +1 -1
- package/dist/render/index.js +6 -4
- package/dist/route/index.d.ts +143 -42
- package/dist/route/index.d.ts.map +1 -1
- package/dist/route/index.js +94 -42
- package/dist/schema/index.d.ts +1286 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +1321 -0
- package/dist/trie/index.d.ts.map +1 -1
- package/dist/trie/index.js +8 -2
- package/dist/util/index.d.ts +113 -19
- package/dist/util/index.d.ts.map +1 -1
- package/dist/util/index.js +111 -35
- package/package.json +4 -1
- package/src/app/index.ts +13 -12
- package/src/context/index.ts +104 -25
- package/src/cookie/index.ts +3 -3
- package/src/index.ts +4 -3
- package/src/middleware/index.ts +19 -8
- package/src/multipart/index.ts +23 -24
- package/src/render/index.ts +7 -4
- package/src/route/index.ts +336 -95
- package/src/schema/index.ts +2794 -0
- package/src/trie/index.ts +12 -2
- package/src/util/index.ts +142 -36
|
@@ -0,0 +1,1321 @@
|
|
|
1
|
+
import { Fragment, jsx } from "../jsx/index.js";
|
|
2
|
+
import { Multipart } from "../multipart/index.js";
|
|
3
|
+
import { Checksum, Codec, Size } from "../util/index.js";
|
|
4
|
+
/** Shared runtime shape operations used by object and form schema methods. */
|
|
5
|
+
class ShapeUtil {
|
|
6
|
+
/**
|
|
7
|
+
* Merge two record-like shapes where `extra` keys override `shape`.
|
|
8
|
+
*
|
|
9
|
+
* @template S Base shape
|
|
10
|
+
* @template E Extra shape
|
|
11
|
+
* @param shape Base shape
|
|
12
|
+
* @param extra Extra values to merge
|
|
13
|
+
* @returns Merged shape
|
|
14
|
+
*/
|
|
15
|
+
static extend(shape, extra) {
|
|
16
|
+
return { ...shape, ...extra };
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Pick keys from a record-like shape.
|
|
20
|
+
*
|
|
21
|
+
* @template S Shape
|
|
22
|
+
* @template N Selected key names
|
|
23
|
+
* @param shape Source shape
|
|
24
|
+
* @param names Non-empty list of keys to include
|
|
25
|
+
* @returns Picked shape
|
|
26
|
+
*/
|
|
27
|
+
static pick(shape, names) {
|
|
28
|
+
const out = {};
|
|
29
|
+
for (const name of names) {
|
|
30
|
+
if (name in shape)
|
|
31
|
+
out[name] = shape[name];
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Omit keys from a record-like shape.
|
|
37
|
+
*
|
|
38
|
+
* @template S Shape
|
|
39
|
+
* @template N Removed key names
|
|
40
|
+
* @param shape Source shape
|
|
41
|
+
* @param names Non-empty list of keys to remove
|
|
42
|
+
* @returns Omitted shape
|
|
43
|
+
*/
|
|
44
|
+
static omit(shape, names) {
|
|
45
|
+
const remove = new Set(names);
|
|
46
|
+
const out = {};
|
|
47
|
+
for (const [name, value] of Object.entries(shape)) {
|
|
48
|
+
if (!remove.has(name))
|
|
49
|
+
out[name] = value;
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Minimal schema validator geared around parsing form data like
|
|
56
|
+
* multipart `FormData` and `URLSearchParams`.
|
|
57
|
+
*
|
|
58
|
+
* Implements Standard Schema v1 via the `~standard` property (sync validate).
|
|
59
|
+
*
|
|
60
|
+
* @template Output Output type after parsing
|
|
61
|
+
*/
|
|
62
|
+
export class Schema {
|
|
63
|
+
/** Email regular expression */
|
|
64
|
+
static #emailRegex = /^(?!\.)(?!.*\.\.)([a-z0-9_'+\-\.]*)[a-z0-9_'+\-]@([a-z0-9][a-z0-9\-]*\.)+[a-z]{2,}$/i;
|
|
65
|
+
/** Validation issue produced during parsing. */
|
|
66
|
+
static Issue = class Issue extends Error {
|
|
67
|
+
/** Expected type/value. */
|
|
68
|
+
expected;
|
|
69
|
+
/** Path to the invalid value. */
|
|
70
|
+
path;
|
|
71
|
+
/**
|
|
72
|
+
* @param expected Expected value
|
|
73
|
+
* @param path Path to the invalid value
|
|
74
|
+
* @param message Issue message
|
|
75
|
+
*/
|
|
76
|
+
constructor(expected, path, message) {
|
|
77
|
+
const exp = String(expected);
|
|
78
|
+
super(message ?? `Expected ${exp}`);
|
|
79
|
+
this.name = "Schema.Issue";
|
|
80
|
+
this.expected = exp;
|
|
81
|
+
this.path = path;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* @returns `Schema.Issue(path): message`
|
|
85
|
+
*/
|
|
86
|
+
toString() {
|
|
87
|
+
let path = "";
|
|
88
|
+
for (const segment of this.path) {
|
|
89
|
+
path +=
|
|
90
|
+
typeof segment === "number"
|
|
91
|
+
? `[${segment}]`
|
|
92
|
+
: `${path ? "." : path}${segment}`;
|
|
93
|
+
}
|
|
94
|
+
return `${this.name}${path ? `(${path})` : ""}: ${this.message}`;
|
|
95
|
+
}
|
|
96
|
+
toJSON() {
|
|
97
|
+
return { ...this, message: this.message };
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
/** AggregateIssue containing at least one Schema.Issue */
|
|
101
|
+
static AggregateIssue = class AggregateIssue extends AggregateError {
|
|
102
|
+
/** Non-empty tuple of issues */
|
|
103
|
+
issues;
|
|
104
|
+
/** User submitted / sanitized values */
|
|
105
|
+
values;
|
|
106
|
+
/**
|
|
107
|
+
* Create a new AggregateIssue.
|
|
108
|
+
*
|
|
109
|
+
* Coerces issues into a non-empty tuple.
|
|
110
|
+
*
|
|
111
|
+
* @param issues Issues
|
|
112
|
+
* @param values Received values
|
|
113
|
+
*/
|
|
114
|
+
constructor([first, ...rest], values) {
|
|
115
|
+
if (!first)
|
|
116
|
+
throw new TypeError("AggregateIssue must have an issue.");
|
|
117
|
+
const issues = [first, ...rest];
|
|
118
|
+
const name = "Schema.AggregateIssue";
|
|
119
|
+
const count = issues.length;
|
|
120
|
+
super(issues, `${name}(${count})\n${issues.join("\n")}`);
|
|
121
|
+
this.name = name;
|
|
122
|
+
this.issues = issues;
|
|
123
|
+
this.values = values;
|
|
124
|
+
}
|
|
125
|
+
toString() {
|
|
126
|
+
// prevents name being in the default twice since it's
|
|
127
|
+
// already in the message
|
|
128
|
+
return this.message;
|
|
129
|
+
}
|
|
130
|
+
toJSON() {
|
|
131
|
+
return { ...this, message: this.message };
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
"~standard" = {
|
|
135
|
+
version: 1,
|
|
136
|
+
vendor: "ovr",
|
|
137
|
+
validate: (value) => {
|
|
138
|
+
const result = this.parse(value);
|
|
139
|
+
return result.issues ? result : { value: result.data };
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
/**
|
|
143
|
+
* Parse and validate an unknown value.
|
|
144
|
+
*
|
|
145
|
+
* @param value Unknown value to parse
|
|
146
|
+
* @param path Optional issue path (internal)
|
|
147
|
+
* @returns Parse result containing data or issues
|
|
148
|
+
*/
|
|
149
|
+
parse;
|
|
150
|
+
/**
|
|
151
|
+
* Construct a new schema - used internally.
|
|
152
|
+
*
|
|
153
|
+
* Use static methods on `Schema` to make a new schema.
|
|
154
|
+
*
|
|
155
|
+
* @param parse Parse function that validates and transforms input
|
|
156
|
+
*/
|
|
157
|
+
constructor(parse) {
|
|
158
|
+
this.parse = (value, path = []) => parse(value, path);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* @internal Required for Field to override and return a `Field` instance
|
|
162
|
+
* from the chained methods instead of a `Schema`
|
|
163
|
+
* @template O Output type of the new schema
|
|
164
|
+
* @param parse Parse function that validates and transforms input
|
|
165
|
+
* @returns New schema instance based on the current instance
|
|
166
|
+
*/
|
|
167
|
+
derive(parse) {
|
|
168
|
+
return new Schema(parse);
|
|
169
|
+
}
|
|
170
|
+
optional() {
|
|
171
|
+
return this.derive((v, path) => {
|
|
172
|
+
if (v === undefined)
|
|
173
|
+
return { data: v };
|
|
174
|
+
return this.parse(v, path);
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
nullable() {
|
|
178
|
+
return this.derive((v, path) => {
|
|
179
|
+
if (v === null)
|
|
180
|
+
return { data: v };
|
|
181
|
+
return this.parse(v, path);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
nullish() {
|
|
185
|
+
return this.derive((v, path) => {
|
|
186
|
+
if (v == null)
|
|
187
|
+
return { data: v };
|
|
188
|
+
return this.parse(v, path);
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
default(value) {
|
|
192
|
+
return this.derive((v, path) => {
|
|
193
|
+
if (v === undefined)
|
|
194
|
+
return { data: value };
|
|
195
|
+
return this.parse(v, path);
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
preprocess(fn) {
|
|
199
|
+
return this.derive((v, path) => this.parse(fn(v), path));
|
|
200
|
+
}
|
|
201
|
+
transform(fn) {
|
|
202
|
+
return this.derive((v, path) => {
|
|
203
|
+
const out = this.parse(v, path);
|
|
204
|
+
return out.issues ? out : { data: fn(out.data) };
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
pipe(next) {
|
|
208
|
+
return this.derive((v, path) => {
|
|
209
|
+
const result = this.parse(v, path);
|
|
210
|
+
return result.issues ? result : next.parse(result.data, path);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
json(schema, message) {
|
|
214
|
+
return this.derive((v, path) => {
|
|
215
|
+
const result = this.parse(v, path);
|
|
216
|
+
if (result.issues)
|
|
217
|
+
return result;
|
|
218
|
+
let data;
|
|
219
|
+
try {
|
|
220
|
+
data = JSON.parse(result.data);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return new Schema.AggregateIssue([
|
|
224
|
+
new Schema.Issue("JSON", path, message),
|
|
225
|
+
]);
|
|
226
|
+
}
|
|
227
|
+
return schema.parse(data, path);
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
email(message = "Expected email") {
|
|
231
|
+
return this.refine((s) => Schema.#emailRegex.test(s), message);
|
|
232
|
+
}
|
|
233
|
+
url(message = "Expected URL") {
|
|
234
|
+
return this.refine(URL.canParse, message);
|
|
235
|
+
}
|
|
236
|
+
int(message = "Expected integer") {
|
|
237
|
+
return this.refine(Number.isSafeInteger, message);
|
|
238
|
+
}
|
|
239
|
+
min(value, message = `Expected minimum ${String(value)}`) {
|
|
240
|
+
return this.refine((next) => {
|
|
241
|
+
return typeof next === "string"
|
|
242
|
+
? next.length >= value
|
|
243
|
+
: next >= value;
|
|
244
|
+
}, message);
|
|
245
|
+
}
|
|
246
|
+
max(value, message = `Expected maximum ${String(value)}`) {
|
|
247
|
+
return this.refine((next) => {
|
|
248
|
+
return typeof next === "string"
|
|
249
|
+
? next.length <= value
|
|
250
|
+
: next <= value;
|
|
251
|
+
}, message);
|
|
252
|
+
}
|
|
253
|
+
refine(check, message) {
|
|
254
|
+
return this.derive((v, path) => {
|
|
255
|
+
const out = this.parse(v, path);
|
|
256
|
+
return out.issues || check(out.data)
|
|
257
|
+
? out
|
|
258
|
+
: new Schema.AggregateIssue([
|
|
259
|
+
new Schema.Issue("refine", path, message),
|
|
260
|
+
]);
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Accepts any value and presents the data as `unknown`.
|
|
265
|
+
*
|
|
266
|
+
* @returns Unknown schema
|
|
267
|
+
*/
|
|
268
|
+
static unknown() {
|
|
269
|
+
return new Schema((v) => ({ data: v }));
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Validate an input is a string.
|
|
273
|
+
*
|
|
274
|
+
* @param message Issue message when invalid
|
|
275
|
+
* @returns String schema
|
|
276
|
+
*/
|
|
277
|
+
static string(message) {
|
|
278
|
+
return new Schema((v, path) => {
|
|
279
|
+
return typeof v === "string"
|
|
280
|
+
? { data: v }
|
|
281
|
+
: new Schema.AggregateIssue([
|
|
282
|
+
new Schema.Issue("string", path, message),
|
|
283
|
+
]);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Validate an input is a `true` or `false` boolean.
|
|
288
|
+
*
|
|
289
|
+
* @param message Issue message when invalid
|
|
290
|
+
* @returns Boolean schema
|
|
291
|
+
*/
|
|
292
|
+
static boolean(message) {
|
|
293
|
+
return new Schema((v, path) => {
|
|
294
|
+
return typeof v === "boolean"
|
|
295
|
+
? { data: v }
|
|
296
|
+
: new Schema.AggregateIssue([
|
|
297
|
+
new Schema.Issue("boolean", path, message),
|
|
298
|
+
]);
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Validate an input is a number.
|
|
303
|
+
*
|
|
304
|
+
* Rejects non-finite values like `NaN` and `Infinity`.
|
|
305
|
+
*
|
|
306
|
+
* @param message Issue message when invalid
|
|
307
|
+
* @returns Number schema
|
|
308
|
+
*/
|
|
309
|
+
static number(message) {
|
|
310
|
+
return new Schema((v, path) => {
|
|
311
|
+
return Number.isFinite(v) // isFinite checks type
|
|
312
|
+
? { data: v }
|
|
313
|
+
: new Schema.AggregateIssue([
|
|
314
|
+
new Schema.Issue("number", path, message),
|
|
315
|
+
]);
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Validate an input is a big integer.
|
|
320
|
+
*
|
|
321
|
+
* @param message Issue message when invalid
|
|
322
|
+
* @returns Big integer schema
|
|
323
|
+
*/
|
|
324
|
+
static bigint(message) {
|
|
325
|
+
return new Schema((v, path) => {
|
|
326
|
+
return typeof v === "bigint"
|
|
327
|
+
? { data: v }
|
|
328
|
+
: new Schema.AggregateIssue([
|
|
329
|
+
new Schema.Issue("bigint", path, message),
|
|
330
|
+
]);
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* @template L Literal type
|
|
335
|
+
* @param literal Exact value to match
|
|
336
|
+
* @param message Issue message when invalid
|
|
337
|
+
* @returns Literal schema
|
|
338
|
+
*/
|
|
339
|
+
static literal(literal, message) {
|
|
340
|
+
return new Schema((v, path) => {
|
|
341
|
+
return v === literal
|
|
342
|
+
? { data: literal }
|
|
343
|
+
: new Schema.AggregateIssue([new Schema.Issue(literal, path, message)]);
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Validates that the input is strictly equal (`===`) to one of the allowed
|
|
348
|
+
* values.
|
|
349
|
+
*
|
|
350
|
+
* @template A Allowed type
|
|
351
|
+
* @param allowed Allowed values
|
|
352
|
+
* @param message Issue message when invalid
|
|
353
|
+
* @returns Enum schema
|
|
354
|
+
*/
|
|
355
|
+
static enum(allowed, message) {
|
|
356
|
+
return new Schema((v, path) => {
|
|
357
|
+
for (const a of allowed) {
|
|
358
|
+
if (v === a)
|
|
359
|
+
return { data: a };
|
|
360
|
+
}
|
|
361
|
+
return new Schema.AggregateIssue([
|
|
362
|
+
new Schema.Issue(allowed.map((v) => JSON.stringify(v)).join(" | "), path, message),
|
|
363
|
+
]);
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Tries each schema in order and returns the first successfully parsed result.
|
|
368
|
+
*
|
|
369
|
+
* @template S Schemas type
|
|
370
|
+
* @param schemas Schemas to try in order
|
|
371
|
+
* @returns Union schema
|
|
372
|
+
*/
|
|
373
|
+
static union(schemas) {
|
|
374
|
+
return new Schema((v, path) => {
|
|
375
|
+
const issues = [];
|
|
376
|
+
for (const schema of schemas) {
|
|
377
|
+
const result = schema.parse(v, path);
|
|
378
|
+
if (!result.issues) {
|
|
379
|
+
// return as soon as one passes
|
|
380
|
+
return result;
|
|
381
|
+
}
|
|
382
|
+
issues.push(...result.issues);
|
|
383
|
+
}
|
|
384
|
+
return new Schema.AggregateIssue(issues);
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Validates an input is an instance of the constructor.
|
|
389
|
+
*
|
|
390
|
+
* @template O Output type
|
|
391
|
+
* @param constructor Constructor to validate the input is an instance of
|
|
392
|
+
* @param message Issue message when invalid
|
|
393
|
+
* @returns Validated instance
|
|
394
|
+
*/
|
|
395
|
+
static instance(constructor, message) {
|
|
396
|
+
return new Schema((v, path) => v instanceof constructor
|
|
397
|
+
? { data: v }
|
|
398
|
+
: new Schema.AggregateIssue([
|
|
399
|
+
new Schema.Issue(constructor.name, path, message),
|
|
400
|
+
]));
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Validates that the input is an array and parses each item.
|
|
404
|
+
*
|
|
405
|
+
* @template O Output type
|
|
406
|
+
* @param schema Schema for each array item
|
|
407
|
+
* @param message Issue message when invalid
|
|
408
|
+
* @returns Array schema
|
|
409
|
+
*/
|
|
410
|
+
static array(schema, message) {
|
|
411
|
+
return new Schema((v, path) => {
|
|
412
|
+
if (!Array.isArray(v)) {
|
|
413
|
+
return new Schema.AggregateIssue([
|
|
414
|
+
new Schema.Issue("Array", path, message),
|
|
415
|
+
]);
|
|
416
|
+
}
|
|
417
|
+
const data = [];
|
|
418
|
+
const issues = [];
|
|
419
|
+
for (let i = 0; i < v.length; i++) {
|
|
420
|
+
const result = schema.parse(v[i], [...path, i]);
|
|
421
|
+
if (result.issues) {
|
|
422
|
+
issues.push(...result.issues);
|
|
423
|
+
}
|
|
424
|
+
else {
|
|
425
|
+
data.push(result.data);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (issues.length)
|
|
429
|
+
return new Schema.AggregateIssue(issues);
|
|
430
|
+
return { data };
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Validates each key in the shape and returns a new object of parsed outputs.
|
|
435
|
+
*
|
|
436
|
+
* @template S Object shape type
|
|
437
|
+
* @param shape Object shape with schemas for each key
|
|
438
|
+
* @returns Object schema
|
|
439
|
+
*/
|
|
440
|
+
static object(shape = {}) {
|
|
441
|
+
return new ObjectSchema(shape, "strip");
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Runtime object schema that validates plain objects and supports shape helpers.
|
|
446
|
+
*
|
|
447
|
+
* @template Shape Object shape type
|
|
448
|
+
* @template Mode Object parsing mode
|
|
449
|
+
*/
|
|
450
|
+
class ObjectSchema extends Schema {
|
|
451
|
+
/** Object shape definitions. */
|
|
452
|
+
shape;
|
|
453
|
+
/** Object parsing mode. */
|
|
454
|
+
#mode;
|
|
455
|
+
/**
|
|
456
|
+
* Create a new object schema validator.
|
|
457
|
+
*
|
|
458
|
+
* @param shape Object shape
|
|
459
|
+
* @param mode Object parsing mode
|
|
460
|
+
*/
|
|
461
|
+
constructor(shape, mode = "strip") {
|
|
462
|
+
super((value, path) => {
|
|
463
|
+
if (value == null || typeof value !== "object" || Array.isArray(value)) {
|
|
464
|
+
return new Schema.AggregateIssue([new Schema.Issue("Object", path)]);
|
|
465
|
+
}
|
|
466
|
+
const data = {};
|
|
467
|
+
const issues = [];
|
|
468
|
+
for (const [name, schema] of Object.entries(shape)) {
|
|
469
|
+
const result = schema.parse(value[name], [
|
|
470
|
+
...path,
|
|
471
|
+
name,
|
|
472
|
+
]);
|
|
473
|
+
if (result.issues) {
|
|
474
|
+
issues.push(...result.issues);
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
data[name] = result.data;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (mode !== "strip") {
|
|
481
|
+
const names = new Set(Object.keys(shape));
|
|
482
|
+
for (const [name, next] of Object.entries(value)) {
|
|
483
|
+
if (!names.has(name)) {
|
|
484
|
+
if (mode === "strict") {
|
|
485
|
+
issues.push(new Schema.Issue("never", [...path, name], "Unexpected key"));
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
data[name] = next;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
return issues.length
|
|
494
|
+
? new Schema.AggregateIssue(issues)
|
|
495
|
+
: { data };
|
|
496
|
+
});
|
|
497
|
+
this.shape = shape;
|
|
498
|
+
this.#mode = mode;
|
|
499
|
+
}
|
|
500
|
+
extend(extra) {
|
|
501
|
+
return new ObjectSchema(ShapeUtil.extend(this.shape, extra instanceof ObjectSchema ? extra.shape : extra), this.#mode);
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Keep only selected field names.
|
|
505
|
+
*
|
|
506
|
+
* @template N Selected key names
|
|
507
|
+
* @param names Non-empty list of key names to keep
|
|
508
|
+
* @returns New object schema with only selected keys
|
|
509
|
+
*/
|
|
510
|
+
pick(names) {
|
|
511
|
+
return new ObjectSchema(ShapeUtil.pick(this.shape, names), this.#mode);
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Remove selected field names.
|
|
515
|
+
*
|
|
516
|
+
* @template N Removed key names
|
|
517
|
+
* @param names Non-empty list of key names to remove
|
|
518
|
+
* @returns New object schema without selected keys
|
|
519
|
+
*/
|
|
520
|
+
omit(names) {
|
|
521
|
+
return new ObjectSchema(ShapeUtil.omit(this.shape, names), this.#mode);
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Reject unknown keys during parsing.
|
|
525
|
+
*
|
|
526
|
+
* @returns New object schema in strict mode
|
|
527
|
+
*/
|
|
528
|
+
strict() {
|
|
529
|
+
return new ObjectSchema(this.shape, "strict");
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Preserve unknown keys during parsing.
|
|
533
|
+
*
|
|
534
|
+
* @returns New object schema in loose mode
|
|
535
|
+
*/
|
|
536
|
+
loose() {
|
|
537
|
+
return new ObjectSchema(this.shape, "loose");
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Form schema with JSX rendering capabilities.
|
|
542
|
+
*
|
|
543
|
+
* Parses `FormData` or `URLSearchParams` and generates form field
|
|
544
|
+
* components.
|
|
545
|
+
*
|
|
546
|
+
* @template Shape Form field shape type
|
|
547
|
+
*/
|
|
548
|
+
export class Form {
|
|
549
|
+
/** Query param keys ordered as `[return, form]`. */
|
|
550
|
+
static params = ["_return", "_form"];
|
|
551
|
+
/** Maximum encoded state size in bytes. */
|
|
552
|
+
static #maxStateBytes = 4 * Size.kb;
|
|
553
|
+
/** Maximum serialized size for a single persisted value. */
|
|
554
|
+
static #maxValueChars = 512;
|
|
555
|
+
/** Schema used to validate persisted form values. */
|
|
556
|
+
static #valueSchema = Schema.union([
|
|
557
|
+
Schema.string(),
|
|
558
|
+
Schema.number(),
|
|
559
|
+
Schema.boolean(),
|
|
560
|
+
Schema.array(Schema.string()),
|
|
561
|
+
]);
|
|
562
|
+
/** Form id. */
|
|
563
|
+
#id;
|
|
564
|
+
/** Field definitions. */
|
|
565
|
+
shape;
|
|
566
|
+
/** Field names in definition order. */
|
|
567
|
+
names;
|
|
568
|
+
/** Maximum expected multipart parts derived from field cardinality. */
|
|
569
|
+
parts;
|
|
570
|
+
/**
|
|
571
|
+
* Create a new form schema validator.
|
|
572
|
+
*
|
|
573
|
+
* @param shape Form fields
|
|
574
|
+
*/
|
|
575
|
+
constructor(shape) {
|
|
576
|
+
this.shape = shape;
|
|
577
|
+
this.names = Object.keys(this.shape);
|
|
578
|
+
this.#id = Checksum.djb2(this.names.join());
|
|
579
|
+
this.parts = Object.values(this.shape).reduce((sum, field) => sum + field.parts, 0);
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Merge `extra` into the current fields.
|
|
583
|
+
*
|
|
584
|
+
* @template E Extra field shape type
|
|
585
|
+
* @param extra Extra fields or form schema to merge
|
|
586
|
+
* @returns New form schema with merged fields
|
|
587
|
+
*/
|
|
588
|
+
extend = (extra) => Form.from(ShapeUtil.extend(this.shape, extra instanceof Form ? extra.shape : extra));
|
|
589
|
+
/**
|
|
590
|
+
* Keep only selected field names.
|
|
591
|
+
*
|
|
592
|
+
* @template N Selected field names
|
|
593
|
+
* @param names Non-empty list of field names to keep
|
|
594
|
+
* @returns New form schema with only selected fields
|
|
595
|
+
*/
|
|
596
|
+
pick = (names) => Form.from(ShapeUtil.pick(this.shape, names));
|
|
597
|
+
/**
|
|
598
|
+
* Remove selected field names.
|
|
599
|
+
*
|
|
600
|
+
* @template N Field names to remove
|
|
601
|
+
* @param names Non-empty list of field names to remove
|
|
602
|
+
* @returns New form schema without selected fields
|
|
603
|
+
*/
|
|
604
|
+
omit = (names) => Form.from(ShapeUtil.omit(this.shape, names));
|
|
605
|
+
/**
|
|
606
|
+
* @param name Unexpected form field name
|
|
607
|
+
* @param path Parent path
|
|
608
|
+
* @returns Schema issue for unexpected form field names
|
|
609
|
+
*/
|
|
610
|
+
#unexpected(name, path = []) {
|
|
611
|
+
return new Schema.Issue("known form data name", [...path, name], "Unexpected form data name");
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Sanitizes render-state values by removing unsupported or oversized entries.
|
|
615
|
+
*
|
|
616
|
+
* @param values Candidate values to keep
|
|
617
|
+
* @param persist When `true`, only allow fields marked with `.persist()`
|
|
618
|
+
* @returns Sanitized values
|
|
619
|
+
*/
|
|
620
|
+
#sanitize(values, persist = true) {
|
|
621
|
+
const sanitized = {};
|
|
622
|
+
if (values) {
|
|
623
|
+
for (const [name, value] of Object.entries(values)) {
|
|
624
|
+
const field = this.shape[name];
|
|
625
|
+
if (field &&
|
|
626
|
+
field.type !== "file" &&
|
|
627
|
+
(!persist || FieldSchema.persisted(field)) &&
|
|
628
|
+
value != null) {
|
|
629
|
+
const result = Form.#valueSchema.parse(value);
|
|
630
|
+
if (!result.issues &&
|
|
631
|
+
JSON.stringify(result.data).length <= Form.#maxValueChars) {
|
|
632
|
+
sanitized[name] = result.data;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
if (Object.keys(sanitized).length)
|
|
637
|
+
return sanitized;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Decode form state from input.
|
|
642
|
+
*
|
|
643
|
+
* @param stateInput Current page URL
|
|
644
|
+
*/
|
|
645
|
+
#decode(stateInput) {
|
|
646
|
+
if (stateInput) {
|
|
647
|
+
const values = this.#sanitize(this.names.reduce((data, name) => {
|
|
648
|
+
if (stateInput.searchParams.has(name)) {
|
|
649
|
+
const value = FieldSchema.read(this.shape[name], stateInput.searchParams, name);
|
|
650
|
+
if (value != null)
|
|
651
|
+
data[name] = value;
|
|
652
|
+
}
|
|
653
|
+
return data;
|
|
654
|
+
}, {}), false);
|
|
655
|
+
const encoded = stateInput.searchParams.get(Form.params[1]);
|
|
656
|
+
if (encoded && encoded.length <= Form.#maxStateBytes * 2) {
|
|
657
|
+
try {
|
|
658
|
+
const result = Schema.string()
|
|
659
|
+
.json(Schema.object({
|
|
660
|
+
id: Schema.literal(this.#id),
|
|
661
|
+
issues: Schema.array(Schema.object({
|
|
662
|
+
expected: Schema.string(),
|
|
663
|
+
path: Schema.array(Schema.union([Schema.string(), Schema.number()])),
|
|
664
|
+
message: Schema.string(),
|
|
665
|
+
}).transform((issue) => new Schema.Issue(issue.expected, issue.path, issue.message))).optional(),
|
|
666
|
+
values: Schema.object(this.names.reduce((shape, name) => {
|
|
667
|
+
shape[name] = Form.#valueSchema.optional();
|
|
668
|
+
return shape;
|
|
669
|
+
}, {})).optional(),
|
|
670
|
+
}))
|
|
671
|
+
.parse(Codec.decode(Codec.Base64Url.decode(encoded)));
|
|
672
|
+
if (result.data?.id === this.#id) {
|
|
673
|
+
const current = this.#sanitize(result.data.values);
|
|
674
|
+
return {
|
|
675
|
+
...result.data,
|
|
676
|
+
values: (values || current) &&
|
|
677
|
+
{ ...values, ...current },
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
catch { }
|
|
682
|
+
}
|
|
683
|
+
return values && { id: this.#id, values };
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Parse and validate form data.
|
|
688
|
+
*
|
|
689
|
+
* @param source FormData, URLSearchParams, or Multipart to parse
|
|
690
|
+
* @param path Internal path reference
|
|
691
|
+
* @returns Parsed result
|
|
692
|
+
*/
|
|
693
|
+
parse = async (source, path = []) => {
|
|
694
|
+
const data = {};
|
|
695
|
+
const issues = [];
|
|
696
|
+
const values = {};
|
|
697
|
+
let form;
|
|
698
|
+
let stream;
|
|
699
|
+
if (source instanceof Multipart) {
|
|
700
|
+
form = new FormData();
|
|
701
|
+
const iter = source[Symbol.asyncIterator]();
|
|
702
|
+
let current;
|
|
703
|
+
while ((current = await iter.next()) && !current.done) {
|
|
704
|
+
const part = current.value;
|
|
705
|
+
if (part.name) {
|
|
706
|
+
const field = this.shape[part.name];
|
|
707
|
+
if (!field) {
|
|
708
|
+
issues.push(this.#unexpected(part.name, path));
|
|
709
|
+
}
|
|
710
|
+
else if (field.streaming) {
|
|
711
|
+
// expose current and rest of the parts to the user
|
|
712
|
+
stream = (async function* () {
|
|
713
|
+
try {
|
|
714
|
+
// have to yield the current part first
|
|
715
|
+
// this is why the multipart can't be passed directly
|
|
716
|
+
yield part;
|
|
717
|
+
let next;
|
|
718
|
+
while ((next = await iter.next()) && !next.done) {
|
|
719
|
+
yield next.value;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
finally {
|
|
723
|
+
try {
|
|
724
|
+
await iter.return?.();
|
|
725
|
+
}
|
|
726
|
+
catch { }
|
|
727
|
+
}
|
|
728
|
+
})();
|
|
729
|
+
break;
|
|
730
|
+
}
|
|
731
|
+
else {
|
|
732
|
+
form.append(part.name, await part.value());
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
else if (source instanceof FormData) {
|
|
738
|
+
form = source;
|
|
739
|
+
for (const name of new Set(source.keys())) {
|
|
740
|
+
if (!this.shape[name])
|
|
741
|
+
issues.push(this.#unexpected(name, path));
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
else {
|
|
745
|
+
// allow passthrough for URLSearchParams
|
|
746
|
+
form = source;
|
|
747
|
+
}
|
|
748
|
+
for (const [name, field] of Object.entries(this.shape)) {
|
|
749
|
+
if (!field.streaming) {
|
|
750
|
+
const value = FieldSchema.read(field, form, name);
|
|
751
|
+
const result = field.parse(value, [...path, name]);
|
|
752
|
+
if (result.issues) {
|
|
753
|
+
issues.push(...result.issues);
|
|
754
|
+
}
|
|
755
|
+
else {
|
|
756
|
+
data[name] = result.data;
|
|
757
|
+
}
|
|
758
|
+
if (FieldSchema.persisted(field) && value != null) {
|
|
759
|
+
values[name] = value;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
if (issues.length) {
|
|
764
|
+
const result = new Schema.AggregateIssue(issues, this.#sanitize(values));
|
|
765
|
+
let search;
|
|
766
|
+
if (result.values) {
|
|
767
|
+
// trim persisted values until the encoded state fits
|
|
768
|
+
for (let i = this.names.length; i >= 0; i--) {
|
|
769
|
+
// skip on the first time - try to encode everything first
|
|
770
|
+
if (i !== this.names.length)
|
|
771
|
+
delete result.values[this.names[i]];
|
|
772
|
+
const state = Codec.encode(JSON.stringify({
|
|
773
|
+
issues: result.issues,
|
|
774
|
+
id: this.#id,
|
|
775
|
+
...(Object.keys(result.values).length
|
|
776
|
+
? { values: result.values }
|
|
777
|
+
: {}),
|
|
778
|
+
}));
|
|
779
|
+
if (state.byteLength <= Form.#maxStateBytes) {
|
|
780
|
+
search = [Form.params[1], Codec.Base64Url.encode(state)];
|
|
781
|
+
break;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
else {
|
|
786
|
+
// fall back to issues-only state when nothing persisted.
|
|
787
|
+
const state = Codec.encode(JSON.stringify({
|
|
788
|
+
issues: result.issues,
|
|
789
|
+
id: this.#id,
|
|
790
|
+
}));
|
|
791
|
+
if (state.byteLength <= Form.#maxStateBytes) {
|
|
792
|
+
search = [Form.params[1], Codec.Base64Url.encode(state)];
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
if (stream) {
|
|
796
|
+
// invalid result does not expose streamed parts, drain
|
|
797
|
+
try {
|
|
798
|
+
for await (const _ of stream)
|
|
799
|
+
;
|
|
800
|
+
}
|
|
801
|
+
catch { }
|
|
802
|
+
}
|
|
803
|
+
return Object.assign(result, { search });
|
|
804
|
+
}
|
|
805
|
+
return { data: data, stream };
|
|
806
|
+
};
|
|
807
|
+
/**
|
|
808
|
+
* Render a single form field.
|
|
809
|
+
*
|
|
810
|
+
* @param props Component props
|
|
811
|
+
* @example
|
|
812
|
+
*
|
|
813
|
+
* ```tsx
|
|
814
|
+
* <User.Field name="username" />
|
|
815
|
+
* ```
|
|
816
|
+
*/
|
|
817
|
+
Field = (props) => this.shape[props.name].render({
|
|
818
|
+
...props,
|
|
819
|
+
state: this.#decode(props.state),
|
|
820
|
+
});
|
|
821
|
+
/**
|
|
822
|
+
* Render all form fields.
|
|
823
|
+
*
|
|
824
|
+
* @param props Component props
|
|
825
|
+
* @example
|
|
826
|
+
*
|
|
827
|
+
* ```tsx
|
|
828
|
+
* <User.Fields />
|
|
829
|
+
* ```
|
|
830
|
+
*/
|
|
831
|
+
Fields = (props = // partial because name is not required
|
|
832
|
+
{}) => {
|
|
833
|
+
const state = this.#decode(props.state); // pulled out to not call each map iteration
|
|
834
|
+
return this.names.map((name) => this.shape[name].render({ ...props, name, state }));
|
|
835
|
+
};
|
|
836
|
+
/**
|
|
837
|
+
* Access bound sub-components for a field.
|
|
838
|
+
*
|
|
839
|
+
* @template N Type of the form field name
|
|
840
|
+
* @param props Field component props
|
|
841
|
+
* @example
|
|
842
|
+
*
|
|
843
|
+
* ```tsx
|
|
844
|
+
* const Radio = User.component({ name: "radio" });
|
|
845
|
+
*
|
|
846
|
+
* <Radio.Label />
|
|
847
|
+
* <Radio.Control />
|
|
848
|
+
* ```
|
|
849
|
+
*/
|
|
850
|
+
component = (props) => this.shape[props.name].component({
|
|
851
|
+
...props,
|
|
852
|
+
state: this.#decode(props.state),
|
|
853
|
+
});
|
|
854
|
+
/**
|
|
855
|
+
* Create a Form from a shape or use another Form.
|
|
856
|
+
*
|
|
857
|
+
* @template S Form field shape type
|
|
858
|
+
* @param shape Form fields
|
|
859
|
+
*/
|
|
860
|
+
static from(shape) {
|
|
861
|
+
return shape instanceof Form ? shape : new Form(shape);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Represents a form field with parsing logic and rendering metadata.
|
|
866
|
+
*
|
|
867
|
+
* @template Output Output type of the field
|
|
868
|
+
* @template Tag Tag name
|
|
869
|
+
* @template Type Input type
|
|
870
|
+
* @template Values Persisted field value type
|
|
871
|
+
* @template Stream If the field should be streamed as a part
|
|
872
|
+
*/
|
|
873
|
+
class FieldSchema extends Schema {
|
|
874
|
+
/** Read the value from form data */
|
|
875
|
+
#read;
|
|
876
|
+
/** Field type */
|
|
877
|
+
type;
|
|
878
|
+
// tag and values are public so emitted .d.ts preserves
|
|
879
|
+
// field discriminants for correct types
|
|
880
|
+
/** Field tag */
|
|
881
|
+
tag;
|
|
882
|
+
/** Field values */
|
|
883
|
+
values;
|
|
884
|
+
/** Maximum expected multipart part count for this field name. */
|
|
885
|
+
parts;
|
|
886
|
+
/** If the field should be streamed as a part */
|
|
887
|
+
streaming;
|
|
888
|
+
/** If the field should persist invalid-state values. */
|
|
889
|
+
#persist;
|
|
890
|
+
/** Field options */
|
|
891
|
+
#options;
|
|
892
|
+
/**
|
|
893
|
+
* Create a new field.
|
|
894
|
+
*
|
|
895
|
+
* @param options Field options
|
|
896
|
+
* @param parse How to validate the input
|
|
897
|
+
* @param read How to read the form data
|
|
898
|
+
* @param parts Maximum expected multipart parts for this field
|
|
899
|
+
* @param stream If this field should be streamed as a multipart part
|
|
900
|
+
* @param persist If this field should persist invalid state values
|
|
901
|
+
*/
|
|
902
|
+
constructor(options, parse,
|
|
903
|
+
// default to a single value, treating blank as missing
|
|
904
|
+
read = (data, name) => data.get(name) || undefined, parts = 1, stream, persist = false) {
|
|
905
|
+
super(parse instanceof Schema ? parse.parse : parse);
|
|
906
|
+
this.#options = options;
|
|
907
|
+
this.tag = (options.tag ?? "input");
|
|
908
|
+
this.values = options.values;
|
|
909
|
+
this.#read = read;
|
|
910
|
+
this.type = options.props?.type;
|
|
911
|
+
this.parts = parts;
|
|
912
|
+
this.streaming = stream;
|
|
913
|
+
this.#persist = persist;
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* @param field Field instance
|
|
917
|
+
* @param data Form data source
|
|
918
|
+
* @param name HTML name attribute
|
|
919
|
+
* @returns Raw field input
|
|
920
|
+
*/
|
|
921
|
+
static read(field, data, name) {
|
|
922
|
+
return field.#read(data, name);
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Stream this field as a multipart request `Part`.
|
|
926
|
+
*
|
|
927
|
+
* @returns Part field
|
|
928
|
+
*/
|
|
929
|
+
stream() {
|
|
930
|
+
return new FieldSchema(this.#options, this.parse, this.#read, this.parts, true, this.#persist);
|
|
931
|
+
}
|
|
932
|
+
persist() {
|
|
933
|
+
return new FieldSchema(this.#options, this.parse, this.#read, this.parts, this.streaming, true);
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Derive a new Field from the current instance type.
|
|
937
|
+
*
|
|
938
|
+
* @template O Output type of the new Field
|
|
939
|
+
* @param parse Parse function that validates and transforms input
|
|
940
|
+
* @returns New `Field` instance
|
|
941
|
+
*/
|
|
942
|
+
derive(parse) {
|
|
943
|
+
return new FieldSchema(this.#options, parse, this.#read, this.parts, this.streaming, this.#persist);
|
|
944
|
+
}
|
|
945
|
+
component({ state, ...props }) {
|
|
946
|
+
const value = state?.values?.[props.name];
|
|
947
|
+
const issue = state?.issues?.find((i) => i.path[0] === props.name);
|
|
948
|
+
const issueId = issue && `${props.name}-issue`;
|
|
949
|
+
const hidden = this.type === "hidden";
|
|
950
|
+
const { label = props.name, ...control } = {
|
|
951
|
+
id: props.name,
|
|
952
|
+
autofocus: issue && state?.issues?.[0] === issue,
|
|
953
|
+
"aria-invalid": issue && "true",
|
|
954
|
+
"aria-describedby": issueId,
|
|
955
|
+
...this.#options.props,
|
|
956
|
+
...props,
|
|
957
|
+
};
|
|
958
|
+
const Issue = (data = {}) => issue && // render nothing if no issue
|
|
959
|
+
!hidden &&
|
|
960
|
+
jsx("p", {
|
|
961
|
+
id: issueId,
|
|
962
|
+
children: issue.message,
|
|
963
|
+
"data-issue": issue && state.issues.indexOf(issue), // issue index starting from 0
|
|
964
|
+
...data,
|
|
965
|
+
});
|
|
966
|
+
if (this.values && this.tag !== "select") {
|
|
967
|
+
// radio/checkboxes
|
|
968
|
+
// make multiple ids for the group so all don't have the same id
|
|
969
|
+
const groupId = (value) => `${control.name}-${value}`.toLowerCase();
|
|
970
|
+
const Control = (data) => jsx(this.tag, {
|
|
971
|
+
...control,
|
|
972
|
+
id: groupId(data.value),
|
|
973
|
+
// autofocus only the first input in the group
|
|
974
|
+
autofocus: control.autofocus && data.value === this.values?.[0],
|
|
975
|
+
checked: Array.isArray(value)
|
|
976
|
+
? value.includes(data.value) // checkboxes
|
|
977
|
+
: value === data.value, // radio
|
|
978
|
+
...data,
|
|
979
|
+
});
|
|
980
|
+
const Label = ({ value, ...rest }) => jsx("label", { for: groupId(value), children: value, ...rest });
|
|
981
|
+
return {
|
|
982
|
+
Issue,
|
|
983
|
+
Label,
|
|
984
|
+
Control,
|
|
985
|
+
Root: (data = {}) => jsx("fieldset", data),
|
|
986
|
+
Option: ({ value, ...rest }) => jsx("div", {
|
|
987
|
+
children: [Control({ value }), Label({ value })],
|
|
988
|
+
...rest,
|
|
989
|
+
}),
|
|
990
|
+
Legend: (data = {}) => jsx("legend", { children: label, ...data }),
|
|
991
|
+
...this,
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
return {
|
|
995
|
+
Issue,
|
|
996
|
+
Root: (data = {}) => hidden ? Fragment(data) : jsx("div", data),
|
|
997
|
+
Label: (data = {}) => !hidden && jsx("label", { for: control.id, children: label, ...data }),
|
|
998
|
+
Control: (data) => {
|
|
999
|
+
const attrs = { ...control, ...data };
|
|
1000
|
+
if (value !== undefined) {
|
|
1001
|
+
if (this.tag === "textarea") {
|
|
1002
|
+
attrs.children = value;
|
|
1003
|
+
}
|
|
1004
|
+
else if (this.tag === "input") {
|
|
1005
|
+
if (this.type === "checkbox") {
|
|
1006
|
+
attrs.checked = value;
|
|
1007
|
+
}
|
|
1008
|
+
else {
|
|
1009
|
+
attrs.value = value;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
return jsx(this.tag, attrs);
|
|
1014
|
+
},
|
|
1015
|
+
Option:
|
|
1016
|
+
// select
|
|
1017
|
+
this.values &&
|
|
1018
|
+
((data) => jsx("option", {
|
|
1019
|
+
children: data.value,
|
|
1020
|
+
selected: Array.isArray(value)
|
|
1021
|
+
? value.includes(data.value) // multiselect
|
|
1022
|
+
: value === data.value,
|
|
1023
|
+
...data,
|
|
1024
|
+
})),
|
|
1025
|
+
...this,
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* @template S Form shape type
|
|
1030
|
+
* @param props Field control props
|
|
1031
|
+
* @returns Input group component
|
|
1032
|
+
*/
|
|
1033
|
+
#Group(props) {
|
|
1034
|
+
const c = this.component(props);
|
|
1035
|
+
return c.Root({
|
|
1036
|
+
children: [
|
|
1037
|
+
// @ts-expect-error - `#Group` runs for grouped inputs, includes `Legend` with label
|
|
1038
|
+
c.Legend(),
|
|
1039
|
+
this.values.map((value) => {
|
|
1040
|
+
return jsx("div", {
|
|
1041
|
+
children: [c.Control({ value }), c.Label({ value })],
|
|
1042
|
+
});
|
|
1043
|
+
}),
|
|
1044
|
+
c.Issue(),
|
|
1045
|
+
],
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* @template S Form shape type
|
|
1050
|
+
* @param props Field control props
|
|
1051
|
+
* @returns Select component
|
|
1052
|
+
*/
|
|
1053
|
+
#Select(props) {
|
|
1054
|
+
const c = this.component(props);
|
|
1055
|
+
return c.Root({
|
|
1056
|
+
children: [
|
|
1057
|
+
c.Label(),
|
|
1058
|
+
c.Control({
|
|
1059
|
+
children: this.values.map((value) => c.Option({ value })),
|
|
1060
|
+
}),
|
|
1061
|
+
c.Issue(),
|
|
1062
|
+
],
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* @template S Form shape type
|
|
1067
|
+
* @param props Field control props
|
|
1068
|
+
* @returns Default input component
|
|
1069
|
+
*/
|
|
1070
|
+
#Input(props) {
|
|
1071
|
+
const c = this.component(props);
|
|
1072
|
+
return c.Root({ children: [c.Label(), c.Control(), c.Issue()] });
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* @template S Form shape type
|
|
1076
|
+
* @param props Field control props including `name` of the field to render
|
|
1077
|
+
* @returns Component that renders the HTML field with default structure
|
|
1078
|
+
*/
|
|
1079
|
+
render(props) {
|
|
1080
|
+
if (this.values) {
|
|
1081
|
+
if (this.tag === "select")
|
|
1082
|
+
return this.#Select(props);
|
|
1083
|
+
return this.#Group(props);
|
|
1084
|
+
}
|
|
1085
|
+
return this.#Input(props);
|
|
1086
|
+
}
|
|
1087
|
+
/**
|
|
1088
|
+
* @param field Field definition
|
|
1089
|
+
* @returns `true` when the field persists invalid-state values
|
|
1090
|
+
*/
|
|
1091
|
+
static persisted(field) {
|
|
1092
|
+
return field.#persist;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
/** Field factory functions */
|
|
1096
|
+
export class Field {
|
|
1097
|
+
// this is used instead of the defaults for example "Expected string"
|
|
1098
|
+
// since "string" doesn't make sense to end users
|
|
1099
|
+
/** Default message for required field values. */
|
|
1100
|
+
static #required = "Required field";
|
|
1101
|
+
/**
|
|
1102
|
+
* @param value Raw form entry
|
|
1103
|
+
* @returns `true` when the file input contains a real file value
|
|
1104
|
+
*/
|
|
1105
|
+
static #nonEmptyFile(value) {
|
|
1106
|
+
return value instanceof File && (value.name !== "" || value.size > 0);
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* @param data Form data
|
|
1110
|
+
* @param name HTML name attribute
|
|
1111
|
+
* @returns Field values or `undefined` when missing
|
|
1112
|
+
*/
|
|
1113
|
+
static #readMany(data, name) {
|
|
1114
|
+
const value = data.getAll(name);
|
|
1115
|
+
return value.length ? value : undefined;
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* @param props Input props
|
|
1119
|
+
* @returns Generic input field
|
|
1120
|
+
*/
|
|
1121
|
+
static #input(props) {
|
|
1122
|
+
return new FieldSchema({ props }, Schema.string(Field.#required));
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* @param props Input props
|
|
1126
|
+
* @returns Text input field
|
|
1127
|
+
*/
|
|
1128
|
+
static text(props) {
|
|
1129
|
+
return Field.#input({ ...props, type: "text" });
|
|
1130
|
+
}
|
|
1131
|
+
/**
|
|
1132
|
+
* @param props Input props
|
|
1133
|
+
* @returns Password input field
|
|
1134
|
+
*/
|
|
1135
|
+
static password(props) {
|
|
1136
|
+
return Field.#input({ ...props, type: "password" });
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* @param props Input props
|
|
1140
|
+
* @returns Search input field
|
|
1141
|
+
*/
|
|
1142
|
+
static search(props) {
|
|
1143
|
+
return Field.#input({ ...props, type: "search" });
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* @param props Input props
|
|
1147
|
+
* @returns Telephone input field
|
|
1148
|
+
*/
|
|
1149
|
+
static tel(props) {
|
|
1150
|
+
return Field.#input({ ...props, type: "tel" });
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* @param props Input props
|
|
1154
|
+
* @returns Color input field
|
|
1155
|
+
*/
|
|
1156
|
+
static color(props) {
|
|
1157
|
+
return Field.#input({ ...props, type: "color" });
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* @param props Input props
|
|
1161
|
+
* @returns Hidden input field
|
|
1162
|
+
*/
|
|
1163
|
+
static hidden(props) {
|
|
1164
|
+
return Field.#input({ ...props, type: "hidden" });
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* @param props Input props
|
|
1168
|
+
* @returns Date input field
|
|
1169
|
+
*/
|
|
1170
|
+
static date(props) {
|
|
1171
|
+
return Field.#input({ ...props, type: "date" });
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* @param props Input props
|
|
1175
|
+
* @returns Datetime input field
|
|
1176
|
+
*/
|
|
1177
|
+
static datetime(props) {
|
|
1178
|
+
return Field.#input({ ...props, type: "datetime-local" });
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1181
|
+
* @param props Input props
|
|
1182
|
+
* @returns Month input field
|
|
1183
|
+
*/
|
|
1184
|
+
static month(props) {
|
|
1185
|
+
return Field.#input({ ...props, type: "month" });
|
|
1186
|
+
}
|
|
1187
|
+
/**
|
|
1188
|
+
* @param props Input props
|
|
1189
|
+
* @returns Week input field
|
|
1190
|
+
*/
|
|
1191
|
+
static week(props) {
|
|
1192
|
+
return Field.#input({ ...props, type: "week" });
|
|
1193
|
+
}
|
|
1194
|
+
/**
|
|
1195
|
+
* @param props Input props
|
|
1196
|
+
* @returns Time input field
|
|
1197
|
+
*/
|
|
1198
|
+
static time(props) {
|
|
1199
|
+
return Field.#input({ ...props, type: "time" });
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Validates email string.
|
|
1203
|
+
*
|
|
1204
|
+
* @param props Input props
|
|
1205
|
+
* @param message Issue message when invalid
|
|
1206
|
+
* @returns Email input field
|
|
1207
|
+
*/
|
|
1208
|
+
static email(props, message) {
|
|
1209
|
+
return new FieldSchema({ props: { ...props, type: "email" } }, Schema.string(Field.#required).email(message));
|
|
1210
|
+
}
|
|
1211
|
+
/**
|
|
1212
|
+
* Validates parsable URL.
|
|
1213
|
+
*
|
|
1214
|
+
* @param props Input props
|
|
1215
|
+
* @param message Issue message when invalid
|
|
1216
|
+
* @returns URL input field
|
|
1217
|
+
*/
|
|
1218
|
+
static url(props, message) {
|
|
1219
|
+
return new FieldSchema({ props: { ...props, type: "url" } }, Schema.string(Field.#required).url(message));
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* @param props Input props
|
|
1223
|
+
* @returns Input field
|
|
1224
|
+
*/
|
|
1225
|
+
static #number(props) {
|
|
1226
|
+
return new FieldSchema({ props }, Schema.number(Field.#required).preprocess((value) =>
|
|
1227
|
+
// form submissions read numeric controls as strings
|
|
1228
|
+
value == null || value === "" ? undefined : Number(value)));
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Coerces to number.
|
|
1232
|
+
*
|
|
1233
|
+
* @param props Input props
|
|
1234
|
+
* @returns Number input field
|
|
1235
|
+
*/
|
|
1236
|
+
static number(props) {
|
|
1237
|
+
return Field.#number({ ...props, type: "number" });
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Coerces to number.
|
|
1241
|
+
*
|
|
1242
|
+
* @param props Input props
|
|
1243
|
+
* @returns Range input field
|
|
1244
|
+
*/
|
|
1245
|
+
static range(props) {
|
|
1246
|
+
return Field.#number({ ...props, type: "range" });
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* - unchecked => key missing => `false`
|
|
1250
|
+
* - checked => key present => `true`
|
|
1251
|
+
*
|
|
1252
|
+
* @param props Input props
|
|
1253
|
+
* @returns Checkbox input field
|
|
1254
|
+
*/
|
|
1255
|
+
static checkbox(props) {
|
|
1256
|
+
return new FieldSchema({ props: { ...props, type: "checkbox" } }, Schema.boolean(), (formData, name) => formData.has(name));
|
|
1257
|
+
}
|
|
1258
|
+
/**
|
|
1259
|
+
* @param props Input props
|
|
1260
|
+
* @returns File input field
|
|
1261
|
+
*/
|
|
1262
|
+
static file(props) {
|
|
1263
|
+
return new FieldSchema({ props: { ...props, type: "file" } }, Schema.instance(File, Field.#required), (data, name) => {
|
|
1264
|
+
const value = data.get(name);
|
|
1265
|
+
return (Field.#nonEmptyFile(value) && value) || undefined;
|
|
1266
|
+
});
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* @param props Input props
|
|
1270
|
+
* @returns Multiple file input field
|
|
1271
|
+
*/
|
|
1272
|
+
static files(props) {
|
|
1273
|
+
return new FieldSchema({ props: { ...props, type: "file", multiple: true } }, Schema.array(Schema.instance(File, Field.#required), Field.#required), (data, name) => {
|
|
1274
|
+
const value = data.getAll(name).filter(Field.#nonEmptyFile);
|
|
1275
|
+
return value.length ? value : undefined;
|
|
1276
|
+
}, Infinity);
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* @template V Value type
|
|
1280
|
+
* @param values Checkbox values
|
|
1281
|
+
* @param props Input props
|
|
1282
|
+
* @returns Checkbox group input field
|
|
1283
|
+
*/
|
|
1284
|
+
static checkboxes(values, props) {
|
|
1285
|
+
return new FieldSchema({ values, props: { ...props, type: "checkbox" } }, Schema.array(Schema.enum(values, Field.#required), Field.#required), Field.#readMany, values.length);
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* @template V Value type
|
|
1289
|
+
* @param values Radio button values
|
|
1290
|
+
* @param props Input props
|
|
1291
|
+
* @returns Radio group input field
|
|
1292
|
+
*/
|
|
1293
|
+
static radio(values, props) {
|
|
1294
|
+
return new FieldSchema({ values, props: { ...props, type: "radio" } }, Schema.enum(values, Field.#required));
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* @param props Textarea props
|
|
1298
|
+
* @returns Textarea field
|
|
1299
|
+
*/
|
|
1300
|
+
static textarea(props) {
|
|
1301
|
+
return new FieldSchema({ tag: "textarea", props }, Schema.string(Field.#required));
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* @template V Value type
|
|
1305
|
+
* @param values Select options
|
|
1306
|
+
* @param props Select props
|
|
1307
|
+
* @returns Select field
|
|
1308
|
+
*/
|
|
1309
|
+
static select(values, props) {
|
|
1310
|
+
return new FieldSchema({ tag: "select", values, props }, Schema.enum(values, Field.#required));
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* @template V Value type
|
|
1314
|
+
* @param values Select options
|
|
1315
|
+
* @param props Select props
|
|
1316
|
+
* @returns Multi-select field
|
|
1317
|
+
*/
|
|
1318
|
+
static multiselect(values, props) {
|
|
1319
|
+
return new FieldSchema({ tag: "select", values, props: { ...props, multiple: true } }, Schema.array(Schema.enum(values, Field.#required), Field.#required), Field.#readMany, values.length);
|
|
1320
|
+
}
|
|
1321
|
+
}
|