@zeyos/zx 5.6.0 → 5.7.1
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/CHANGELOG.md +188 -0
- package/README.md +73 -7
- package/bin/zx-css.js +328 -0
- package/dist/types/components/account-menu/account-menu.d.ts +4 -2
- package/dist/types/components/activity-list/activity-list.d.ts +14 -8
- package/dist/types/components/agent-thread/ag-ui.d.ts +340 -0
- package/dist/types/components/agent-thread/agent-thread.d.ts +142 -14
- package/dist/types/components/agent-thread/ui-message-stream.d.ts +401 -0
- package/dist/types/components/app-sidebar/app-sidebar.d.ts +14 -8
- package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
- package/dist/types/components/calendar/calendar-model.d.ts +9 -2
- package/dist/types/components/calendar/calendar.d.ts +12 -4
- package/dist/types/components/chart/chart.d.ts +25 -13
- package/dist/types/components/checklist/checklist.d.ts +29 -0
- package/dist/types/components/code-editor/code-editor.d.ts +7 -2
- package/dist/types/components/composer/composer.d.ts +206 -4
- package/dist/types/components/composer/queue.d.ts +76 -0
- package/dist/types/components/copy/copy-button.d.ts +6 -4
- package/dist/types/components/copy/copy-input.d.ts +10 -6
- package/dist/types/components/datebox/date-range-box.d.ts +33 -0
- package/dist/types/components/datebox/placeholder.d.ts +7 -0
- package/dist/types/components/dialog/dialog.d.ts +2 -2
- package/dist/types/components/dock/dock.d.ts +12 -3
- package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
- package/dist/types/components/field-upload/field-upload.d.ts +3 -2
- package/dist/types/components/file-item/file-item.d.ts +3 -2
- package/dist/types/components/file-list/file-list.d.ts +14 -8
- package/dist/types/components/filter/filter-model.d.ts +31 -1
- package/dist/types/components/filter/filter.d.ts +20 -2
- package/dist/types/components/finder/finder.d.ts +14 -6
- package/dist/types/components/flag/flag.d.ts +99 -0
- package/dist/types/components/grid/grid.d.ts +1 -1
- package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
- package/dist/types/components/launcher/launcher.d.ts +2 -0
- package/dist/types/components/modal/modal.d.ts +34 -8
- package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
- package/dist/types/components/number-field/number-field.d.ts +41 -7
- package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
- package/dist/types/components/prose/prose.d.ts +9 -6
- package/dist/types/components/questionnaire/conditions.d.ts +270 -0
- package/dist/types/components/questionnaire/items.d.ts +52 -30
- package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
- package/dist/types/components/rating/rating.d.ts +5 -3
- package/dist/types/components/select/country.d.ts +106 -0
- package/dist/types/components/select/field-adapter.d.ts +2 -1
- package/dist/types/components/select/locale.d.ts +102 -0
- package/dist/types/components/select/select.d.ts +41 -2
- package/dist/types/components/sheet/sheet.d.ts +2 -2
- package/dist/types/components/slider/slider.d.ts +1 -0
- package/dist/types/components/sort-control/sort-control.d.ts +7 -3
- package/dist/types/components/source-list/source-list.d.ts +7 -5
- package/dist/types/components/split-view/split-view.d.ts +5 -3
- package/dist/types/components/surface/catalog.d.ts +260 -0
- package/dist/types/components/surface/elicit.d.ts +81 -0
- package/dist/types/components/surface/mcp.d.ts +165 -0
- package/dist/types/components/surface/schema.d.ts +314 -0
- package/dist/types/components/surface/stream.d.ts +118 -0
- package/dist/types/components/surface/surface.d.ts +718 -0
- package/dist/types/components/surface/text.d.ts +277 -0
- package/dist/types/components/surface/validate.d.ts +339 -0
- package/dist/types/components/table/table.d.ts +55 -3
- package/dist/types/components/table/window.d.ts +203 -0
- package/dist/types/components/toolbar/toolbar.d.ts +10 -6
- package/dist/types/components/tooltip/tooltip.d.ts +2 -2
- package/dist/types/components/tree/tree.d.ts +20 -13
- package/dist/types/core/component.d.ts +10 -0
- package/dist/types/core/date.d.ts +8 -1
- package/dist/types/core/dom.d.ts +15 -0
- package/dist/types/core/http.d.ts +10 -0
- package/dist/types/core/i18n.d.ts +38 -0
- package/dist/types/core/messages.d.ts +344 -1
- package/dist/types/core/storage.d.ts +7 -2
- package/dist/types/elements/define.d.ts +21 -46
- package/dist/types/elements/definitions.d.ts +147 -0
- package/dist/types/elements/kit.d.ts +7 -0
- package/dist/types/elements/reflect.d.ts +6 -3
- package/dist/types/index.d.ts +10 -1
- package/dist/types/internal/date-locale.d.ts +7 -0
- package/dist/types/internal/json-patch.d.ts +146 -0
- package/dist/types/locales/de.d.ts +13 -0
- package/dist/types/locales/en.d.ts +2 -0
- package/dist/types/locales/index.d.ts +823 -0
- package/dist/types/zeyos/view.d.ts +8 -1
- package/dist/zx-zeyos.esm.js +16852 -15131
- package/dist/zx-zeyos.esm.min.js +5 -5
- package/dist/zx.core.css +1276 -0
- package/dist/zx.core.min.css +1 -0
- package/dist/zx.css +520 -143
- package/dist/zx.esm.js +40940 -29684
- package/dist/zx.esm.min.js +36 -23
- package/dist/zx.global.js +40940 -29684
- package/dist/zx.global.min.js +36 -23
- package/dist/zx.layered.css +17315 -0
- package/dist/zx.layered.min.css +1 -0
- package/dist/zx.min.css +1 -1
- package/docs/agent-catalog.json +12501 -0
- package/docs/agent-surfaces.md +340 -0
- package/docs/api.json +909 -137
- package/docs/llms.md +1046 -80
- package/docs/llms.txt +30 -9
- package/package.json +29 -6
- package/src/components/account-menu/account-menu.js +6 -3
- package/src/components/activity-item/activity-item.js +2 -1
- package/src/components/activity-list/activity-list.js +16 -10
- package/src/components/agent-thread/ag-ui.js +1439 -0
- package/src/components/agent-thread/agent-thread.js +359 -54
- package/src/components/agent-thread/ui-message-stream.js +1281 -0
- package/src/components/app-sidebar/app-sidebar.js +18 -8
- package/src/components/approval-card/approval-card.js +3 -2
- package/src/components/block-view/block-view.js +7 -6
- package/src/components/breadcrumb/breadcrumb.js +8 -5
- package/src/components/button/button.css +24 -11
- package/src/components/calendar/calendar-model.js +8 -2
- package/src/components/calendar/calendar.js +53 -18
- package/src/components/chart/chart.js +54 -23
- package/src/components/checklist/checklist.css +9 -1
- package/src/components/checklist/checklist.js +59 -3
- package/src/components/checklist/field-adapter.js +2 -11
- package/src/components/code-editor/code-editor.js +45 -8
- package/src/components/code-editor/field-adapter.js +1 -1
- package/src/components/composer/composer.css +80 -1
- package/src/components/composer/composer.js +390 -16
- package/src/components/composer/queue.js +78 -0
- package/src/components/context-menu/context-menu.js +12 -1
- package/src/components/copy/copy-button.js +9 -7
- package/src/components/copy/copy-input.js +10 -6
- package/src/components/date-picker/date-picker.js +2 -1
- package/src/components/date-picker/date-range-picker.js +8 -7
- package/src/components/datebox/date-range-box.js +3 -9
- package/src/components/datebox/datebox.js +18 -21
- package/src/components/datebox/placeholder.js +18 -0
- package/src/components/dialog/dialog.js +4 -5
- package/src/components/dock/dock.js +34 -13
- package/src/components/entity-ref/entity-ref.js +16 -5
- package/src/components/field-upload/field-upload.js +81 -38
- package/src/components/file-item/file-item.js +70 -40
- package/src/components/file-list/file-list.js +15 -9
- package/src/components/filter/filter-model.js +46 -8
- package/src/components/filter/filter.css +3 -3
- package/src/components/filter/filter.js +29 -10
- package/src/components/filter-panel/filter-panel.js +13 -5
- package/src/components/finder/finder.js +50 -26
- package/src/components/flag/flag.css +40 -0
- package/src/components/flag/flag.js +177 -0
- package/src/components/form/form.js +1 -1
- package/src/components/grid/grid.js +22 -8
- package/src/components/kanban-view/kanban-view.js +51 -81
- package/src/components/launcher/launcher.js +17 -2
- package/src/components/list-toolbar/list-toolbar.js +2 -1
- package/src/components/master-panel/master-panel.js +1 -1
- package/src/components/menu-button/menu-button.js +4 -0
- package/src/components/message/message.js +3 -0
- package/src/components/modal/modal.js +62 -8
- package/src/components/multi-value-editor/multi-value-editor.js +10 -9
- package/src/components/navigation-bar/navigation-bar.js +3 -3
- package/src/components/number-field/number-field.js +98 -29
- package/src/components/prompt-starters/prompt-starters.css +91 -0
- package/src/components/prompt-starters/prompt-starters.js +206 -0
- package/src/components/prose/prose.js +14 -10
- package/src/components/questionnaire/conditions.js +666 -0
- package/src/components/questionnaire/items.js +150 -41
- package/src/components/questionnaire/questionnaire.js +126 -32
- package/src/components/rating/rating.js +5 -4
- package/src/components/run-status/run-status.js +2 -2
- package/src/components/select/country.js +136 -0
- package/src/components/select/field-adapter.js +7 -2
- package/src/components/select/locale.js +219 -0
- package/src/components/select/select.css +20 -22
- package/src/components/select/select.js +94 -12
- package/src/components/sheet/sheet-stack.js +10 -1
- package/src/components/sheet/sheet.js +12 -5
- package/src/components/slider/slider.js +7 -2
- package/src/components/sort-control/sort-control.js +15 -5
- package/src/components/source-list/source-list.js +7 -4
- package/src/components/split-view/split-view.js +5 -3
- package/src/components/surface/catalog.js +1334 -0
- package/src/components/surface/elicit.js +107 -0
- package/src/components/surface/mcp.js +243 -0
- package/src/components/surface/schema.js +644 -0
- package/src/components/surface/stream.js +245 -0
- package/src/components/surface/surface.css +308 -0
- package/src/components/surface/surface.js +2291 -0
- package/src/components/surface/text.js +513 -0
- package/src/components/surface/validate.js +2218 -0
- package/src/components/tabbox/tabbox.js +9 -0
- package/src/components/table/table.css +63 -3
- package/src/components/table/table.js +167 -28
- package/src/components/table/window.js +317 -0
- package/src/components/toolbar/toolbar.js +12 -7
- package/src/components/tooltip/tooltip.css +2 -3
- package/src/components/tooltip/tooltip.js +32 -5
- package/src/components/tree/tree.js +53 -23
- package/src/core/component.js +25 -1
- package/src/core/date.js +62 -16
- package/src/core/dom.js +67 -4
- package/src/core/format.js +15 -13
- package/src/core/http.js +29 -20
- package/src/core/i18n.js +83 -10
- package/src/core/icons.js +13 -2
- package/src/core/keyboard.js +79 -8
- package/src/core/messages.js +376 -2
- package/src/core/overlay-host.js +1 -0
- package/src/core/position.js +3 -2
- package/src/core/storage.js +59 -6
- package/src/elements/define.js +178 -130
- package/src/elements/definitions.js +229 -0
- package/src/elements/kit.js +444 -0
- package/src/elements/reflect.js +8 -3
- package/src/index.js +10 -1
- package/src/internal/date-locale.js +11 -0
- package/src/internal/json-patch.js +405 -0
- package/src/locales/de.js +911 -0
- package/src/locales/en.js +2 -0
- package/src/locales/index.js +7 -0
- package/src/zeyos/calendar.js +2 -1
- package/src/zeyos/form.js +2 -1
- package/src/zeyos/launcher.js +7 -6
- package/src/zeyos/module-bar.js +2 -1
- package/src/zeyos/schema.js +37 -23
- package/src/zeyos/select.js +4 -3
- package/src/zeyos/table.js +2 -13
- package/src/zeyos/view.js +57 -17
- package/styles/core.css +11 -0
- package/styles/tokens/semantic.css +1 -0
- package/styles/zeyos.css +2 -0
- package/styles/zx.css +4 -8
- package/styles/zx.layered.css +1 -0
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Declarative questionnaire logic: conditions, branch targets and validation rules written as
|
|
4
|
+
* plain JSON instead of functions, so they can be stored, sent and written by an agent.
|
|
5
|
+
*
|
|
6
|
+
* Everything here is pure and touches no DOM. The Questionnaire evaluates its items' `when`,
|
|
7
|
+
* `next` and `validate` with these functions, and so does anything else that shows or hides an
|
|
8
|
+
* input on a condition, so the two cannot drift.
|
|
9
|
+
* @module questionnaire/conditions
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The comparison a leaf condition makes.
|
|
14
|
+
* - `eq`, `ne`: equal, not equal. A number compares with a numeric string by value.
|
|
15
|
+
* - `in`, `nin`: the answer is (is not) one of `value`, a list. A multiple answer is "in" when any
|
|
16
|
+
* of its entries is.
|
|
17
|
+
* - `gt`, `gte`, `lt`, `lte`: two numbers by value, two strings in code-point order (so ISO dates
|
|
18
|
+
* and times compare correctly). Anything else is never greater or less.
|
|
19
|
+
* - A `Date` answer meets a string value in that value's shape: its local `YYYY-MM-DD` against a
|
|
20
|
+
* date, its local `YYYY-MM-DDTHH:MM` (`:SS` only when not zero) against a date-time.
|
|
21
|
+
* - A value is never `null`: an unanswered item has no answer to compare, so test it with `empty`.
|
|
22
|
+
* - `empty`, `filled`: the answer is (is not) absent: `null`, an empty or blank string, or a list
|
|
23
|
+
* with no non-empty entry. `false` and `0` are answers. These take no `value`.
|
|
24
|
+
* - `contains`: a multiple answer holds `value`, or a text answer contains the string `value`.
|
|
25
|
+
* @typedef {'eq'|'ne'|'in'|'nin'|'gt'|'gte'|'lt'|'lte'|'empty'|'filled'|'contains'} ConditionOp
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** @typedef {string|number|boolean|null} ConditionValue */
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A test of one answer.
|
|
32
|
+
* @typedef {Object} FieldCondition
|
|
33
|
+
* @property {string} field Name of the answer tested.
|
|
34
|
+
* @property {ConditionOp} op The comparison.
|
|
35
|
+
* @property {ConditionValue|ConditionValue[]} [value] What the answer is compared with: a list
|
|
36
|
+
* for `in` and `nin`, nothing for `empty` and `filled`, one value otherwise.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A condition: a field test, or `{all: […]}`, `{any: […]}` or `{not: …}` around further
|
|
41
|
+
* conditions, at most four levels deep counting the field test itself.
|
|
42
|
+
* @typedef {FieldCondition|{all: Condition[]}|{any: Condition[]}|{not: Condition}} Condition
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* One entry of a branch list: `goto` is taken when `if` holds, or always when there is no `if`.
|
|
47
|
+
* @typedef {Object} NextBranch
|
|
48
|
+
* @property {Condition} [if] Condition to test. Only the last entry may leave it out.
|
|
49
|
+
* @property {string} goto Item name, `$review` or `$submit`.
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Where an item leads: an item name, `$review` (the review screen), `$submit` (straight to
|
|
54
|
+
* submission), or a list of branches whose first match wins. No match falls through to the next
|
|
55
|
+
* visible item.
|
|
56
|
+
* @typedef {string|NextBranch[]} NextTarget
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* One validation rule. Each rule object carries exactly one rule key, and optionally the `message`
|
|
61
|
+
* shown when it fails in place of the default.
|
|
62
|
+
* - `{required: true}`: an answer must be given.
|
|
63
|
+
* - `{minLength: n}`, `{maxLength: n}`: characters of a text answer, or entries of a multiple one.
|
|
64
|
+
* - `{minimum: n}`, `{maximum: n}`: a number, or a numeric text answer.
|
|
65
|
+
* - `{format: 'date'|'date-time'|'time'|'email'|'uri'}`: `YYYY-MM-DD`, an ISO 8601 date and time,
|
|
66
|
+
* `HH:MM` or `HH:MM:SS`, an email address, an absolute URI.
|
|
67
|
+
* - `{oneOf: [values]}`: the answer, or every entry of a multiple one, is one of the values.
|
|
68
|
+
*
|
|
69
|
+
* Rules other than `required` pass an empty answer; there are no patterns.
|
|
70
|
+
* @typedef {Object} ValidationRule
|
|
71
|
+
* @property {boolean} [required] Whether an answer is needed.
|
|
72
|
+
* @property {number} [minLength] Fewest characters or entries.
|
|
73
|
+
* @property {number} [maxLength] Most characters or entries.
|
|
74
|
+
* @property {number} [minimum] Lowest number.
|
|
75
|
+
* @property {number} [maximum] Highest number.
|
|
76
|
+
* @property {RuleFormat} [format] Named format the text must follow.
|
|
77
|
+
* @property {ConditionValue[]} [oneOf] Allowed values.
|
|
78
|
+
* @property {string} [message] Text shown when this rule fails.
|
|
79
|
+
*/
|
|
80
|
+
|
|
81
|
+
/** @typedef {'date'|'date-time'|'time'|'email'|'uri'} RuleFormat */
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A problem found in a declarative condition, branch list or rule list. `path` is a JSON Pointer
|
|
85
|
+
* into the checked value (`''` for the value itself).
|
|
86
|
+
* @typedef {Object} ConditionProblem
|
|
87
|
+
* @property {string} path Where the problem is.
|
|
88
|
+
* @property {string} message What is wrong.
|
|
89
|
+
*/
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Turns a message key and its arguments into text. Keys are the rule names, `minItems` and
|
|
93
|
+
* `maxItems` for the list forms of `minLength` and `maxLength`, and the format name itself
|
|
94
|
+
* (`date`, `date-time`, `time`, `email`, `uri`) for a failed `format`.
|
|
95
|
+
* Called with the key and the interpolation values for `%1`, `%2`, ….
|
|
96
|
+
* @typedef {(key: string, ...args: unknown[]) => string} RuleMessage
|
|
97
|
+
*/
|
|
98
|
+
|
|
99
|
+
/** Deepest a condition may nest, counting the field test itself. */
|
|
100
|
+
export const MAX_CONDITION_DEPTH = 4;
|
|
101
|
+
|
|
102
|
+
/** Every comparison a field condition may make. */
|
|
103
|
+
export const CONDITION_OPS = Object.freeze(/** @type {ConditionOp[]} */ ([
|
|
104
|
+
'eq', 'ne', 'in', 'nin', 'gt', 'gte', 'lt', 'lte', 'empty', 'filled', 'contains'
|
|
105
|
+
]));
|
|
106
|
+
|
|
107
|
+
/** Every validation rule. */
|
|
108
|
+
export const RULE_NAMES = Object.freeze(['required', 'minLength', 'maxLength', 'minimum', 'maximum', 'format', 'oneOf']);
|
|
109
|
+
|
|
110
|
+
/** Every named format the `format` rule knows. */
|
|
111
|
+
export const RULE_FORMATS = Object.freeze(/** @type {RuleFormat[]} */ (['date', 'date-time', 'time', 'email', 'uri']));
|
|
112
|
+
|
|
113
|
+
/** The `next` target that opens the review screen. */
|
|
114
|
+
export const NEXT_REVIEW = '$review';
|
|
115
|
+
|
|
116
|
+
/** The `next` target that submits at once, skipping any review screen. */
|
|
117
|
+
export const NEXT_SUBMIT = '$submit';
|
|
118
|
+
|
|
119
|
+
/** English texts of the rule messages, keyed as `RuleMessage` describes. */
|
|
120
|
+
export const RULE_MESSAGES = Object.freeze({
|
|
121
|
+
required: 'Enter an answer to continue.',
|
|
122
|
+
minLength: 'Enter at least %1 characters.',
|
|
123
|
+
maxLength: 'Enter at most %1 characters.',
|
|
124
|
+
minItems: 'Choose at least %1.',
|
|
125
|
+
maxItems: 'Choose at most %1.',
|
|
126
|
+
minimum: 'Enter a number of at least %1.',
|
|
127
|
+
maximum: 'Enter a number of at most %1.',
|
|
128
|
+
oneOf: 'Choose one of the offered answers.',
|
|
129
|
+
date: 'Enter a date as YYYY-MM-DD.',
|
|
130
|
+
'date-time': 'Enter a date and time as YYYY-MM-DDTHH:MM.',
|
|
131
|
+
time: 'Enter a time as HH:MM.',
|
|
132
|
+
email: 'Enter an email address.',
|
|
133
|
+
uri: 'Enter a full address, such as https://example.com.'
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
const OPS = new Set(CONDITION_OPS);
|
|
137
|
+
const VALUELESS_OPS = new Set(['empty', 'filled']);
|
|
138
|
+
const LIST_OPS = new Set(['in', 'nin']);
|
|
139
|
+
const FORMATS = new Set(RULE_FORMATS);
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The English rule message for a key, with `%1` filled in. The default `RuleMessage`.
|
|
143
|
+
* @param {string} key Message key.
|
|
144
|
+
* @param {...unknown} args Interpolation values for `%1`, `%2`, ….
|
|
145
|
+
* @returns {string}
|
|
146
|
+
*/
|
|
147
|
+
export function ruleMessage(key, ...args) {
|
|
148
|
+
const text = /** @type {Record<string, string>} */ (RULE_MESSAGES)[key] ?? key;
|
|
149
|
+
return text.replace(/%(\d+)/g, (match, digit) => {
|
|
150
|
+
const value = args[Number(digit) - 1];
|
|
151
|
+
return value === undefined ? match : String(value);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Reports whether an answer counts as absent. An empty or blank string, a list with no non-empty
|
|
157
|
+
* entry, `null` and `undefined` are "no answer"; `false` and `0` are answers.
|
|
158
|
+
* @param {unknown} value Answer value.
|
|
159
|
+
* @returns {boolean}
|
|
160
|
+
*/
|
|
161
|
+
export function isEmptyAnswer(value) {
|
|
162
|
+
if (value == null) return true;
|
|
163
|
+
if (typeof value === 'string') return value.trim() === '';
|
|
164
|
+
if (Array.isArray(value)) return value.every((entry) => isEmptyAnswer(entry));
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Evaluates a condition against a set of answers. The caller decides which answers a condition
|
|
170
|
+
* may see; the Questionnaire hands each item only the answers of visible items declared before it.
|
|
171
|
+
* @param {Condition} condition Condition to evaluate.
|
|
172
|
+
* @param {Record<string, unknown>} answers Answers by name.
|
|
173
|
+
* @returns {boolean}
|
|
174
|
+
* @throws {TypeError} When the condition is malformed or nests deeper than four levels; check it
|
|
175
|
+
* first with `checkCondition()` to report rather than throw.
|
|
176
|
+
*/
|
|
177
|
+
export function evaluate(condition, answers) {
|
|
178
|
+
return evaluateAt(condition, answers ?? {}, 1);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* @param {unknown} condition @param {Record<string, unknown>} answers @param {number} depth
|
|
183
|
+
* @returns {boolean}
|
|
184
|
+
*/
|
|
185
|
+
function evaluateAt(condition, answers, depth) {
|
|
186
|
+
if (depth > MAX_CONDITION_DEPTH) {
|
|
187
|
+
throw new TypeError(`A condition may nest at most ${MAX_CONDITION_DEPTH} levels`);
|
|
188
|
+
}
|
|
189
|
+
if (!isPlainObject(condition)) throw new TypeError('A condition must be an object');
|
|
190
|
+
if (Object.hasOwn(condition, 'all')) {
|
|
191
|
+
return listOf(condition.all, 'all').every((entry) => evaluateAt(entry, answers, depth + 1));
|
|
192
|
+
}
|
|
193
|
+
if (Object.hasOwn(condition, 'any')) {
|
|
194
|
+
return listOf(condition.any, 'any').some((entry) => evaluateAt(entry, answers, depth + 1));
|
|
195
|
+
}
|
|
196
|
+
if (Object.hasOwn(condition, 'not')) return !evaluateAt(condition.not, answers, depth + 1);
|
|
197
|
+
|
|
198
|
+
const { field, op, value } = condition;
|
|
199
|
+
if (typeof field !== 'string' || field === '') throw new TypeError('A condition needs a "field"');
|
|
200
|
+
if (typeof op !== 'string' || !OPS.has(/** @type {ConditionOp} */ (op))) {
|
|
201
|
+
throw new TypeError(`Unknown condition op: ${String(op)}`);
|
|
202
|
+
}
|
|
203
|
+
if (LIST_OPS.has(op) && !Array.isArray(value)) throw new TypeError(`"${op}" needs a list as its value`);
|
|
204
|
+
const answer = Object.hasOwn(answers, field) ? comparable(answers[field]) : undefined;
|
|
205
|
+
return compare(/** @type {ConditionOp} */ (op), answer, value);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** @param {unknown} list @param {string} name @returns {unknown[]} */
|
|
209
|
+
function listOf(list, name) {
|
|
210
|
+
if (!Array.isArray(list)) throw new TypeError(`"${name}" needs a list of conditions`);
|
|
211
|
+
return list;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* @param {ConditionOp} op @param {unknown} answer @param {unknown} value
|
|
216
|
+
* @returns {boolean}
|
|
217
|
+
*/
|
|
218
|
+
function compare(op, answer, value) {
|
|
219
|
+
switch (op) {
|
|
220
|
+
case 'eq': return same(answer, value);
|
|
221
|
+
case 'ne': return !same(answer, value);
|
|
222
|
+
case 'in': return within(answer, /** @type {unknown[]} */ (value));
|
|
223
|
+
case 'nin': return !within(answer, /** @type {unknown[]} */ (value));
|
|
224
|
+
case 'gt': return order(answer, value) > 0;
|
|
225
|
+
case 'gte': return order(answer, value) >= 0;
|
|
226
|
+
case 'lt': return order(answer, value) < 0;
|
|
227
|
+
case 'lte': return order(answer, value) <= 0;
|
|
228
|
+
case 'empty': return isEmptyAnswer(answer);
|
|
229
|
+
case 'filled': return !isEmptyAnswer(answer);
|
|
230
|
+
case 'contains':
|
|
231
|
+
if (Array.isArray(answer)) return answer.some((entry) => same(comparable(entry), value));
|
|
232
|
+
return typeof answer === 'string' && typeof value === 'string' && answer.includes(value);
|
|
233
|
+
default: return false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** @param {unknown} answer @param {unknown[]} list @returns {boolean} */
|
|
238
|
+
function within(answer, list) {
|
|
239
|
+
if (Array.isArray(answer)) return answer.some((entry) => list.some((candidate) => same(comparable(entry), candidate)));
|
|
240
|
+
return list.some((candidate) => same(answer, candidate));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Equality of an answer and a condition value: identical, or a number and a numeric string with
|
|
245
|
+
* the same value.
|
|
246
|
+
* @param {unknown} answer @param {unknown} value @returns {boolean}
|
|
247
|
+
*/
|
|
248
|
+
function same(answer, value) {
|
|
249
|
+
if (answer === value) return true;
|
|
250
|
+
if (answer instanceof Date) {
|
|
251
|
+
if (typeof value !== 'string') return false;
|
|
252
|
+
const [left, right] = datePair(answer, value);
|
|
253
|
+
return left === right;
|
|
254
|
+
}
|
|
255
|
+
if (typeof value === 'number' && typeof answer === 'string') return toNumber(answer) === value;
|
|
256
|
+
if (typeof answer === 'number' && typeof value === 'string') return toNumber(value) === answer;
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Orders an answer against a value: negative, zero or positive, or `NaN` when they do not
|
|
262
|
+
* compare — which makes every ordering op false.
|
|
263
|
+
* @param {unknown} answer @param {unknown} value @returns {number}
|
|
264
|
+
*/
|
|
265
|
+
function order(answer, value) {
|
|
266
|
+
if (answer instanceof Date) {
|
|
267
|
+
if (typeof value !== 'string') return NaN;
|
|
268
|
+
const [left, right] = datePair(answer, value);
|
|
269
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
270
|
+
}
|
|
271
|
+
if (typeof value === 'number') {
|
|
272
|
+
const number = typeof answer === 'number' ? answer : typeof answer === 'string' ? toNumber(answer) : NaN;
|
|
273
|
+
return Number.isFinite(number) ? number - value : NaN;
|
|
274
|
+
}
|
|
275
|
+
if (typeof value === 'string' && typeof answer === 'string') return answer < value ? -1 : answer > value ? 1 : 0;
|
|
276
|
+
return NaN;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** @param {string} text @returns {number} NaN unless the whole text is a finite number. */
|
|
280
|
+
function toNumber(text) {
|
|
281
|
+
const trimmed = text.trim();
|
|
282
|
+
if (trimmed === '') return NaN;
|
|
283
|
+
const number = Number(trimmed);
|
|
284
|
+
return Number.isFinite(number) ? number : NaN;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Brings an answer into the shape conditions compare: an invalid `Date` counts as no answer. A
|
|
289
|
+
* valid one is kept, and compared through `datePair()` in the shape of the value it meets.
|
|
290
|
+
* @param {unknown} value @returns {unknown}
|
|
291
|
+
*/
|
|
292
|
+
function comparable(value) {
|
|
293
|
+
if (value instanceof Date && Number.isNaN(value.getTime())) return null;
|
|
294
|
+
return value;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** @param {number} number @returns {string} */
|
|
298
|
+
const pad = (number) => String(number).padStart(2, '0');
|
|
299
|
+
|
|
300
|
+
/** @param {Date} date @returns {string} The local `YYYY-MM-DD`. */
|
|
301
|
+
function localDate(date) {
|
|
302
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* A `Date` as a local date-time, `YYYY-MM-DDTHH:MM`, with `:SS` only when the seconds are not zero.
|
|
307
|
+
* @param {Date} date @returns {string}
|
|
308
|
+
*/
|
|
309
|
+
function localDateTime(date) {
|
|
310
|
+
const seconds = date.getSeconds() === 0 ? '' : `:${pad(date.getSeconds())}`;
|
|
311
|
+
return `${localDate(date)}T${pad(date.getHours())}:${pad(date.getMinutes())}${seconds}`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Puts a `Date` answer and a string value into one shape. Against a date-only value
|
|
316
|
+
* (`YYYY-MM-DD`) the answer's local date is compared; against anything else its local date-time,
|
|
317
|
+
* with a local date-time value normalised the same way (`T` separator, `:00` seconds dropped).
|
|
318
|
+
* @param {Date} date @param {string} value @returns {[string, string]}
|
|
319
|
+
*/
|
|
320
|
+
function datePair(date, value) {
|
|
321
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return [localDate(date), value];
|
|
322
|
+
const match = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})(?::(\d{2}))?$/i.exec(value);
|
|
323
|
+
const normalised = match ? `${match[1]}T${match[2]}${match[3] && match[3] !== '00' ? `:${match[3]}` : ''}` : value;
|
|
324
|
+
return [localDateTime(date), normalised];
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** @param {unknown} value @returns {string} Text a length rule measures. */
|
|
328
|
+
function textOf(value) {
|
|
329
|
+
return value instanceof Date ? localDateTime(value) : String(value);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Checks a condition's shape without evaluating it, and lists every problem rather than stopping
|
|
334
|
+
* at the first. With `fields`, a field test may only name one of them — how a caller limits a
|
|
335
|
+
* condition to the inputs declared before it.
|
|
336
|
+
* @param {unknown} condition Condition to check.
|
|
337
|
+
* @param {{fields?: Iterable<string>|null, maxDepth?: number}} [options]
|
|
338
|
+
* @returns {ConditionProblem[]} Empty when the condition is well-formed.
|
|
339
|
+
*/
|
|
340
|
+
export function checkCondition(condition, options = {}) {
|
|
341
|
+
const fields = options.fields == null ? null : new Set(options.fields);
|
|
342
|
+
const maxDepth = Math.min(options.maxDepth ?? MAX_CONDITION_DEPTH, MAX_CONDITION_DEPTH);
|
|
343
|
+
/** @type {ConditionProblem[]} */
|
|
344
|
+
const problems = [];
|
|
345
|
+
checkConditionAt(condition, '', 1, maxDepth, fields, problems);
|
|
346
|
+
return problems;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* @param {unknown} condition @param {string} path @param {number} depth @param {number} maxDepth
|
|
351
|
+
* @param {Set<string>|null} fields @param {ConditionProblem[]} problems
|
|
352
|
+
*/
|
|
353
|
+
function checkConditionAt(condition, path, depth, maxDepth, fields, problems) {
|
|
354
|
+
if (depth > maxDepth) {
|
|
355
|
+
problems.push({ path, message: `A condition may nest at most ${maxDepth} levels` });
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (!isPlainObject(condition)) {
|
|
359
|
+
problems.push({ path, message: 'A condition must be an object' });
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
const keys = Object.keys(condition);
|
|
363
|
+
const combinator = ['all', 'any', 'not'].find((key) => keys.includes(key));
|
|
364
|
+
if (combinator) {
|
|
365
|
+
if (keys.length !== 1) {
|
|
366
|
+
problems.push({ path, message: `"${combinator}" cannot be combined with other keys` });
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
if (combinator === 'not') {
|
|
370
|
+
checkConditionAt(condition.not, `${path}/not`, depth + 1, maxDepth, fields, problems);
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
const list = condition[combinator];
|
|
374
|
+
if (!Array.isArray(list) || list.length === 0) {
|
|
375
|
+
problems.push({ path: `${path}/${combinator}`, message: `"${combinator}" needs a non-empty list of conditions` });
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
list.forEach((entry, index) => checkConditionAt(entry, `${path}/${combinator}/${index}`, depth + 1, maxDepth, fields, problems));
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
for (const key of keys) {
|
|
383
|
+
if (key !== 'field' && key !== 'op' && key !== 'value') problems.push({ path: `${path}/${escape(key)}`, message: 'Unknown key' });
|
|
384
|
+
}
|
|
385
|
+
const { field, op } = condition;
|
|
386
|
+
if (typeof field !== 'string' || field === '') {
|
|
387
|
+
problems.push({ path: `${path}/field`, message: 'A condition needs a "field" naming an input' });
|
|
388
|
+
} else if (fields && !fields.has(field)) {
|
|
389
|
+
problems.push({ path: `${path}/field`, message: `"${field}" is not an input declared before this condition` });
|
|
390
|
+
}
|
|
391
|
+
if (typeof op !== 'string' || !OPS.has(/** @type {ConditionOp} */ (op))) {
|
|
392
|
+
problems.push({ path: `${path}/op`, message: `"op" must be one of ${CONDITION_OPS.join(', ')}` });
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
const hasValue = Object.hasOwn(condition, 'value');
|
|
396
|
+
const { value } = condition;
|
|
397
|
+
if (VALUELESS_OPS.has(op)) {
|
|
398
|
+
if (hasValue) problems.push({ path: `${path}/value`, message: `"${op}" takes no value` });
|
|
399
|
+
} else if (LIST_OPS.has(op)) {
|
|
400
|
+
if (!Array.isArray(value) || value.length === 0 || !value.every(isScalar)) {
|
|
401
|
+
problems.push({ path: `${path}/value`, message: `"${op}" needs a non-empty list of strings, numbers or booleans` });
|
|
402
|
+
} else if (value.includes(null)) {
|
|
403
|
+
// An unanswered item has no answer at all, so null would never match: say what does.
|
|
404
|
+
problems.push({ path: `${path}/value`, message: `"${op}" cannot test for null; use "empty" or "filled"` });
|
|
405
|
+
}
|
|
406
|
+
} else if (!hasValue || !isScalar(value)) {
|
|
407
|
+
problems.push({ path: `${path}/value`, message: `"${op}" needs a string, number or boolean value` });
|
|
408
|
+
} else if (value === null) {
|
|
409
|
+
problems.push({ path: `${path}/value`, message: `"${op}" cannot test for null; use "empty" or "filled"` });
|
|
410
|
+
} else if (['gt', 'gte', 'lt', 'lte'].includes(op) && typeof value !== 'number' && typeof value !== 'string') {
|
|
411
|
+
problems.push({ path: `${path}/value`, message: `"${op}" needs a number or a string` });
|
|
412
|
+
} else if (op === 'contains' && typeof value === 'object') {
|
|
413
|
+
problems.push({ path: `${path}/value`, message: '"contains" needs a string, number or boolean' });
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Resolves where an item leads, given its answer. A list's first entry whose `if` holds — or that
|
|
419
|
+
* has no `if` — wins; no match, like no `next`, gives `null`. A function form is called with the
|
|
420
|
+
* answer and the answers and its result returned as a name.
|
|
421
|
+
* @param {NextTarget|((answer: unknown, answers: Record<string, unknown>) => string|null)|null|undefined} next
|
|
422
|
+
* Branch target.
|
|
423
|
+
* @param {unknown} answer The item's own answer.
|
|
424
|
+
* @param {Record<string, unknown>} answers Answers the branch conditions may see.
|
|
425
|
+
* @returns {string|null} An item name, `$review`, `$submit`, or `null` to fall through.
|
|
426
|
+
* @throws {TypeError} When `next` or one of its conditions is malformed.
|
|
427
|
+
*/
|
|
428
|
+
export function resolveNext(next, answer, answers) {
|
|
429
|
+
if (next == null || next === '') return null;
|
|
430
|
+
if (typeof next === 'string') return next;
|
|
431
|
+
if (typeof next === 'function') {
|
|
432
|
+
const resolved = next(answer, answers);
|
|
433
|
+
return resolved == null || resolved === '' ? null : String(resolved);
|
|
434
|
+
}
|
|
435
|
+
if (!Array.isArray(next)) throw new TypeError('"next" must be a name, a list of branches, or a function');
|
|
436
|
+
for (const branch of next) {
|
|
437
|
+
if (!isPlainObject(branch) || typeof branch.goto !== 'string' || branch.goto === '') {
|
|
438
|
+
throw new TypeError('Each branch needs a "goto" name');
|
|
439
|
+
}
|
|
440
|
+
if (!Object.hasOwn(branch, 'if') || evaluate(/** @type {Condition} */ (branch.if), answers)) return branch.goto;
|
|
441
|
+
}
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Checks a declarative `next` without resolving it. With `targets`, every name must be one of
|
|
447
|
+
* them or a sentinel; with `fields`, branch conditions may only name those.
|
|
448
|
+
* @param {unknown} next Branch target to check.
|
|
449
|
+
* @param {{targets?: Iterable<string>|null, fields?: Iterable<string>|null}} [options]
|
|
450
|
+
* @returns {ConditionProblem[]} Empty when well-formed.
|
|
451
|
+
*/
|
|
452
|
+
export function checkNext(next, options = {}) {
|
|
453
|
+
const targets = options.targets == null ? null : new Set(options.targets);
|
|
454
|
+
/** @type {ConditionProblem[]} */
|
|
455
|
+
const problems = [];
|
|
456
|
+
/** @param {unknown} name @param {string} path */
|
|
457
|
+
const checkTarget = (name, path) => {
|
|
458
|
+
if (typeof name !== 'string' || name === '') problems.push({ path, message: 'A branch target must be a non-empty name' });
|
|
459
|
+
else if (targets && name !== NEXT_REVIEW && name !== NEXT_SUBMIT && !targets.has(name)) {
|
|
460
|
+
problems.push({ path, message: `Unknown target "${name}"` });
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
if (typeof next === 'string') {
|
|
464
|
+
checkTarget(next, '');
|
|
465
|
+
return problems;
|
|
466
|
+
}
|
|
467
|
+
if (!Array.isArray(next) || next.length === 0) {
|
|
468
|
+
problems.push({ path: '', message: '"next" must be a name or a non-empty list of branches' });
|
|
469
|
+
return problems;
|
|
470
|
+
}
|
|
471
|
+
next.forEach((branch, index) => {
|
|
472
|
+
const path = `/${index}`;
|
|
473
|
+
if (!isPlainObject(branch)) {
|
|
474
|
+
problems.push({ path, message: 'A branch must be an object' });
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
for (const key of Object.keys(branch)) {
|
|
478
|
+
if (key !== 'if' && key !== 'goto') problems.push({ path: `${path}/${escape(key)}`, message: 'Unknown key' });
|
|
479
|
+
}
|
|
480
|
+
checkTarget(branch.goto, `${path}/goto`);
|
|
481
|
+
if (Object.hasOwn(branch, 'if')) {
|
|
482
|
+
for (const problem of checkCondition(branch.if, { fields: options.fields })) {
|
|
483
|
+
problems.push({ path: `${path}/if${problem.path}`, message: problem.message });
|
|
484
|
+
}
|
|
485
|
+
} else if (index < next.length - 1) {
|
|
486
|
+
problems.push({ path, message: 'Only the last branch may leave out "if"; the ones after it are never reached' });
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
return problems;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Runs validation rules in order and returns the first failure's message: the rule's own
|
|
494
|
+
* `message`, or the default from `message`. Rules other than `required` pass an empty answer.
|
|
495
|
+
* @param {ValidationRule[]} rules Rules to run.
|
|
496
|
+
* @param {unknown} value The answer.
|
|
497
|
+
* @param {RuleMessage} [message=ruleMessage] Resolves a default message.
|
|
498
|
+
* @returns {string|null} The message, or `null` when every rule passes.
|
|
499
|
+
* @throws {TypeError} When a rule is malformed; check them first with `checkRuleList()`.
|
|
500
|
+
*/
|
|
501
|
+
export function checkRules(rules, value, message = ruleMessage) {
|
|
502
|
+
if (!Array.isArray(rules)) throw new TypeError('Validation rules must be a list');
|
|
503
|
+
const answer = comparable(value);
|
|
504
|
+
const empty = isEmptyAnswer(answer);
|
|
505
|
+
for (const rule of rules) {
|
|
506
|
+
const failure = failedRule(rule, answer, empty);
|
|
507
|
+
if (!failure) continue;
|
|
508
|
+
const own = /** @type {ValidationRule} */ (rule).message;
|
|
509
|
+
return typeof own === 'string' && own !== '' ? own : message(failure.key, ...failure.args);
|
|
510
|
+
}
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* @param {unknown} rule @param {unknown} answer @param {boolean} empty
|
|
516
|
+
* @returns {{key: string, args: unknown[]}|null}
|
|
517
|
+
*/
|
|
518
|
+
function failedRule(rule, answer, empty) {
|
|
519
|
+
const name = ruleName(rule);
|
|
520
|
+
if (!name) throw new TypeError('Each validation rule needs exactly one rule key');
|
|
521
|
+
const argument = /** @type {Record<string, unknown>} */ (rule)[name];
|
|
522
|
+
if (name === 'required') return argument === true && empty ? { key: 'required', args: [] } : null;
|
|
523
|
+
if (empty) return null;
|
|
524
|
+
|
|
525
|
+
switch (name) {
|
|
526
|
+
case 'minLength':
|
|
527
|
+
case 'maxLength': {
|
|
528
|
+
const limit = Number(argument);
|
|
529
|
+
const list = Array.isArray(answer);
|
|
530
|
+
const length = list ? /** @type {unknown[]} */ (answer).filter((entry) => !isEmptyAnswer(entry)).length
|
|
531
|
+
: [...textOf(answer)].length;
|
|
532
|
+
const failed = name === 'minLength' ? length < limit : length > limit;
|
|
533
|
+
const key = list ? (name === 'minLength' ? 'minItems' : 'maxItems') : name;
|
|
534
|
+
return failed ? { key, args: [limit] } : null;
|
|
535
|
+
}
|
|
536
|
+
case 'minimum':
|
|
537
|
+
case 'maximum': {
|
|
538
|
+
const limit = Number(argument);
|
|
539
|
+
const number = typeof answer === 'number' ? answer : typeof answer === 'string' ? toNumber(answer) : NaN;
|
|
540
|
+
const failed = !Number.isFinite(number) || (name === 'minimum' ? number < limit : number > limit);
|
|
541
|
+
return failed ? { key: name, args: [limit] } : null;
|
|
542
|
+
}
|
|
543
|
+
case 'format': {
|
|
544
|
+
const format = /** @type {RuleFormat} */ (argument);
|
|
545
|
+
const entries = Array.isArray(answer) ? answer.filter((entry) => !isEmptyAnswer(entry)) : [answer];
|
|
546
|
+
return entries.every((entry) => matchesFormat(format, comparable(entry))) ? null : { key: format, args: [] };
|
|
547
|
+
}
|
|
548
|
+
case 'oneOf': {
|
|
549
|
+
const allowed = /** @type {unknown[]} */ (argument);
|
|
550
|
+
const entries = Array.isArray(answer) ? answer.filter((entry) => !isEmptyAnswer(entry)) : [answer];
|
|
551
|
+
return entries.every((entry) => allowed.some((candidate) => same(entry, candidate))) ? null : { key: 'oneOf', args: [] };
|
|
552
|
+
}
|
|
553
|
+
default: return null;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** @param {unknown} rule @returns {string|null} The rule key, when there is exactly one. */
|
|
558
|
+
function ruleName(rule) {
|
|
559
|
+
if (!isPlainObject(rule)) return null;
|
|
560
|
+
const names = Object.keys(rule).filter((key) => RULE_NAMES.includes(key));
|
|
561
|
+
return names.length === 1 ? names[0] : null;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Checks a rule list's shape without running it, and lists every problem.
|
|
566
|
+
* @param {unknown} rules Rules to check.
|
|
567
|
+
* @returns {ConditionProblem[]} Empty when well-formed.
|
|
568
|
+
*/
|
|
569
|
+
export function checkRuleList(rules) {
|
|
570
|
+
/** @type {ConditionProblem[]} */
|
|
571
|
+
const problems = [];
|
|
572
|
+
if (!Array.isArray(rules)) return [{ path: '', message: 'Validation rules must be a list' }];
|
|
573
|
+
rules.forEach((rule, index) => {
|
|
574
|
+
const path = `/${index}`;
|
|
575
|
+
if (!isPlainObject(rule)) {
|
|
576
|
+
problems.push({ path, message: 'A rule must be an object' });
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
const names = Object.keys(rule).filter((key) => RULE_NAMES.includes(key));
|
|
580
|
+
for (const key of Object.keys(rule)) {
|
|
581
|
+
if (key !== 'message' && !RULE_NAMES.includes(key)) problems.push({ path: `${path}/${escape(key)}`, message: 'Unknown key' });
|
|
582
|
+
}
|
|
583
|
+
if (Object.hasOwn(rule, 'message') && typeof rule.message !== 'string') {
|
|
584
|
+
problems.push({ path: `${path}/message`, message: '"message" must be a string' });
|
|
585
|
+
}
|
|
586
|
+
if (names.length !== 1) {
|
|
587
|
+
problems.push({ path, message: `A rule needs exactly one of ${RULE_NAMES.join(', ')}` });
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
const name = names[0];
|
|
591
|
+
const argument = rule[name];
|
|
592
|
+
const at = `${path}/${name}`;
|
|
593
|
+
if (name === 'required' && typeof argument !== 'boolean') problems.push({ path: at, message: '"required" must be true or false' });
|
|
594
|
+
if ((name === 'minLength' || name === 'maxLength') && !(Number.isInteger(argument) && /** @type {number} */ (argument) >= 0)) {
|
|
595
|
+
problems.push({ path: at, message: `"${name}" must be a whole number of zero or more` });
|
|
596
|
+
}
|
|
597
|
+
if ((name === 'minimum' || name === 'maximum') && !(typeof argument === 'number' && Number.isFinite(argument))) {
|
|
598
|
+
problems.push({ path: at, message: `"${name}" must be a finite number` });
|
|
599
|
+
}
|
|
600
|
+
if (name === 'format' && !FORMATS.has(/** @type {RuleFormat} */ (argument))) {
|
|
601
|
+
problems.push({ path: at, message: `"format" must be one of ${RULE_FORMATS.join(', ')}` });
|
|
602
|
+
}
|
|
603
|
+
if (name === 'oneOf' && !(Array.isArray(argument) && argument.length > 0 && argument.every(isScalar))) {
|
|
604
|
+
problems.push({ path: at, message: '"oneOf" needs a non-empty list of strings, numbers, booleans or null' });
|
|
605
|
+
}
|
|
606
|
+
});
|
|
607
|
+
return problems;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Reports whether a value follows a named format.
|
|
612
|
+
* @param {RuleFormat} format @param {unknown} value @returns {boolean}
|
|
613
|
+
*/
|
|
614
|
+
function matchesFormat(format, value) {
|
|
615
|
+
// A Date or date-time Field answers with a Date: it is a date, and a date-time, whatever its time.
|
|
616
|
+
if (value instanceof Date) return format === 'date' || format === 'date-time';
|
|
617
|
+
if (typeof value !== 'string') return false;
|
|
618
|
+
switch (format) {
|
|
619
|
+
case 'date': return isDate(value);
|
|
620
|
+
case 'date-time': {
|
|
621
|
+
const match = /^(\d{4}-\d{2}-\d{2})[T ]([0-2]\d:[0-5]\d(?::[0-5]\d(?:\.\d+)?)?)(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)?$/i.exec(value);
|
|
622
|
+
return Boolean(match) && isDate(match[1]) && isTime(match[2].replace(/\.\d+$/, ''));
|
|
623
|
+
}
|
|
624
|
+
case 'time': return isTime(value);
|
|
625
|
+
case 'email': return /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/.test(value);
|
|
626
|
+
case 'uri':
|
|
627
|
+
if (!/^[a-z][a-z0-9+.-]*:\S+$/i.test(value)) return false;
|
|
628
|
+
try {
|
|
629
|
+
new URL(value);
|
|
630
|
+
return true;
|
|
631
|
+
} catch {
|
|
632
|
+
return false;
|
|
633
|
+
}
|
|
634
|
+
default: return false;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** @param {string} value @returns {boolean} A real calendar date written `YYYY-MM-DD`. */
|
|
639
|
+
function isDate(value) {
|
|
640
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
641
|
+
if (!match) return false;
|
|
642
|
+
const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
643
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
644
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** @param {string} value @returns {boolean} `HH:MM` or `HH:MM:SS` on a 24-hour clock. */
|
|
648
|
+
function isTime(value) {
|
|
649
|
+
return /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(value);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
653
|
+
function isPlainObject(value) {
|
|
654
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** @param {unknown} value @returns {boolean} */
|
|
658
|
+
function isScalar(value) {
|
|
659
|
+
return value === null || typeof value === 'string' || typeof value === 'boolean'
|
|
660
|
+
|| (typeof value === 'number' && Number.isFinite(value));
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/** @param {string} key @returns {string} The key as one JSON Pointer segment. */
|
|
664
|
+
function escape(key) {
|
|
665
|
+
return key.replace(/~/g, '~0').replace(/\//g, '~1');
|
|
666
|
+
}
|