@atscript/ui 0.1.164 → 0.1.165

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 (60) hide show
  1. package/dist/client-factory.d.cts +6 -1
  2. package/dist/client-factory.d.mts +6 -1
  3. package/dist/form/create-form-def.cjs +28 -6
  4. package/dist/form/create-form-def.mjs +29 -7
  5. package/dist/form/labels.cjs +7 -4
  6. package/dist/form/labels.d.cts +6 -2
  7. package/dist/form/labels.d.mts +6 -2
  8. package/dist/form/labels.mjs +7 -4
  9. package/dist/form/types.d.cts +14 -0
  10. package/dist/form/types.d.mts +14 -0
  11. package/dist/form/validate.cjs +59 -23
  12. package/dist/form/validate.d.cts +37 -6
  13. package/dist/form/validate.d.mts +37 -6
  14. package/dist/form/validate.mjs +58 -23
  15. package/dist/i18n/ui-texts.cjs +135 -0
  16. package/dist/i18n/ui-texts.d.cts +81 -0
  17. package/dist/i18n/ui-texts.d.mts +81 -0
  18. package/dist/i18n/ui-texts.mjs +132 -0
  19. package/dist/index.cjs +6 -0
  20. package/dist/index.d.cts +7 -6
  21. package/dist/index.d.mts +7 -6
  22. package/dist/index.mjs +3 -2
  23. package/dist/messages.cjs +301 -0
  24. package/dist/messages.d.cts +302 -0
  25. package/dist/messages.d.mts +302 -0
  26. package/dist/messages.mjs +300 -0
  27. package/dist/plugin/annotations.cjs +30 -15
  28. package/dist/plugin/annotations.mjs +30 -15
  29. package/dist/plugin/value-help-validation.cjs +17 -7
  30. package/dist/plugin/value-help-validation.mjs +17 -7
  31. package/dist/shared/meta-cache.cjs +75 -37
  32. package/dist/shared/meta-cache.d.cts +40 -20
  33. package/dist/shared/meta-cache.d.mts +40 -20
  34. package/dist/shared/meta-cache.mjs +75 -37
  35. package/dist/table/create-table-def.cjs +17 -8
  36. package/dist/table/create-table-def.d.cts +5 -1
  37. package/dist/table/create-table-def.d.mts +5 -1
  38. package/dist/table/create-table-def.mjs +18 -9
  39. package/dist/table/types.d.cts +5 -2
  40. package/dist/table/types.d.mts +5 -2
  41. package/dist/table/value-kind.cjs +6 -6
  42. package/dist/table/value-kind.d.cts +8 -7
  43. package/dist/table/value-kind.d.mts +8 -7
  44. package/dist/table/value-kind.mjs +6 -6
  45. package/dist/value-help/extract-literals.cjs +61 -22
  46. package/dist/value-help/extract-literals.d.cts +20 -8
  47. package/dist/value-help/extract-literals.d.mts +20 -8
  48. package/dist/value-help/extract-literals.mjs +60 -23
  49. package/dist/value-help/index.d.mts +1 -1
  50. package/dist/value-help/resolve-options.cjs +8 -4
  51. package/dist/value-help/resolve-options.d.cts +8 -3
  52. package/dist/value-help/resolve-options.d.mts +8 -3
  53. package/dist/value-help/resolve-options.mjs +9 -5
  54. package/dist/value-help/resolve.cjs +7 -3
  55. package/dist/value-help/resolve.d.cts +7 -2
  56. package/dist/value-help/resolve.d.mts +7 -2
  57. package/dist/value-help/resolve.mjs +7 -3
  58. package/dist/value-help/types.d.cts +5 -0
  59. package/dist/value-help/types.d.mts +5 -0
  60. package/package.json +15 -10
@@ -13,8 +13,13 @@ import { AtscriptClientShape, Client, ClientOptions } from "@atscript/db-client"
13
13
  * given `metaKey` (e.g. the route template of a parametric mount). Since 0.1.153.
14
14
  * - `metaStore` — `false` during server rendering, so `/meta` bodies are never
15
15
  * kept in a process-wide store shared by every viewer. Since 0.1.153.
16
+ * - `locale` — the UI locale the client is for (`provideAsLocale` /
17
+ * `setUiLocale`), sent as `Accept-Language`: `/meta`, its action forms and
18
+ * error bodies come back in it. Set only when the app has a locale. Since 0.1.165.
16
19
  */
17
- type ClientFactoryOptions = Pick<ClientOptions, "metaKey" | "metaStore">;
20
+ type ClientFactoryOptions = Pick<ClientOptions, "metaKey" | "metaStore"> & {
21
+ locale?: string;
22
+ };
18
23
  /**
19
24
  * Factory that creates a `Client` for a given URL.
20
25
  *
@@ -13,8 +13,13 @@ import { AtscriptClientShape, Client, ClientOptions } from "@atscript/db-client"
13
13
  * given `metaKey` (e.g. the route template of a parametric mount). Since 0.1.153.
14
14
  * - `metaStore` — `false` during server rendering, so `/meta` bodies are never
15
15
  * kept in a process-wide store shared by every viewer. Since 0.1.153.
16
+ * - `locale` — the UI locale the client is for (`provideAsLocale` /
17
+ * `setUiLocale`), sent as `Accept-Language`: `/meta`, its action forms and
18
+ * error bodies come back in it. Set only when the app has a locale. Since 0.1.165.
16
19
  */
