ovr 7.0.0-next.2 → 7.0.0-next.21

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +1157 -0
  2. package/dist/auth/client-source.d.ts +2 -2
  3. package/dist/auth/client-source.d.ts.map +1 -1
  4. package/dist/auth/client-source.js +2 -2
  5. package/dist/auth/client.d.ts.map +1 -1
  6. package/dist/auth/client.js +7 -4
  7. package/dist/auth/configure.d.ts +21 -8
  8. package/dist/auth/configure.d.ts.map +1 -1
  9. package/dist/auth/configure.js +172 -6
  10. package/dist/auth/index.d.ts +48 -0
  11. package/dist/auth/index.d.ts.map +1 -1
  12. package/dist/auth/index.js +19 -0
  13. package/dist/auth/passkey.d.ts +14 -2
  14. package/dist/auth/passkey.d.ts.map +1 -1
  15. package/dist/auth/passkey.js +18 -5
  16. package/dist/auth/state.d.ts +6 -0
  17. package/dist/auth/state.d.ts.map +1 -1
  18. package/dist/auth/state.js +28 -5
  19. package/dist/auth/storage.d.ts +38 -0
  20. package/dist/auth/storage.d.ts.map +1 -1
  21. package/dist/auth/storage.js +60 -3
  22. package/dist/context/index.d.ts +4 -4
  23. package/dist/context/index.d.ts.map +1 -1
  24. package/dist/context/index.js +6 -3
  25. package/dist/form/index.d.ts +239 -31
  26. package/dist/form/index.d.ts.map +1 -1
  27. package/dist/form/index.js +657 -66
  28. package/dist/markdown/index.d.ts +6 -1
  29. package/dist/markdown/index.d.ts.map +1 -1
  30. package/dist/markdown/index.js +180 -9
  31. package/dist/mcp/index.d.ts.map +1 -1
  32. package/dist/mcp/index.js +154 -57
  33. package/dist/schema/index.d.ts +88 -19
  34. package/dist/schema/index.d.ts.map +1 -1
  35. package/dist/schema/index.js +32 -11
  36. package/dist/util/index.d.ts +12 -0
  37. package/dist/util/index.d.ts.map +1 -1
  38. package/dist/util/index.js +19 -0
  39. package/package.json +2 -1
  40. package/src/auth/client-source.ts +2 -2
  41. package/src/auth/client.ts +7 -4
  42. package/src/auth/configure.ts +189 -13
  43. package/src/auth/index.ts +44 -0
  44. package/src/auth/passkey.ts +25 -7
  45. package/src/auth/state.ts +32 -7
  46. package/src/auth/storage.ts +66 -3
  47. package/src/context/index.ts +14 -6
  48. package/src/form/index.ts +1174 -195
  49. package/src/markdown/index.ts +203 -12
  50. package/src/mcp/index.ts +205 -72
  51. package/src/schema/index.ts +195 -52
  52. package/src/util/index.ts +23 -0
@@ -1,8 +1,10 @@
1
1
  import { Fragment, jsx } from "../jsx/index.js";
2
2
  import { Schema, ShapeUtil, annotate, append, exact, normalizers, own, } from "../schema/index.js";
3
- import { Checksum, Codec, Size } from "../util/index.js";
3
+ import { Checksum, Codec, Prose, Size } from "../util/index.js";
4
4
  /** Internal protocol for a GET route, to make the form its fields render. */
5
5
  export const query = Symbol("query");
6
+ /** Internal protocol for Auth, the message a `taken()` field shows */
7
+ export const taken = Symbol("taken");
6
8
  /** A field's components and render, which a route's form reads */
7
9
  const component = Symbol("component");
8
10
  const render = Symbol("render");
@@ -43,6 +45,8 @@ export class Form {
43
45
  shape;
44
46
  /** Field names in definition order. */
45
47
  names;
48
+ /** Names of the lists, whose cells are named by them. */
49
+ #lists;
46
50
  /** Maximum expected multipart parts derived from field cardinality. */
47
51
  parts;
48
52
  /**
@@ -53,6 +57,7 @@ export class Form {
53
57
  constructor(shape) {
54
58
  this.shape = shape;
55
59
  this.names = Object.keys(this.shape);
60
+ this.#lists = this.names.filter((name) => this.shape[name].item);
56
61
  this.#id = Checksum.djb2(this.names.join());
57
62
  this.parts = Object.values(this.shape).reduce((sum, field) => sum + field.parts, 0);
58
63
  }
@@ -78,10 +83,52 @@ export class Form {
78
83
  }
79
84
  /**
80
85
  * @param name Form data name
81
- * @returns The field, own fields only, so a name such as "constructor" has none
86
+ * @returns The field, own fields only, so a name such as "constructor" has
87
+ * none. A list's cell, such as `steps.0`, is its list's.
82
88
  */
83
89
  #field(name) {
84
- return Object.hasOwn(this.shape, name) ? this.shape[name] : undefined;
90
+ if (Object.hasOwn(this.shape, name))
91
+ return this.shape[name];
92
+ for (const list of this.#lists) {
93
+ const field = this.shape[list];
94
+ if (FieldSchema.place(field.item, list, name) !== undefined)
95
+ return field;
96
+ }
97
+ }
98
+ /**
99
+ * @param item What each item of a list is
100
+ * @param value Candidate items
101
+ * @returns The items a list can render, without what a cell cannot
102
+ */
103
+ static #items(item, value, url = false) {
104
+ if (!Array.isArray(value))
105
+ return;
106
+ const cell = (field, value) => {
107
+ if (field.type === "file" ||
108
+ field.type === "password" ||
109
+ // a row's hidden value, such as its ID, is the server's to give:
110
+ // state in a URL, which anyone can write, never sets it
111
+ (url && field.type === "hidden") ||
112
+ value == null)
113
+ return;
114
+ const result = Form.#value().parse(value);
115
+ if (!result.issues)
116
+ return result.data;
117
+ };
118
+ return value.map((row) => {
119
+ // a place is kept, so the items after it stay where they were
120
+ if (field(item))
121
+ return cell(item, row) ?? "";
122
+ const cells = {};
123
+ if (row && typeof row === "object") {
124
+ for (const key of Object.keys(item)) {
125
+ const value = cell(item[key], row[key]);
126
+ if (value !== undefined)
127
+ own(cells, key, value);
128
+ }
129
+ }
130
+ return cells;
131
+ });
85
132
  }