17
- type ClientFactoryOptions = Pick<ClientOptions, "metaKey" | "metaStore">;
20
+ type ClientFactoryOptions = Pick<ClientOptions, "metaKey" | "metaStore"> & {
21
+ locale?: string;
22
+ };
18
23
  /**
19
24
  * Factory that creates a `Client` for a given URL.
20
25
  *
@@ -1,5 +1,6 @@
1
1
  const require_annotation_keys = require("../shared/annotation-keys.cjs");
2
2
  const require_field_resolver = require("../shared/field-resolver.cjs");
3
+ const require_messages = require("../messages.cjs");
3
4
  const require_extract_literals = require("../value-help/extract-literals.cjs");
4
5
  const require_extract_ref = require("../value-help/extract-ref.cjs");
5
6
  const require_skipped_nav = require("./skipped-nav.cjs");
@@ -217,7 +218,7 @@ function buildFieldDef(path, prop, edit) {
217
218
  type: "array",
218
219
  customType: isTags ? "tags" : isMultiselect ? "multiselect" : customType,
219
220
  itemType: arrayType.of,
220
- itemField: createFieldDef("", arrayType.of, edit)
221
+ itemField: labelledBy(createFieldDef("", arrayType.of, edit), prop)
221
222
  };
222
223
  }
223
224
  if (kind === "object") return {
@@ -372,11 +373,20 @@ function isChildOfStructured(path, prefixes) {
372
373
  function buildUnionVariants(typeDef) {
373
374
  return createUnionVariants(typeDef, false);
374
375
  }
376
+ /**
377
+ * A scalar field inside `outer` (an array item, a union variant) also takes `outer`'s
378
+ * `@ui.literalLabel` labels — `flags: boolean[]`, `active: boolean | null`.
379
+ */
380
+ function labelledBy(field, outer) {
381
+ if (field.prop?.type.kind === "" && outer.metadata.has("ui.literalLabel")) field.labelsFrom = outer;
382
+ return field;
383
+ }
375
384
  function createUnionVariants(typeDef, edit) {
376
385
  const items = typeDef.type.items ?? [typeDef];
377
386
  const variants = [];
378
387
  for (const item of items) {
379
388
  const v = createVariant(item, edit);
389
+ if (v.itemField) labelledBy(v.itemField, typeDef);
380
390
  if (items.length > 1) v.label = `${String(variants.length + 1)}. ${v.label}`;
381
391
  variants.push(v);
382
392
  }
@@ -386,10 +396,10 @@ function createUnionVariants(typeDef, edit) {
386
396
  function createVariant(def, edit) {
387
397
  const kind = def.type.kind;
388
398
  if (kind === "object") {
389
- const label = require_field_resolver.getFieldMeta(def, "meta.label") ?? "Object";
399
+ const label = require_field_resolver.getFieldMeta(def, require_annotation_keys.META_LABEL);
390
400
  const hasComponent = require_field_resolver.getFieldMeta(def, require_annotation_keys.UI_FORM_COMPONENT) !== void 0;
391
401
  return {
392
- label,
402
+ ...label === void 0 ? typeLabel("object") : { label },
393
403
  type: def,
394
404
  def: buildFormDef(def, edit),
395
405
  itemField: hasComponent ? createFieldDef("", def, edit) : void 0
@@ -398,14 +408,14 @@ function createVariant(def, edit) {
398
408
  if (kind === "") {
399
409
  const dt = def.type.designType;
400
410
  return {
401
- label: capitalize(dt === "phantom" ? "item" : dt),
411
+ ...typeLabel(dt === "phantom" ? "item" : dt),
402
412
  type: def,
403
413
  itemField: createFieldDef("", def, edit),
404
414
  designType: dt
405
415
  };
406
416
  }
407
417
  return {
408
- label: capitalize(kind),
418
+ ...typeLabel(kind),
409
419
  type: def,
410
420
  itemField: createFieldDef("", def, edit)
411
421
  };
@@ -426,7 +436,7 @@ function soleValueMember(prop) {
426
436
  const members = /* @__PURE__ */ new Set();
427
437
  const visit = (t) => {
428
438
  if (t.type.kind === "union") for (const item of t.type.items) visit(item);
429
- else if (t.type.kind !== "" || t.type.designType !== "null" && t.type.designType !== "undefined") members.add(t);
439
+ else if (!require_extract_literals.isEmptyMember(t)) members.add(t);
430
440
  };
431
441
  visit(prop);
432
442
  return members.size === 1 ? members.values().next().value : void 0;
@@ -434,6 +444,18 @@ function soleValueMember(prop) {
434
444
  function capitalize(s) {
435
445
  return s.charAt(0).toUpperCase() + s.slice(1);
436
446
  }
447
+ /**
448
+ * A union variant's name for its type when it has no `@meta.label`: the
449
+ * English text of `UI_FORM_TYPE_*` with that code, worded at render time in
450
+ * the UI locale (a definition is built once, for every locale).
451
+ */
452
+ function typeLabel(kind) {
453
+ const code = `UI_FORM_TYPE_${kind.toUpperCase()}`;
454
+ return Object.hasOwn(require_messages.AS_UI_MESSAGES, code) ? {
455
+ label: require_messages.AS_UI_MESSAGES[code],
456
+ labelCode: code
457
+ } : { label: capitalize(kind) };
458
+ }
437
459
  //#endregion
438
460
  exports.buildUnionVariants = buildUnionVariants;
439
461
  exports.createFormDef = createFormDef;
@@ -1,6 +1,7 @@
1
1
  import { META_DESCRIPTION, META_LABEL, UI_FORM_COMPONENT, UI_FORM_PUSH_DOWN, UI_TYPE } from "../shared/annotation-keys.mjs";
2
2
  import { getFieldMeta, hasComputedAnnotations } from "../shared/field-resolver.mjs";
3
- import { isPureLiteralUnion } from "../value-help/extract-literals.mjs";
3
+ import { AS_UI_MESSAGES } from "../messages.mjs";
4
+ import { isEmptyMember, isPureLiteralUnion } from "../value-help/extract-literals.mjs";
4
5
  import { extractValueHelp } from "../value-help/extract-ref.mjs";
5
6
  import { isSkippedNavField } from "./skipped-nav.mjs";
6
7
  import { flattenAnnotatedType } from "@atscript/typescript/utils";
@@ -217,7 +218,7 @@ function buildFieldDef(path, prop, edit) {
217
218
  type: "array",
218
219
  customType: isTags ? "tags" : isMultiselect ? "multiselect" : customType,
219
220
  itemType: arrayType.of,
220
- itemField: createFieldDef("", arrayType.of, edit)
221
+ itemField: labelledBy(createFieldDef("", arrayType.of, edit), prop)
221
222
  };
222
223
  }
223
224
  if (kind === "object") return {
@@ -372,11 +373,20 @@ function isChildOfStructured(path, prefixes) {
372
373
  function buildUnionVariants(typeDef) {
373
374
  return createUnionVariants(typeDef, false);
374
375
  }
376
+ /**
377
+ * A scalar field inside `outer` (an array item, a union variant) also takes `outer`'s
378
+ * `@ui.literalLabel` labels — `flags: boolean[]`, `active: boolean | null`.
379
+ */
380
+ function labelledBy(field, outer) {
381
+ if (field.prop?.type.kind === "" && outer.metadata.has("ui.literalLabel")) field.labelsFrom = outer;
382
+ return field;
383
+ }
375
384
  function createUnionVariants(typeDef, edit) {
376
385
  const items = typeDef.type.items ?? [typeDef];
377
386
  const variants = [];
378
387
  for (const item of items) {
379
388
  const v = createVariant(item, edit);
389
+ if (v.itemField) labelledBy(v.itemField, typeDef);
380
390
  if (items.length > 1) v.label = `${String(variants.length + 1)}. ${v.label}`;
381
391
  variants.push(v);
382
392
  }
@@ -386,10 +396,10 @@ function createUnionVariants(typeDef, edit) {
386
396
  function createVariant(def, edit) {
387
397
  const kind = def.type.kind;
388
398
  if (kind === "object") {
389
- const label = getFieldMeta(def, "meta.label") ?? "Object";
399
+ const label = getFieldMeta(def, META_LABEL);
390
400
  const hasComponent = getFieldMeta(def, UI_FORM_COMPONENT) !== void 0;
391
401
  return {
392
- label,
402
+ ...label === void 0 ? typeLabel("object") : { label },
393
403
  type: def,
394
404
  def: buildFormDef(def, edit),
395
405
  itemField: hasComponent ? createFieldDef("", def, edit) : void 0
@@ -398,14 +408,14 @@ function createVariant(def, edit) {
398
408
  if (kind === "") {
399
409
  const dt = def.type.designType;
400
410
  return {
401
- label: capitalize(dt === "phantom" ? "item" : dt),
411
+ ...typeLabel(dt === "phantom" ? "item" : dt),
402
412
  type: def,
403
413
  itemField: createFieldDef("", def, edit),
404
414
  designType: dt
405
415
  };
406
416
  }
407
417
  return {
408
- label: capitalize(kind),
418
+ ...typeLabel(kind),
409
419
  type: def,
410
420
  itemField: createFieldDef("", def, edit)
411
421
  };
@@ -426,7 +436,7 @@ function soleValueMember(prop) {
426
436
  const members = /* @__PURE__ */ new Set();
427
437
  const visit = (t) => {
428
438
  if (t.type.kind === "union") for (const item of t.type.items) visit(item);
429
- else if (t.type.kind !== "" || t.type.designType !== "null" && t.type.designType !== "undefined") members.add(t);
439
+ else if (!isEmptyMember(t)) members.add(t);
430
440
  };
431
441
  visit(prop);
432
442
  return members.size === 1 ? members.values().next().value : void 0;
@@ -434,5 +444,17 @@ function soleValueMember(prop) {
434
444
  function capitalize(s) {
435
445
  return s.charAt(0).toUpperCase() + s.slice(1);
436
446
  }
447
+ /**
448
+ * A union variant's name for its type when it has no `@meta.label`: the
449
+ * English text of `UI_FORM_TYPE_*` with that code, worded at render time in
450
+ * the UI locale (a definition is built once, for every locale).
451
+ */
452
+ function typeLabel(kind) {
453
+ const code = `UI_FORM_TYPE_${kind.toUpperCase()}`;
454
+ return Object.hasOwn(AS_UI_MESSAGES, code) ? {
455
+ label: AS_UI_MESSAGES[code],
456
+ labelCode: code
457
+ } : { label: capitalize(kind) };
458
+ }
437
459
  //#endregion
438
460
  export { buildUnionVariants, createFormDef, findVersionColumn };
@@ -1,10 +1,13 @@
1
1
  require("../shared/annotation-keys.cjs");
2
2
  const require_field_resolver = require("../shared/field-resolver.cjs");
3
+ const require_ui_texts = require("../i18n/ui-texts.cjs");
3
4
  //#region src/form/labels.ts
4
- /** Singular label for an array field (used by AsArray for "Add <singular>"). */
5
- function resolveSingularLabel(meta) {
6
- if (!meta) return "item";
7
- return require_field_resolver.getFieldMeta(meta, "ui.form.label.singular") || "item";
5
+ /**
6
+ * Singular label for an array field (used by AsArray for "Add <singular>"):
7
+ * `@ui.form.label.singular`, else `t("UI_ITEM")` ("item").
8
+ */
9
+ function resolveSingularLabel(meta, t = require_ui_texts.getUiTexts().t) {
10
+ return meta && require_field_resolver.getFieldMeta(meta, "ui.form.label.singular") || t("UI_ITEM");
8
11
  }
9
12
  //#endregion
10
13
  exports.resolveSingularLabel = resolveSingularLabel;
@@ -1,7 +1,11 @@
1
+ import { UiT } from "../i18n/ui-texts.cjs";
1
2
  import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
2
3
 
3
4
  //#region src/form/labels.d.ts
4
- /** Singular label for an array field (used by AsArray for "Add <singular>"). */
5
- declare function resolveSingularLabel(meta: TAtscriptAnnotatedType | undefined): string;
5
+ /**
6
+ * Singular label for an array field (used by AsArray for "Add <singular>"):
7
+ * `@ui.form.label.singular`, else `t("UI_ITEM")` ("item").
8
+ */
9
+ declare function resolveSingularLabel(meta: TAtscriptAnnotatedType | undefined, t?: UiT): string;
6
10
  //#endregion
7
11
  export { resolveSingularLabel };
@@ -1,7 +1,11 @@
1
+ import { UiT } from "../i18n/ui-texts.mjs";
1
2
  import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
2
3
 
3
4
  //#region src/form/labels.d.ts
4
- /** Singular label for an array field (used by AsArray for "Add <singular>"). */
5
- declare function resolveSingularLabel(meta: TAtscriptAnnotatedType | undefined): string;
5
+ /**
6
+ * Singular label for an array field (used by AsArray for "Add <singular>"):
7
+ * `@ui.form.label.singular`, else `t("UI_ITEM")` ("item").
8
+ */
9
+ declare function resolveSingularLabel(meta: TAtscriptAnnotatedType | undefined, t?: UiT): string;
6
10
  //#endregion
7
11
  export { resolveSingularLabel };
@@ -1,10 +1,13 @@
1
1
  import "../shared/annotation-keys.mjs";
2
2
  import { getFieldMeta } from "../shared/field-resolver.mjs";
3
+ import { getUiTexts } from "../i18n/ui-texts.mjs";
3
4
  //#region src/form/labels.ts
4
- /** Singular label for an array field (used by AsArray for "Add <singular>"). */
5
- function resolveSingularLabel(meta) {
6
- if (!meta) return "item";
7
- return getFieldMeta(meta, "ui.form.label.singular") || "item";
5
+ /**
6
+ * Singular label for an array field (used by AsArray for "Add <singular>"):
7
+ * `@ui.form.label.singular`, else `t("UI_ITEM")` ("item").
8
+ */
9
+ function resolveSingularLabel(meta, t = getUiTexts().t) {
10
+ return meta && getFieldMeta(meta, "ui.form.label.singular") || t("UI_ITEM");
8
11
  }
9
12
  //#endregion
10
13
  export { resolveSingularLabel };
@@ -1,4 +1,5 @@
1
1
  import { TFormEntryOptions, ValueHelpInfo } from "../value-help/types.cjs";
2
+ import { AsUiMessageCode } from "../messages.cjs";
2
3
  import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
3
4
 
4
5
  //#region src/form/types.d.ts
@@ -65,6 +66,13 @@ interface FormFieldDef {
65
66
  * Since 0.1.144.
66
67
  */
67
68
  derived?: true;
69
+ /**
70
+ * The enclosing prop whose `@ui.literalLabel` labels also apply to this
71
+ * field's values: the array prop of an item field (`flags: boolean[]`) or the
72
+ * union prop of a variant (`active: boolean | null`). Set only when that prop
73
+ * declares labels; pass it to `resolveOptions` as `labelsFrom`. Since 0.1.165.
74
+ */
75
+ labelsFrom?: TAtscriptAnnotatedType;
68
76
  }
69
77
  /**
70
78
  * Complete form definition — produced by createFormDef().
@@ -90,6 +98,12 @@ interface FormDef {
90
98
  interface FormUnionVariant {
91
99
  /** Display label — from @meta.label or auto-generated (e.g. "1. String") */
92
100
  label: string;
101
+ /**
102
+ * The UI text code of an auto-generated label's type name
103
+ * (`UI_FORM_TYPE_STRING`); `label` ends with its English text. Render the
104
+ * name in the UI locale with it. Since 0.1.165.
105
+ */
106
+ labelCode?: AsUiMessageCode;
93
107
  /** The annotated type for this variant */
94
108
  type: TAtscriptAnnotatedType;
95
109
  /** Pre-built FormDef for object variants (undefined for primitives) */
@@ -1,4 +1,5 @@
1
1
  import { TFormEntryOptions, ValueHelpInfo } from "../value-help/types.mjs";
2
+ import { AsUiMessageCode } from "../messages.mjs";
2
3
  import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
3
4
 
4
5
  //#region src/form/types.d.ts
@@ -65,6 +66,13 @@ interface FormFieldDef {
65
66
  * Since 0.1.144.
66
67
  */
67
68
  derived?: true;
69
+ /**
70
+ * The enclosing prop whose `@ui.literalLabel` labels also apply to this
71
+ * field's values: the array prop of an item field (`flags: boolean[]`) or the
72
+ * union prop of a variant (`active: boolean | null`). Set only when that prop
73
+ * declares labels; pass it to `resolveOptions` as `labelsFrom`. Since 0.1.165.
74
+ */
75
+ labelsFrom?: TAtscriptAnnotatedType;
68
76
  }
69
77
  /**
70
78
  * Complete form definition — produced by createFormDef().
@@ -90,6 +98,12 @@ interface FormDef {
90
98
  interface FormUnionVariant {
91
99
  /** Display label — from @meta.label or auto-generated (e.g. "1. String") */
92
100
  label: string;
101
+ /**
102
+ * The UI text code of an auto-generated label's type name
103
+ * (`UI_FORM_TYPE_STRING`); `label` ends with its English text. Render the
104
+ * name in the UI locale with it. Since 0.1.165.
105
+ */
106
+ labelCode?: AsUiMessageCode;
93
107
  /** The annotated type for this variant */
94
108
  type: TAtscriptAnnotatedType;
95
109
  /** Pre-built FormDef for object variants (undefined for primitives) */
@@ -1,10 +1,26 @@
1
1
  require("../shared/annotation-keys.cjs");
2
2
  const require_types = require("./types.cjs");
3
+ const require_ui_texts = require("../i18n/ui-texts.cjs");
3
4
  const require_skipped_nav = require("./skipped-nav.cjs");
4
5
  const require_error_utils = require("./error-utils.cjs");
5
6
  let _atscript_typescript_utils = require("@atscript/typescript/utils");
7
+ let _atscript_db_validator = require("@atscript/db/validator");
6
8
  //#region src/form/validate.ts
7
- const dbPlugin = (0, require("@atscript/db/validator").createDbValidatorPlugin)();
9
+ /**
10
+ * `error`'s message in the language of `t` (looked up by code or text, see
11
+ * {@link TFormValidatorCallOptions.t}); the English message when `t` has none.
12
+ * Its `details` are dropped first: only the message is read.
13
+ */
14
+ function messageIn(error, t) {
15
+ return (0, _atscript_typescript_utils.localizeErrors)([{
16
+ ...error,
17
+ details: void 0
18
+ }], (id, params) => {
19
+ const text = t(id, params);
20
+ return text === id ? void 0 : text;
21
+ })[0].message;
22
+ }
23
+ const dbPlugin = (0, _atscript_db_validator.createDbValidatorPlugin)();
8
24
  const INSERT_CONTEXT = { mode: "insert" };
9
25
  /**
10
26
  * Always-on plugin for fields the server fills in, so a create form is not
@@ -67,20 +83,24 @@ function getDefaultValidatorPlugins() {
67
83
  return defaultValidatorPlugins;
68
84
  }
69
85
  /**
70
- * Returns a reusable validator function for a whole FormDef.
86
+ * Returns a reusable validator for a whole FormDef.
71
87
  *
72
88
  * Validator is created once and reused on every call.
73
89
  * ATScript's @expect.* validation runs automatically; server-managed db
74
90
  * fields (every `derived` field, absent `@db.default*` / version) pass.
75
91
  * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
76
92
  *
77
- * Errors are keyed by dotted path. A root-level error (a failing
78
- * `@ui.form.validate` on the form's interface) is keyed `__form`.
93
+ * It validates the data as given: apply `@normalize.*` first with its
94
+ * `normalize(data)` and validate (and submit) the result, as the server does.
95
+ *
96
+ * Errors are keyed by dotted path, worded in the language of `callOpts.t`.
97
+ * A root-level error (a failing `@ui.form.validate` on the form's interface)
98
+ * is keyed `__form`.
79
99
  */
80
100
  function getFormValidator(def, opts) {
81
101
  const derived = collectDerivedProps(def);
82
102
  const derivedPlugin = (_ctx, prop) => derived.has(prop) ? true : void 0;
83
- const validator = new _atscript_typescript_utils.Validator(def.type, {
103
+ const options = {
84
104
  unknownProps: "ignore",
85
105
  ...opts,
86
106
  plugins: [
@@ -89,14 +109,21 @@ function getFormValidator(def, opts) {
89
109
  ...defaultValidatorPlugins,
90
110
  ...opts?.plugins ?? []
91
111
  ]
92
- });
93
- return (callOpts) => {
112
+ };
113
+ const validator = new _atscript_typescript_utils.Validator(def.type, options);
114
+ const validate = (callOpts) => {
94
115
  if (validator.validate(callOpts.data, true, {
95
116
  data: callOpts.data,
96
- context: callOpts.context ?? {}
117
+ context: callOpts.context ?? {},
118
+ t: callOpts.t
97
119
  })) return {};
98
- return require_error_utils.validatorErrorsToMap(validator.errors);
120
+ const t = callOpts.t ?? require_ui_texts.getUiTexts().t;
121
+ return require_error_utils.validatorErrorsToMap(validator.errors.map((e) => ({
122
+ path: e.path,
123
+ message: messageIn(e, t)
124
+ })));
99
125
  };
126
+ return Object.assign(validate, { normalize: (data) => (0, _atscript_typescript_utils.normalizeForType)(def.type, data, options) });
100
127
  }
101
128
  /**
102
129
  * Root-only plugin: passes every descendant without visiting it. Only
@@ -119,27 +146,36 @@ function isContainerKind(kind) {
119
146
  * Creates a cached validator function for a single ATScript prop.
120
147
  *
121
148
  * The `Validator` instance is created lazily on first call and reused.
122
- * Returns `true` when valid, or the first error message string when invalid.
149
+ * Returns `true` when valid, or the first error message string when invalid,
150
+ * worded in the language of `externalCtx.t` (else `opts.t`, else the active
151
+ * UI texts) — looked up by the error's code, see {@link TFormValidatorCallOptions.t}.
152
+ * The value is judged with the prop's `@normalize.*` applied, as a submit
153
+ * judges it (the value itself is not changed).
123
154
  * With `rootOnly`, an object / array / tuple prop is validated at its root
124
155
  * only (descendants are not walked — their errors would be discarded anyway).
125
156
  */
126
157
  function createFieldValidator(prop, opts) {
127
158
  let cached;
159
+ let options;
160
+ const rootOfContainer = opts?.rootOnly === true && isContainerKind(prop.type.kind);
128
161
  return (value, externalCtx) => {
129
- cached ??= new _atscript_typescript_utils.Validator(prop, { plugins: opts?.rootOnly && isContainerKind(prop.type.kind) ? [
130
- skipDescendantsPlugin,
131
- serverManagedPlugin,
132
- ...defaultValidatorPlugins
133
- ] : [serverManagedPlugin, ...defaultValidatorPlugins] });
134
- if (!cached.validate(value, true, externalCtx)) {
135
- if (opts?.rootOnly) {
136
- const rootError = cached.errors?.find((e) => e.path === "");
137
- if (rootError) return rootError.message;
138
- return true;
139
- }
140
- return cached.errors?.[0]?.message || "Invalid value";
162
+ if (!cached) {
163
+ options = { plugins: rootOfContainer ? [
164
+ skipDescendantsPlugin,
165
+ serverManagedPlugin,
166
+ ...defaultValidatorPlugins
167
+ ] : [serverManagedPlugin, ...defaultValidatorPlugins] };
168
+ cached = new _atscript_typescript_utils.Validator(prop, options);
169
+ }
170
+ const judged = rootOfContainer ? value : (0, _atscript_typescript_utils.normalizeForType)(prop, value, options);
171
+ if (cached.validate(judged, true, externalCtx)) return true;
172
+ const t = externalCtx?.t ?? opts?.t ?? require_ui_texts.getUiTexts().t;
173
+ if (opts?.rootOnly) {
174
+ const rootError = cached.errors?.find((e) => e.path === "");
175
+ return rootError ? messageIn(rootError, t) : true;
141
176
  }
142
- return true;
177
+ const error = cached.errors?.[0];
178
+ return error && messageIn(error, t) || t("UI_INVALID_VALUE");
143
179
  };
144
180
  }
145
181
  //#endregion
@@ -1,4 +1,5 @@
1
1
  import { FormDef } from "./types.cjs";
2
+ import { UiT } from "../i18n/ui-texts.cjs";
2
3
  import { TAtscriptAnnotatedType, TValidatorOptions, TValidatorPlugin } from "@atscript/typescript/utils";
3
4
 
4
5
  //#region src/form/validate.d.ts
@@ -6,27 +7,52 @@ import { TAtscriptAnnotatedType, TValidatorOptions, TValidatorPlugin } from "@at
6
7
  interface TFormValidatorCallOptions {
7
8
  data: Record<string, unknown>;
8
9
  context?: Record<string, unknown>;
10
+ /**
11
+ * The app's texts: the `t` of `@ui.form.validate` rules and the language of
12
+ * every message — validator messages are looked up by their code
13
+ * (`MIN_LENGTH`, with the error's params) or, for a message of your own, by
14
+ * its text: your translator first, then the texts the server served
15
+ * (`/meta` `$i18n`). The active UI texts when omitted.
16
+ */
17
+ t?: UiT;
18
+ }
19
+ /** A form validator, see {@link getFormValidator}. Since 0.1.165 (before: a plain function). */
20
+ interface FormValidator {
21
+ (callOpts: TFormValidatorCallOptions): Record<string, string>;
22
+ /**
23
+ * `data` with the type's `@normalize.*` applied (trimmed, case-folded, …),
24
+ * judged with this validator's options — the value to validate and to
25
+ * submit. Copy-on-change: `data` itself when nothing changes; never
26
+ * validates. Since 0.1.165.
27
+ */
28
+ normalize<T>(data: T): T;
9
29
  }
10
30
  /** Replace the default validator plugins applied to every form/field validator. */
11
31
  declare function setDefaultValidatorPlugins(plugins: TValidatorPlugin[]): void;
12
32
  /** Get the currently registered default validator plugins. */
13
33
  declare function getDefaultValidatorPlugins(): TValidatorPlugin[];
14
34
  /**
15
- * Returns a reusable validator function for a whole FormDef.
35
+ * Returns a reusable validator for a whole FormDef.
16
36
  *
17
37
  * Validator is created once and reused on every call.
18
38
  * ATScript's @expect.* validation runs automatically; server-managed db
19
39
  * fields (every `derived` field, absent `@db.default*` / version) pass.
20
40
  * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
21
41
  *
22
- * Errors are keyed by dotted path. A root-level error (a failing
23
- * `@ui.form.validate` on the form's interface) is keyed `__form`.
42
+ * It validates the data as given: apply `@normalize.*` first with its
43
+ * `normalize(data)` and validate (and submit) the result, as the server does.
44
+ *
45
+ * Errors are keyed by dotted path, worded in the language of `callOpts.t`.
46
+ * A root-level error (a failing `@ui.form.validate` on the form's interface)
47
+ * is keyed `__form`.
24
48
  */
25
- declare function getFormValidator(def: FormDef, opts?: Partial<TValidatorOptions>): (callOpts: TFormValidatorCallOptions) => Record<string, string>;
49
+ declare function getFormValidator(def: FormDef, opts?: Partial<TValidatorOptions>): FormValidator;
26
50
  /** Options for createFieldValidator. */
27
51
  interface TFieldValidatorOptions {
28
52
  /** Only report errors at the root path (for structure/array container validation). */
29
53
  rootOnly?: boolean;
54
+ /** Words the fallback error (`UI_INVALID_VALUE`); the active UI texts when omitted. */
55
+ t?: UiT;
30
56
  }
31
57
  /**
32
58
  * Whether a type kind is a container that carries its own children:
@@ -38,13 +64,18 @@ declare function isContainerKind(kind: string): boolean;
38
64
  * Creates a cached validator function for a single ATScript prop.
39
65
  *
40
66
  * The `Validator` instance is created lazily on first call and reused.
41
- * Returns `true` when valid, or the first error message string when invalid.
67
+ * Returns `true` when valid, or the first error message string when invalid,
68
+ * worded in the language of `externalCtx.t` (else `opts.t`, else the active
69
+ * UI texts) — looked up by the error's code, see {@link TFormValidatorCallOptions.t}.
70
+ * The value is judged with the prop's `@normalize.*` applied, as a submit
71
+ * judges it (the value itself is not changed).
42
72
  * With `rootOnly`, an object / array / tuple prop is validated at its root
43
73
  * only (descendants are not walked — their errors would be discarded anyway).
44
74
  */
45
75
  declare function createFieldValidator(prop: TAtscriptAnnotatedType, opts?: TFieldValidatorOptions): (value: unknown, externalCtx?: {
46
76
  data: unknown;
47
77
  context: unknown;
78
+ t?: UiT;
48
79
  }) => true | string;
49
80
  //#endregion
50
- export { TFieldValidatorOptions, TFormValidatorCallOptions, createFieldValidator, getDefaultValidatorPlugins, getFormValidator, isContainerKind, setDefaultValidatorPlugins };
81
+ export { FormValidator, TFieldValidatorOptions, TFormValidatorCallOptions, createFieldValidator, getDefaultValidatorPlugins, getFormValidator, isContainerKind, setDefaultValidatorPlugins };
@@ -1,4 +1,5 @@
1
1
  import { FormDef } from "./types.mjs";
2
+ import { UiT } from "../i18n/ui-texts.mjs";
2
3
  import { TAtscriptAnnotatedType, TValidatorOptions, TValidatorPlugin } from "@atscript/typescript/utils";
3
4
 
4
5
  //#region src/form/validate.d.ts
@@ -6,27 +7,52 @@ import { TAtscriptAnnotatedType, TValidatorOptions, TValidatorPlugin } from "@at
6
7
  interface TFormValidatorCallOptions {
7
8
  data: Record<string, unknown>;
8
9
  context?: Record<string, unknown>;
10
+ /**
11
+ * The app's texts: the `t` of `@ui.form.validate` rules and the language of
12
+ * every message — validator messages are looked up by their code
13
+ * (`MIN_LENGTH`, with the error's params) or, for a message of your own, by
14
+ * its text: your translator first, then the texts the server served
15
+ * (`/meta` `$i18n`). The active UI texts when omitted.
16
+ */
17
+ t?: UiT;
18
+ }
19
+ /** A form validator, see {@link getFormValidator}. Since 0.1.165 (before: a plain function). */
20
+ interface FormValidator {
21
+ (callOpts: TFormValidatorCallOptions): Record<string, string>;
22
+ /**
23
+ * `data` with the type's `@normalize.*` applied (trimmed, case-folded, …),
24
+ * judged with this validator's options — the value to validate and to
25
+ * submit. Copy-on-change: `data` itself when nothing changes; never
26
+ * validates. Since 0.1.165.
27
+ */
28
+ normalize<T>(data: T): T;
9
29
  }
10
30
  /** Replace the default validator plugins applied to every form/field validator. */
11
31
  declare function setDefaultValidatorPlugins(plugins: TValidatorPlugin[]): void;
12
32
  /** Get the currently registered default validator plugins. */
13
33
  declare function getDefaultValidatorPlugins(): TValidatorPlugin[];
14
34
  /**
15
- * Returns a reusable validator function for a whole FormDef.
35
+ * Returns a reusable validator for a whole FormDef.
16
36
  *
17
37
  * Validator is created once and reused on every call.
18
38
  * ATScript's @expect.* validation runs automatically; server-managed db
19
39
  * fields (every `derived` field, absent `@db.default*` / version) pass.
20
40
  * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
21
41
  *
22
- * Errors are keyed by dotted path. A root-level error (a failing
23
- * `@ui.form.validate` on the form's interface) is keyed `__form`.
42
+ * It validates the data as given: apply `@normalize.*` first with its
43
+ * `normalize(data)` and validate (and submit) the result, as the server does.
44
+ *
45
+ * Errors are keyed by dotted path, worded in the language of `callOpts.t`.
46
+ * A root-level error (a failing `@ui.form.validate` on the form's interface)
47
+ * is keyed `__form`.
24
48
  */
25
- declare function getFormValidator(def: FormDef, opts?: Partial<TValidatorOptions>): (callOpts: TFormValidatorCallOptions) => Record<string, string>;
49
+ declare function getFormValidator(def: FormDef, opts?: Partial<TValidatorOptions>): FormValidator;
26
50
  /** Options for createFieldValidator. */
27
51
  interface TFieldValidatorOptions {
28
52
  /** Only report errors at the root path (for structure/array container validation). */
29
53
  rootOnly?: boolean;
54
+ /** Words the fallback error (`UI_INVALID_VALUE`); the active UI texts when omitted. */
55
+ t?: UiT;
30
56
  }
31
57
  /**
32
58
  * Whether a type kind is a container that carries its own children:
@@ -38,13 +64,18 @@ declare function isContainerKind(kind: string): boolean;
38
64
  * Creates a cached validator function for a single ATScript prop.
39
65
  *
40
66
  * The `Validator` instance is created lazily on first call and reused.
41
- * Returns `true` when valid, or the first error message string when invalid.
67
+ * Returns `true` when valid, or the first error message string when invalid,
68
+ * worded in the language of `externalCtx.t` (else `opts.t`, else the active
69
+ * UI texts) — looked up by the error's code, see {@link TFormValidatorCallOptions.t}.
70
+ * The value is judged with the prop's `@normalize.*` applied, as a submit
71
+ * judges it (the value itself is not changed).
42
72
  * With `rootOnly`, an object / array / tuple prop is validated at its root
43
73
  * only (descendants are not walked — their errors would be discarded anyway).
44
74
  */
45
75
  declare function createFieldValidator(prop: TAtscriptAnnotatedType, opts?: TFieldValidatorOptions): (value: unknown, externalCtx?: {
46
76
  data: unknown;
47
77
  context: unknown;
78
+ t?: UiT;
48
79
  }) => true | string;
49
80
  //#endregion
50
- export { TFieldValidatorOptions, TFormValidatorCallOptions, createFieldValidator, getDefaultValidatorPlugins, getFormValidator, isContainerKind, setDefaultValidatorPlugins };
81
+ export { FormValidator, TFieldValidatorOptions, TFormValidatorCallOptions, createFieldValidator, getDefaultValidatorPlugins, getFormValidator, isContainerKind, setDefaultValidatorPlugins };