86
133
  /**
87
134
  * @param name Unexpected form field name
@@ -108,10 +155,26 @@ export class Form {
108
155
  field.type !== "file" &&
109
156
  (!persist || FieldSchema.persisted(field)) &&
110
157
  value != null) {
158
+ if (field.item) {
159
+ // a cleared list is recorded empty, and no list has a size of
160
+ // its own: the state's limit holds them all
161
+ const items = value === ""
162
+ ? []
163
+ : Form.#items(field.item,
164
+ // no more rows from a URL than the list takes
165
+ limit && Array.isArray(value)
166
+ ? value.slice(0, FieldSchema.most(field))
167
+ : value, limit);
168
+ if (items)
169
+ own(sanitized, name, items);
170
+ continue;
171
+ }
111
172
  const result = Form.#value().parse(value);
112
173
  if (!result.issues &&
113
174
  (!limit ||
114
- JSON.stringify(result.data).length <= Form.#maxValueChars)) {
175
+ // each of many values, such as a line, has the limit:
176
+ // the state's own holds them all
177
+ (Array.isArray(result.data) ? result.data : [result.data]).every((one) => JSON.stringify(one).length <= Form.#maxValueChars))) {
115
178
  own(sanitized, name, result.data);
116
179
  }
117
180
  }
@@ -120,6 +183,34 @@ export class Form {
120
183
  return sanitized;
121
184
  }
122
185
  }
186
+ /**
187
+ * An issue by place means nothing without the rows it was found in, and a
188
+ * list's rows are only shown again when it persists and they fit the state.
189
+ *
190
+ * @param state Restored state
191
+ * @returns The state, where an issue of a cell whose list's rows were not
192
+ * restored is the list's own, and says which row and field it is about
193
+ */
194
+ #unplaced(state) {
195
+ if (!state?.issues || !this.#lists.length)
196
+ return state;
197
+ return {
198
+ ...state,
199
+ issues: state.issues.map((issue) => {
200
+ const [name, place, key] = issue.path;
201
+ if (typeof place !== "number" ||
202
+ !this.#lists.includes(name) ||
203
+ state.values?.[name] !== undefined)
204
+ return issue;
205
+ // the field as people know it, by its column's heading
206
+ const { item } = this.shape[name];
207
+ const cell = typeof key === "string" && !field(item) && Object.hasOwn(item, key)
208
+ ? `, ${FieldSchema.named(item[key], key)}`
209
+ : "";
210
+ return new Schema.Issue(issue.expected, [name], `Row ${place + 1}${cell}: ${issue.message}`);
211
+ }),
212
+ };
213
+ }
123
214
  /**
124
215
  * Decode form state, over the initial values.
125
216
  *
@@ -127,7 +218,7 @@ export class Form {
127
218
  * @param initial Initial values, submitted values take precedence
128
219
  */
129
220
  #decode(stateInput, initial) {
130
- const state = this.#restore(stateInput);
221
+ const state = this.#unplaced(this.#restore(stateInput));
131
222
  // initial values come from the server, not the URL, so no size limit
132
223
  const values = this.#sanitize(initial, false, false);
133
224
  if (!values)
@@ -143,7 +234,8 @@ export class Form {
143
234
  if (stateInput) {
144
235
  const { searchParams } = stateInput;
145
236
  const values = this.#sanitize((this.#query ? this.names : []).reduce((data, name) => {
146
- if (searchParams.has(name)) {
237
+ // a list's cells are named by it, so its own name is not there
238
+ if (searchParams.has(name) || this.shape[name].item) {
147
239
  const value = FieldSchema.read(this.shape[name], searchParams, name);
148
240
  if (value != null)
149
241
  own(data, name, value);
@@ -162,7 +254,11 @@ export class Form {
162
254
  message: Schema.string(),
163
255
  }).transform((issue) => new Schema.Issue(issue.expected, issue.path, issue.message))).optional(),
164
256
  values: Schema.object(this.names.reduce((shape, name) => {
165
- own(shape, name, Form.#value().optional());
257
+ own(shape, name,
258
+ // a list's items are checked as they are sanitized
259
+ this.shape[name].item
260
+ ? Schema.unknown()
261
+ : Form.#value().optional());
166
262
  return shape;
167
263
  }, {})).optional(),
168
264
  }))
@@ -218,10 +314,14 @@ export class Form {
218
314
  *
219
315
  * @param source FormData, URLSearchParams, or Multipart to parse
220
316
  * @param path Internal path reference
317
+ * @param sent The fields an agent's tool call gave, which are all it
318
+ * updates. Without it the source is a form's, which sends every field it
319
+ * has.
221
320
  * @returns Parsed result
222
321
  */
223
- parse = async (source, path = []) => {
322
+ parse = async (source, path = [], sent) => {
224
323
  const data = {};
324
+ const updates = {};
225
325
  const issues = [];
226
326
  const values = {};
227
327
  let form;
@@ -292,6 +392,10 @@ export class Form {
292
392
  else if (result.data !== undefined) {
293
393
  own(data, name, result.data);
294
394
  }
395
+ // what the request sets: a field sent empty is cleared, and one
396
+ // not sent keeps its value
397
+ if (sent ? sent.has(name) : FieldSchema.sent(field, form, name))
398
+ own(updates, name, result.data ?? null);
295
399
  // a cleared field is recorded empty, so it overrides initial values
296
400
  if (FieldSchema.persisted(field))
297
401
  own(values, name, value ?? "");
@@ -310,6 +414,7 @@ export class Form {
310
414
  }
311
415
  return {
312
416
  data: data,
417
+ updates: updates,
313
418
  stream,
314
419
  invalid: (messages) => this.#invalid(Object.entries(messages).flatMap(([name, message]) => typeof message === "string"
315
420
  ? [new Schema.Issue("valid", [name], message)]
@@ -368,6 +473,8 @@ export class Form {
368
473
  const required = "Required field";
369
474
  /** Default message for a choice that is not one of the options */
370
475
  const choose = "Select an option";
476
+ /** Default message for a number field sent a value that is not a number */
477
+ const numeric = "Enter a number";
371
478
  /**
372
479
  * @param value Form data entry
373
480
  * @returns `true` for a file a person chose, a browser sends an empty one otherwise
@@ -390,6 +497,7 @@ const readMany = (data, name) => {
390
497
  * @template Type Input type
391
498
  * @template Values Persisted field value type
392
499
  * @template Stream If the field should be streamed as a part
500
+ * @template Item What each item of a list is
393
501
  */
394
502
  class FieldSchema extends Schema {
395
503
  /** Read the value from form data */
@@ -402,6 +510,8 @@ class FieldSchema extends Schema {
402
510
  tag;
403
511
  /** Choices of a select, radio, or checkbox group */
404
512
  options;
513
+ /** What each item of a list is: a field, or fields by name */
514
+ item;
405
515
  /** Maximum expected multipart part count for this field name. */
406
516
  parts;
407
517
  /** If the field should be streamed as a part */
@@ -429,9 +539,18 @@ class FieldSchema extends Schema {
429
539
  this.#config = config;
430
540
  this.tag = (config.tag ?? "input");
431
541
  this.options = config.options;
542
+ this.item = config.item;
432
543
  this.#read = read;
433
544
  this.type = config.props?.type;
434
- this.parts = parts;
545
+ // a list takes as many rows as its `max()`, or the most any list
546
+ // does, so a request cannot send rows without end
547
+ const { item } = this;
548
+ this.parts = item
549
+ ? Math.min(this.#most(), FieldSchema.#rows) *
550
+ (item instanceof FieldSchema
551
+ ? item.parts
552
+ : Object.values(item).reduce((sum, cell) => sum + cell.parts, 0))
553
+ : parts;
435
554
  this.streaming = stream;
436
555
  this.#persist = persist;
437
556
  }
@@ -446,14 +565,14 @@ class FieldSchema extends Schema {
446
565
  this.type !== "hidden" &&
447
566
  Boolean(this.parse(this.#read(new URLSearchParams(), "")).issues));
448
567
  }
449
- /** How each picker writes its value */
568
+ /** How each picker writes its value, a sentence so it reads alone too */
450
569
  static #formats = {
451
- date: "Date as YYYY-MM-DD",
452
- "datetime-local": "Date and time as YYYY-MM-DDTHH:mm",
453
- month: "Month as YYYY-MM",
454
- week: "Week as YYYY-Www, such as 2026-W46",
455
- time: "Time as HH:mm",
456
- color: "Color as #rrggbb",
570
+ date: "Date as YYYY-MM-DD.",
571
+ "datetime-local": "Date and time as YYYY-MM-DDTHH:mm.",
572
+ month: "Month as YYYY-MM.",
573
+ week: "Week as YYYY-Www, such as 2026-W46.",
574
+ time: "Time as HH:mm.",
575
+ color: "Color as #rrggbb.",
457
576
  };
458
577
  /**
459
578
  * @internal The label people read, which names a terse field such as
@@ -466,9 +585,12 @@ class FieldSchema extends Schema {
466
585
  const { description } = this;
467
586
  // what a browser's picker sends, which a string alone does not say
468
587
  const format = FieldSchema.#formats[this.type];
469
- const described = [description?.replace(/\.$/, ""), format]
470
- .filter(Boolean)
471
- .join(". ");
588
+ // what people call a choice, where it is not its value
589
+ const named = Object.entries(this.#config.labels ?? {})
590
+ .filter(([value, label]) => label !== value)
591
+ .map(([value, label]) => `${value} (${label})`)
592
+ .join(", ");
593
+ const described = Prose.join(description, format, named && `Choices: ${named}.`);
472
594
  return {
473
595
  ...(label && { title: label }),
474
596
  ...(described && { description: described }),
@@ -489,6 +611,90 @@ class FieldSchema extends Schema {
489
611
  static read(field, data, name) {
490
612
  return field.#read(data, name);
491
613
  }
614
+ /**
615
+ * @param field Field
616
+ * @param data A form's data
617
+ * @param name The field's name
618
+ * @returns `true` when the form sent the field. A browser sends nothing
619
+ * for a box that is not ticked or a choice not made, so those are always
620
+ * sent: empty is their value.
621
+ */
622
+ static sent(field, data, name) {
623
+ if (field.type === "checkbox" ||
624
+ field.type === "radio" ||
625
+ (field.tag === "select" && field.#config.props?.multiple))
626
+ return true;
627
+ const { item } = field;
628
+ if (!item)
629
+ return data.has(name);
630
+ // a list's cells are named by it
631
+ for (const key of data.keys())
632
+ if (FieldSchema.place(item, name, key) !== undefined)
633
+ return true;
634
+ return false;
635
+ }
636
+ /**
637
+ * @param item What each item of the list is
638
+ * @param list The list's name
639
+ * @param name Form data name
640
+ * @returns The place of the item the name is a cell of, such as 2 for
641
+ * `steps.2` or `ingredients.2.amount`, `undefined` for any other name
642
+ */
643
+ static place(item, list, name) {
644
+ if (!name.startsWith(`${list}.`))
645
+ return;
646
+ const [, place, key] = /^(0|[1-9]\d{0,8})(?:\.(.+))?$/s.exec(name.slice(list.length + 1)) ?? [];
647
+ if (place === undefined ||
648
+ (item instanceof FieldSchema
649
+ ? key !== undefined
650
+ : key === undefined || !Object.hasOwn(item, key)))
651
+ return;
652
+ return Number(place);
653
+ }
654
+ /**
655
+ * @param item What each item of the list is
656
+ * @returns How the list reads its items, in the order of their places. An
657
+ * item left empty is left out, so a person clears a row to remove it.
658
+ */
659
+ static items(item) {
660
+ // a hidden cell, such as a row's ID, is sent with an empty row too
661
+ const filled = (cell, value) => value !== undefined && value !== false && cell.type !== "hidden";
662
+ return (all, name) => {
663
+ // each row's own entries, found in one pass: reading a cell from
664
+ // all of them would cost the whole form again for every cell
665
+ const rows = new Map();
666
+ for (const [key, value] of all) {
667
+ const place = FieldSchema.place(item, name, key);
668
+ if (place === undefined)
669
+ continue;
670
+ let row = rows.get(place);
671
+ if (!row)
672
+ rows.set(place, (row = new FormData()));
673
+ row.append(key, value);
674
+ }
675
+ const items = [];
676
+ for (const [place, data] of [...rows].sort(([a], [b]) => a - b)) {
677
+ const at = `${name}.${place}`;
678
+ if (item instanceof FieldSchema) {
679
+ const value = item.#read(data, at);
680
+ if (filled(item, value))
681
+ items.push(value);
682
+ continue;
683
+ }
684
+ const row = {};
685
+ let any = false;
686
+ for (const [key, cell] of Object.entries(item)) {
687
+ const value = cell.#read(data, `${at}.${key}`);
688
+ if (filled(cell, value))
689
+ any = true;
690
+ own(row, key, value);
691
+ }
692
+ if (any)
693
+ items.push(row);
694
+ }
695
+ return items.length ? items : undefined;
696
+ };
697
+ }
492
698
  /**
493
699
  * Stream this field as a multipart request `Part`.
494
700
  *
@@ -512,6 +718,38 @@ class FieldSchema extends Schema {
512
718
  label(text) {
513
719
  return this.#with({ label: text });
514
720
  }
721
+ /**
722
+ * What people read under the control, in place of the field's
723
+ * description. Use it when what `describe()` says is written for an agent
724
+ * to be complete, and a person needs fewer words. Agents still read the
725
+ * description. An empty hint shows people nothing.
726
+ *
727
+ * ```ts
728
+ * Field.number()
729
+ * .describe("Weight in grams for cups and spoons. Empty for counts and liquids.")
730
+ * .hint("For cups and spoons");
731
+ * ```
732
+ *
733
+ * @param text Hint
734
+ * @returns Field with the hint
735
+ */
736
+ hint(text) {
737
+ return this.#with({ hint: text });
738
+ }
739
+ /**
740
+ * @returns What people read under the control: the field's hint, or its
741
+ * description
742
+ */
743
+ #shown() {
744
+ return this.#config.hint ?? this.description;
745
+ }
746
+ taken(message) {
747
+ return this.#with({ taken: message });
748
+ }
749
+ /** @internal The message `taken()` set */
750
+ get [taken]() {
751
+ return this.#config.taken;
752
+ }
515
753
  /**
516
754
  * Attributes for the field's control wherever it renders, such as a
517
755
  * placeholder. Those for one form are passed when it renders.
@@ -560,6 +798,23 @@ class FieldSchema extends Schema {
560
798
  }
561
799
  : readMany, file ? Infinity : this.options.length || Infinity, this.streaming, this.#persist);
562
800
  }
801
+ // the overload above is its type
802
+ lines() {
803
+ const { description, ...def } = this.def;
804
+ // a description given before describes the field, not each line
805
+ const array = Schema.array((description === undefined
806
+ ? this
807
+ : this.#copy({ def })), required);
808
+ return new FieldSchema(this.#config, description === undefined ? array : { ...array.def, description }, (data, name) => {
809
+ // a person's one value is split, an agent's array has one each
810
+ const lines = data
811
+ .getAll(name)
812
+ .flatMap((value) => typeof value === "string" ? value.split(/\r?\n/) : [])
813
+ .map((line) => line.trim())
814
+ .filter(Boolean);
815
+ return lines.length ? lines : undefined;
816
+ }, Infinity, this.streaming, this.#persist);
817
+ }
563
818
  persist() {
564
819
  return this.#copy({ persist: true });
565
820
  }
@@ -580,16 +835,43 @@ class FieldSchema extends Schema {
580
835
  */
581
836
  #options(given) {
582
837
  const { options } = this;
583
- return options && (options.length ? options : (given ?? []));
838
+ return (options &&
839
+ (options.length
840
+ ? options
841
+ : Array.isArray(given)
842
+ ? given
843
+ : Object.keys(given ?? {})));
844
+ }
845
+ /**
846
+ * @param given Options given as the form renders
847
+ * @returns What people call each choice: the field's own labels, or those
848
+ * given with the options of a field made from a schema
849
+ */
850
+ #labels(given) {
851
+ const labels = this.#config.labels ??
852
+ (this.options?.length || Array.isArray(given)
853
+ ? undefined
854
+ : given);
855
+ // own labels only, so a value such as "constructor" is itself
856
+ return (value) => labels && Object.hasOwn(labels, value) ? labels[value] : value;
584
857
  }
585
- [component]({ state, options: given, ...props }) {
858
+ [component]({ state, options: given, ...props },
859
+ // what a list calls its cell, which is named by its place
860
+ named = props.name,
861
+ // if the control is read with its description. A row laid out by
862
+ // hand, such as in a table, seldom renders each cell's, and the
863
+ // default table has one for the column, whose ID this is.
864
+ described = true) {
586
865
  const options = this.#options(given);
866
+ const text = this.#labels(given);
587
867
  const value = state?.values?.[props.name];
588
- const issue = state?.issues?.find((i) => i.path[0] === props.name);
868
+ const issue = state?.issues?.find((i) => i.path[0] === props.name &&
869
+ // a list's own, each of its cells shows its own
870
+ (!this.item || i.path.length === 1));
589
871
  const issueId = issue && `${props.name}-issue`;
590
872
  const hidden = this.type === "hidden";
591
- const { label = props.name } = this.#config;
592
- const { description } = this;
873
+ const { label = named } = this.#config;
874
+ const description = this.#shown();
593
875
  const descriptionId = description && !hidden ? `${props.name}-description` : undefined;
594
876
  const control = {
595
877
  id: hidden ? undefined : props.name,
@@ -597,7 +879,9 @@ class FieldSchema extends Schema {
597
879
  autofocus: issue && state?.issues?.[0] === issue,
598
880
  "aria-invalid": issue && "true",
599
881
  // read with the control: its description, then what is wrong with it
600
- "aria-describedby": [descriptionId, issueId].filter(Boolean).join(" ") || undefined,
882
+ "aria-describedby": [described === true ? descriptionId : described, issueId]
883
+ .filter(Boolean)
884
+ .join(" ") || undefined,
601
885
  ...this.#config.props,
602
886
  ...props,
603
887
  };
@@ -623,25 +907,61 @@ class FieldSchema extends Schema {
623
907
  "data-issue": issue && state.issues.indexOf(issue), // issue index starting from 0
624
908
  ...data,
625
909
  });
910
+ if (this.item) {
911
+ const cells = () => this.#cells({ state, options: given, ...props });
912
+ let built;
913
+ // a list has no control of its own, so what is passed to it, such
914
+ // as a class, is its fieldset's
915
+ const { name: _, rows: __, ...attributes } = props;
916
+ return {
917
+ Description,
918
+ Issue,
919
+ Root: (data = {}) => jsx("fieldset", { ...attributes, ...data }),
920
+ Legend: (data = {}) => jsx("legend", { children: label, ...data }),
921
+ ...this,
922
+ // built when read, the default layout renders each cell itself
923
+ get rows() {
924
+ return (built ??= cells().map((row) => Array.isArray(row)
925
+ ? row[0][component](row[1], row[2], false)
926
+ : Object.fromEntries(Object.entries(row).map(([key, cell]) => [
927
+ key,
928
+ cell[0][component](cell[1], cell[2], false),
929
+ ]))));
930
+ },
931
+ };
932
+ }
626
933
  if (options && this.tag !== "select") {
627
934
  // radio/checkboxes
628
935
  // make multiple ids for the group so all don't have the same id
629
936
  const groupId = (value) => `${control.name}-${value}`.toLowerCase();
937
+ // a group's own attributes, such as a class, are its fieldset's,
938
+ // as a list's are. Each box has those `control()` set, and if it
939
+ // is required.
940
+ const { name, required = this.#required(), placeholder: _, ...attributes } = props;
941
+ const box = {
942
+ id: undefined,
943
+ required,
944
+ autofocus: control.autofocus,
945
+ "aria-invalid": control["aria-invalid"],
946
+ "aria-describedby": control["aria-describedby"],
947
+ ...this.#config.props,
948
+ name,
949
+ };
630
950
  const Control = (data) => jsx(this.tag, {
631
- ...control,
951
+ ...box,
632
952
  id: groupId(data.value),
633
953
  // autofocus only the first input in the group
634
954
  autofocus: control.autofocus && data.value === options[0],
635
955
  checked: chosen(data.value),
636
956
  ...data,
637
957
  });
638
- const Label = ({ value, ...rest }) => jsx("label", { for: groupId(value), children: value, ...rest });
958
+ const Label = ({ value, ...rest }) => jsx("label", { for: groupId(value), children: text(value), ...rest });
639
959
  return {
640
960
  Description,
641
961
  Issue,
642
962
  Label,
643
963
  Control,
644
- Root: (data = {}) => jsx("fieldset", data),
964
+ Root: (data = {}) => jsx("fieldset", { ...attributes, ...data }),
645
965
  Option: ({ value, ...rest }) => jsx("div", {
646
966
  children: [Control({ value }), Label({ value })],
647
967
  ...rest,
@@ -658,9 +978,13 @@ class FieldSchema extends Schema {
658
978
  Label: (data = {}) => !hidden && jsx("label", { for: control.id, children: label, ...data }),
659
979
  Control: (data) => {
660
980
  const attrs = { ...control, ...data };
981
+ // a select has none: it is the text of its empty choice
982
+ if (this.tag === "select")
983
+ delete attrs.placeholder;
661
984
  if (value !== undefined) {
662
985
  if (this.tag === "textarea") {
663
- attrs.children = value;
986
+ // each of its `lines()` on its own line
987
+ attrs.children = Array.isArray(value) ? value.join("\n") : value;
664
988
  }
665
989
  else if (this.tag === "input") {
666
990
  if (this.type === "checkbox") {
@@ -677,7 +1001,7 @@ class FieldSchema extends Schema {
677
1001
  // select
678
1002
  options &&
679
1003
  ((data) => jsx("option", {
680
- children: data.value,
1004
+ children: text(data.value),
681
1005
  selected: chosen(data.value),
682
1006
  ...data,
683
1007
  })),
@@ -690,32 +1014,234 @@ class FieldSchema extends Schema {
690
1014
  * @param props Field control props including `name` of the field to render
691
1015
  * @returns Component that renders the HTML field with default structure
692
1016
  */
693
- [render](props) {
694
- // the sub-components of each kind of field, told apart by `options` and `tag` below
695
- const c = this[component](props);
696
- const options = this.#options(props.options);
1017
+ [render](props, named) {
1018
+ const { item } = this;
1019
+ // a list of several fields is a table, a column for each
1020
+ if (item && !(item instanceof FieldSchema))
1021
+ return this.#table(props, item);
1022
+ const c = this[component](props, named);
697
1023
  return c.Root({
698
1024
  children: [
699
- options && this.tag !== "select"
700
- ? // radio/checkboxes, a group with a legend, each value labelled
1025
+ item
1026
+ ? // a list of one field, a group with a legend, a row for each.
1027
+ // Its description is before the rows it explains, which
1028
+ // may be many.
701
1029
  [
702
1030
  c.Legend(),
703
- options.map((value) => jsx("div", {
704
- children: [c.Control({ value }), c.Label({ value })],
705
- })),
1031
+ c.Description(),
1032
+ this.#cells(props).map((row) => {
1033
+ const [field, cell, named] = row;
1034
+ return field[render](cell, named);
1035
+ }),
706
1036
  ]
707
- : [
708
- c.Label(),
709
- // a select has an option for each value
710
- c.Control(options && {
711
- children: options.map((value) => c.Option({ value })),
712
- }),
713
- ],
1037
+ : this.#grouped(props)
1038
+ ? // before the options it explains, as a list's is
1039
+ [c.Legend(), c.Description(), this.#body(c, props)]
1040
+ : [c.Label(), this.#body(c, props), c.Description()],
1041
+ c.Issue(),
1042
+ ],
1043
+ });
1044
+ }
1045
+ /**
1046
+ * @template S Form shape type
1047
+ * @param props Field control props
1048
+ * @returns `true` for a radio or checkbox group
1049
+ */
1050
+ #grouped(props) {
1051
+ return Boolean(this.#options(props.options)) && this.tag !== "select";
1052
+ }
1053
+ /**
1054
+ * @template S Form shape type
1055
+ * @param c The field's parts
1056
+ * @param props Field control props
1057
+ * @returns The field's control: a group's boxes each with its label, or
1058
+ * one control, a select with its options
1059
+ */
1060
+ #body(c, props) {
1061
+ const options = this.#options(props.options);
1062
+ if (!options)
1063
+ return c.Control();
1064
+ if (this.tag !== "select")
1065
+ return options.map((value) => jsx("div", { children: [c.Control({ value }), c.Label({ value })] }));
1066
+ const placeholder = props.placeholder ??
1067
+ this.#config.props?.placeholder;
1068
+ return c.Control({
1069
+ children: [
1070
+ // a browser chooses a select's first option, so one that may be
1071
+ // left empty, or that says what to choose, starts with an empty
1072
+ // choice
1073
+ (placeholder !== undefined || !(props.required ?? this.#required())) &&
1074
+ !this.#config.props?.multiple &&
1075
+ jsx("option", { value: "", children: placeholder }),
1076
+ options.map((value) => c.Option({ value })),
1077
+ ],
1078
+ });
1079
+ }
1080
+ /**
1081
+ * @template S Form shape type
1082
+ * @param props The list's props
1083
+ * @param item The fields of each item, by name
1084
+ * @returns A list of several fields: a table with a column for each
1085
+ * field, named in its heading and described once under the table, and a
1086
+ * row for each item
1087
+ */
1088
+ #table(props, item) {
1089
+ const c = this[component](props);
1090
+ const fields = Object.entries(item);
1091
+ const columns = fields.filter(([, field]) => field.type !== "hidden");
1092
+ const id = (key, part) => `${props.name}.${key}-${part}`;
1093
+ return c.Root({
1094
+ children: [
1095
+ c.Legend(),
714
1096
  c.Description(),
1097
+ // an element of its own, so a wide table can scroll alone and the
1098
+ // text around it keeps the fieldset's width
1099
+ jsx("div", {
1100
+ children: jsx("table", {
1101
+ children: [
1102
+ jsx("thead", {
1103
+ children: jsx("tr", {
1104
+ children: columns.map(([key, field]) =>
1105
+ // only the label, which names each cell of the column
1106
+ jsx("th", {
1107
+ id: id(key, "label"),
1108
+ scope: "col",
1109
+ children: field.#config.label ?? key,
1110
+ })),
1111
+ }),
1112
+ }),
1113
+ jsx("tbody", {
1114
+ children: this.#cells(props).map((cells) => {
1115
+ const row = cells;
1116
+ return jsx("tr", {
1117
+ children: columns.map(([key, field], column) => {
1118
+ const [, cell, named] = row[key];
1119
+ const group = field.#grouped(cell);
1120
+ const labelled = { "aria-labelledby": id(key, "label") };
1121
+ const parts = field[component](group ? cell : { ...cell, ...labelled }, named, Boolean(field.#shown()) && id(key, "description"));
1122
+ const body = field.#body(parts, cell);
1123
+ return jsx("td", {
1124
+ children: [
1125
+ // a row's hidden values, such as its ID
1126
+ !column &&
1127
+ fields.map(([key, field]) => field.type === "hidden" &&
1128
+ field[render](row[key][1], row[key][2])),
1129
+ group
1130
+ ? jsx("div", {
1131
+ role: "group",
1132
+ ...labelled,
1133
+ children: body,
1134
+ })
1135
+ : body,
1136
+ parts.Issue(),
1137
+ ],
1138
+ });
1139
+ }),
1140
+ });
1141
+ }),
1142
+ }),
1143
+ ],
1144
+ }),
1145
+ }),
1146
+ // what each column is, once under the table: a heading has no
1147
+ // room for it. Each cell of the column is read with its text.
1148
+ columns.map(([key, field]) => field.#shown() &&
1149
+ jsx("p", {
1150
+ "data-description": true,
1151
+ children: [
1152
+ jsx("span", { children: field.#config.label ?? key }),
1153
+ ": ",
1154
+ jsx("span", {
1155
+ id: id(key, "description"),
1156
+ children: field.#shown(),
1157
+ }),
1158
+ ],
1159
+ })),
715
1160
  c.Issue(),
716
1161
  ],
717
1162
  });
718
1163
  }
1164
+ /** The most rows a list without a `max()` takes in one request */
1165
+ static #rows = 1000;
1166
+ /**
1167
+ * @param field List field
1168
+ * @returns The most items it shows from state in a URL: its `max()`, or
1169
+ * the most any list takes
1170
+ */
1171
+ static most(field) {
1172
+ return Math.min(field.#most(), FieldSchema.#rows);
1173
+ }
1174
+ /**
1175
+ * @returns The most items a list takes, set with `max()`
1176
+ */
1177
+ #most() {
1178
+ let most = Infinity;
1179
+ for (let def = this.def; def && "inner" in def; def = def.inner.def) {
1180
+ if (def.type === "check" && def.check.name === "max")
1181
+ most = Math.min(most, Math.floor(Number(def.check.value)));
1182
+ }
1183
+ return most;
1184
+ }
1185
+ /**
1186
+ * @template S Form shape type
1187
+ * @param props The list's props
1188
+ * @returns Each row of the list: its filled items, then empty ones. A row is
1189
+ * its cell, or its cells by name, each as the field, the props that render
1190
+ * it, and what it is called.
1191
+ */
1192
+ #cells({ state, rows, ...props }) {
1193
+ const item = this.item;
1194
+ const { name } = props;
1195
+ // for this form, or wherever the list renders, set with `control()`
1196
+ const shown = rows ?? this.#config.props?.rows;
1197
+ const value = state?.values?.[name];
1198
+ const filled = Array.isArray(value) ? value : [];
1199
+ const values = {};
1200
+ filled.forEach((row, place) => {
1201
+ if (item instanceof FieldSchema)
1202
+ values[`${name}.${place}`] = row;
1203
+ else if (row && typeof row === "object")
1204
+ for (const key of Object.keys(item))
1205
+ values[`${name}.${place}.${key}`] = row[key];
1206
+ });
1207
+ // each cell finds its value and its issue by its own name
1208
+ const depth = item instanceof FieldSchema ? 2 : 3;
1209
+ const cells = {
1210
+ id: state?.id ?? "",
1211
+ values,
1212
+ issues: state?.issues?.map((issue) => issue.path[0] === name && issue.path.length > 1
1213
+ ? new Schema.Issue(issue.expected, [
1214
+ issue.path.slice(0, depth).join("."),
1215
+ ...issue.path.slice(depth),
1216
+ ], issue.message)
1217
+ : issue),
1218
+ };
1219
+ const cell = (field, name, named) => [
1220
+ field,
1221
+ // never required: a row left empty is left out. The list's own
1222
+ // attributes are its fieldset's, not each control's.
1223
+ { name, state: cells, options: props.options, required: false },
1224
+ named,
1225
+ ];
1226
+ return Array.from({
1227
+ // every filled row, and one more unless told how many to show,
1228
+ // but no more empty rows than the list takes
1229
+ length: Math.max(filled.length, Math.min(shown === undefined ? filled.length + 1 : Number(shown), this.#most())),
1230
+ }, (_, place) => item instanceof FieldSchema
1231
+ ? cell(item, `${name}.${place}`, String(place + 1))
1232
+ : Object.fromEntries(Object.entries(item).map(([key, field]) => [
1233
+ key,
1234
+ cell(field, `${name}.${place}.${key}`, key),
1235
+ ])));
1236
+ }
1237
+ /**
1238
+ * @param field Field definition
1239
+ * @param name The field's name
1240
+ * @returns What people call the field: its label, or its name
1241
+ */
1242
+ static named(field, name) {
1243
+ return field.#config.label ?? name;
1244
+ }
719
1245
  /**
720
1246
  * @param field Field definition
721
1247
  * @returns `true` when the field persists invalid-state values
@@ -741,6 +1267,32 @@ export class Field {
741
1267
  static #input(props) {
742
1268
  return new FieldSchema({ props }, Schema.string(required));
743
1269
  }
1270
+ /** A time as a browser's picker sends it, with seconds when it has them */
1271
+ static #clock = /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/;
1272
+ /**
1273
+ * @param value Text
1274
+ * @returns `true` for a day of the calendar as YYYY-MM-DD
1275
+ */
1276
+ static #day(value) {
1277
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value))
1278
+ return false;
1279
+ const date = new Date(`${value}T00:00:00Z`);
1280
+ // a day that is not one, such as the 31st of June, becomes another
1281
+ return (!Number.isNaN(date.getTime()) && date.toISOString().startsWith(value));
1282
+ }
1283
+ /**
1284
+ * A browser's picker only sends its own format, but an agent, or any
1285
+ * other client, sends what it likes, so the value is checked.
1286
+ *
1287
+ * @template T Input type
1288
+ * @param type Input type of the picker
1289
+ * @param message Issue message for a value in another format
1290
+ * @param valid Checks the value
1291
+ * @returns Input field for a picker's value
1292
+ */
1293
+ static #picked(type, message, valid) {
1294
+ return Field.#input({ type }).refine(valid, message);
1295
+ }
744
1296
  /**
745
1297
  * @returns Text input field
746
1298
  */
@@ -769,7 +1321,7 @@ export class Field {
769
1321
  * @returns Color input field
770
1322
  */
771
1323
  static color() {
772
- return Field.#input({ type: "color" });
1324
+ return Field.#picked("color", "Enter a color as #rrggbb", (value) => /^#[0-9a-f]{6}$/i.test(value));
773
1325
  }
774
1326
  /**
775
1327
  * @returns Hidden input field
@@ -781,31 +1333,36 @@ export class Field {
781
1333
  * @returns Date input field
782
1334
  */
783
1335
  static date() {
784
- return Field.#input({ type: "date" });
1336
+ return Field.#picked("date", "Enter a date as YYYY-MM-DD", (value) => Field.#day(value));
785
1337
  }
786
1338
  /**
787
1339
  * @returns Datetime input field
788
1340
  */
789
1341
  static datetime() {
790
- return Field.#input({ type: "datetime-local" });
1342
+ return Field.#picked("datetime-local", "Enter a date and time as YYYY-MM-DDTHH:mm", (value) => {
1343
+ const [day, time, more] = value.split("T");
1344
+ return (more === undefined &&
1345
+ Field.#day(day) &&
1346
+ Field.#clock.test(time ?? ""));
1347
+ });
791
1348
  }
792
1349
  /**
793
1350
  * @returns Month input field
794
1351
  */
795
1352
  static month() {
796
- return Field.#input({ type: "month" });
1353
+ return Field.#picked("month", "Enter a month as YYYY-MM", (value) => /^\d{4}-(0[1-9]|1[0-2])$/.test(value));
797
1354
  }
798
1355
  /**
799
1356
  * @returns Week input field
800
1357
  */
801
1358
  static week() {
802
- return Field.#input({ type: "week" });
1359
+ return Field.#picked("week", "Enter a week as YYYY-Www", (value) => /^\d{4}-W(0[1-9]|[1-4]\d|5[0-3])$/.test(value));
803
1360
  }
804
1361
  /**
805
1362
  * @returns Time input field
806
1363
  */
807
1364
  static time() {
808
- return Field.#input({ type: "time" });
1365
+ return Field.#picked("time", "Enter a time as HH:mm", (value) => Field.#clock.test(value));
809
1366
  }
810
1367
  /**
811
1368
  * Validates email string.
@@ -834,7 +1391,9 @@ export class Field {
834
1391
  // registered here rather than as the class loads, which is a side effect
835
1392
  // that would keep `Field` in bundles that only use `Form`
836
1393
  normalizers.add(Field.#toNumber);
837
- return new FieldSchema({ props }, Schema.number(required).preprocess(Field.#toNumber));
1394
+ return new FieldSchema({ props },
1395
+ // text, such as an agent's, is not a field left empty
1396
+ { type: "number", message: numeric, missing: required }).preprocess(Field.#toNumber);
838
1397
  }
839
1398
  /**
840
1399
  * @param value Form entry or stored number
@@ -886,10 +1445,17 @@ export class Field {
886
1445
  * @returns Fixed choices, and the schema that checks one, when given a list
887
1446
  */
888
1447
  static #choices(options) {
889
- return options instanceof Schema
890
- ? // given to `Field` or `component` as the form renders
891
- [[], options]
892
- : [options, Schema.enum(options, choose)];
1448
+ // given to `Field` or `component` as the form renders
1449
+ if (options instanceof Schema)
1450
+ return {
1451
+ options: [],
1452
+ choice: options,
1453
+ };
1454
+ const labels = Array.isArray(options)
1455
+ ? undefined
1456
+ : options;
1457
+ const values = (labels ? Object.keys(labels) : options);
1458
+ return { options: values, labels, choice: Schema.enum(values, choose) };
893
1459
  }
894
1460
  /**
895
1461
  * A group of checkboxes, of fixed choices or of choices a schema checks,
@@ -901,21 +1467,23 @@ export class Field {
901
1467
  * ```
902
1468
  *
903
1469
  * @template V Value type
904
- * @param options Checkbox options, or a schema for each one
1470
+ * @param options Checkbox options, an object of each one's label by its
1471
+ * value, or a schema for each one
905
1472
  * @returns Checkbox group input field
906
1473
  */
907
1474
  static checkboxes(options) {
908
- const [values, choice] = Field.#choices(options);
909
- return new FieldSchema({ options: values, props: { type: "checkbox" } }, Schema.array(choice, choose), readMany, values.length || Infinity);
1475
+ const { choice, ...config } = Field.#choices(options);
1476
+ return new FieldSchema({ ...config, props: { type: "checkbox" } }, Schema.array(choice, choose), readMany, config.options.length || Infinity);
910
1477
  }
911
1478
  /**
912
1479
  * @template V Value type
913
- * @param options Radio button options, or a schema for the one chosen
1480
+ * @param options Radio button options, an object of each one's label by
1481
+ * its value, or a schema for the one chosen
914
1482
  * @returns Radio group input field
915
1483
  */
916
1484
  static radio(options) {
917
- const [values, choice] = Field.#choices(options);
918
- return new FieldSchema({ options: values, props: { type: "radio" } }, choice);
1485
+ const { choice, ...config } = Field.#choices(options);
1486
+ return new FieldSchema({ ...config, props: { type: "radio" } }, choice);
919
1487
  }
920
1488
  /**
921
1489
  * @returns Textarea field
@@ -923,13 +1491,36 @@ export class Field {
923
1491
  static textarea() {
924
1492
  return new FieldSchema({ tag: "textarea" }, Schema.string(required));
925
1493
  }
1494
+ /**
1495
+ * A list of items in order, where an item may repeat: each is one field,
1496
+ * or several by name. People fill a row for each item, and agents send an
1497
+ * array. A row left empty is left out, and the list needs one item unless
1498
+ * the field is made optional after. `min()` and `max()` count its items.
1499
+ *
1500
+ * ```tsx
1501
+ * Field.list(Field.select(Schema.string().uuid())); // string[]
1502
+ * Field.list({ amount: Field.number(), name: Field.text() }); // { amount, name }[]
1503
+ * Field.list(Field.select(id)).max(7).control({ rows: 7 }); // a week's dinners
1504
+ * ```
1505
+ *
1506
+ * @template I Item type
1507
+ * @param item What each item is: a field, or fields by name
1508
+ * @returns List field whose value is an array of its items
1509
+ */
1510
+ static list(item) {
1511
+ return new FieldSchema({ tag: "fieldset", item }, Schema.array(field(item)
1512
+ ? item
1513
+ : Schema.object(item), required), FieldSchema.items(item), Infinity);
1514
+ }
926
1515
  /**
927
1516
  * @template V Value type
928
- * @param options Select options, or a schema for the one chosen
1517
+ * @param options Select options, an object of each one's label by its
1518
+ * value, or a schema for the one chosen. One that may be left empty
1519
+ * starts with an empty choice, whose text is its `placeholder`.
929
1520
  * @returns Select field
930
1521
  */
931
1522
  static select(options) {
932
- const [values, choice] = Field.#choices(options);
933
- return new FieldSchema({ tag: "select", options: values }, choice);
1523
+ const { choice, ...config } = Field.#choices(options);
1524
+ return new FieldSchema({ ...config, tag: "select" }, choice);
934
1525
  }
935
1526
  }