@grafctory/blue 0.0.0-stage → 0.15.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.
Files changed (139) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +509 -2
  3. package/dist/boolean/assembler.d.ts +53 -0
  4. package/dist/boolean/assembler.d.ts.map +1 -0
  5. package/dist/boolean/assembler.js +78 -0
  6. package/dist/boolean/assembler.js.map +1 -0
  7. package/dist/boolean/index.d.ts +86 -0
  8. package/dist/boolean/index.d.ts.map +1 -0
  9. package/dist/boolean/index.js +99 -0
  10. package/dist/boolean/index.js.map +1 -0
  11. package/dist/boolean/validator.d.ts +30 -0
  12. package/dist/boolean/validator.d.ts.map +1 -0
  13. package/dist/boolean/validator.js +68 -0
  14. package/dist/boolean/validator.js.map +1 -0
  15. package/dist/dictionary/assembler.d.ts +70 -0
  16. package/dist/dictionary/assembler.d.ts.map +1 -0
  17. package/dist/dictionary/assembler.js +154 -0
  18. package/dist/dictionary/assembler.js.map +1 -0
  19. package/dist/dictionary/index.d.ts +211 -0
  20. package/dist/dictionary/index.d.ts.map +1 -0
  21. package/dist/dictionary/index.js +43 -0
  22. package/dist/dictionary/index.js.map +1 -0
  23. package/dist/dictionary/inference.d.ts +42 -0
  24. package/dist/dictionary/inference.d.ts.map +1 -0
  25. package/dist/dictionary/inference.js +17 -0
  26. package/dist/dictionary/inference.js.map +1 -0
  27. package/dist/dictionary/validator.d.ts +34 -0
  28. package/dist/dictionary/validator.d.ts.map +1 -0
  29. package/dist/dictionary/validator.js +91 -0
  30. package/dist/dictionary/validator.js.map +1 -0
  31. package/dist/index.core.d.ts +33 -0
  32. package/dist/index.core.d.ts.map +1 -0
  33. package/dist/index.core.js +149 -0
  34. package/dist/index.core.js.map +1 -0
  35. package/dist/index.d.ts +333 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +378 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/number/assembler.d.ts +70 -0
  40. package/dist/number/assembler.d.ts.map +1 -0
  41. package/dist/number/assembler.js +188 -0
  42. package/dist/number/assembler.js.map +1 -0
  43. package/dist/number/index.d.ts +329 -0
  44. package/dist/number/index.d.ts.map +1 -0
  45. package/dist/number/index.js +312 -0
  46. package/dist/number/index.js.map +1 -0
  47. package/dist/number/validator.d.ts +31 -0
  48. package/dist/number/validator.d.ts.map +1 -0
  49. package/dist/number/validator.js +57 -0
  50. package/dist/number/validator.js.map +1 -0
  51. package/dist/reference/accessors.d.ts +29 -0
  52. package/dist/reference/accessors.d.ts.map +1 -0
  53. package/dist/reference/accessors.js +38 -0
  54. package/dist/reference/accessors.js.map +1 -0
  55. package/dist/reference/assembler.d.ts +63 -0
  56. package/dist/reference/assembler.d.ts.map +1 -0
  57. package/dist/reference/assembler.js +127 -0
  58. package/dist/reference/assembler.js.map +1 -0
  59. package/dist/reference/index.d.ts +108 -0
  60. package/dist/reference/index.d.ts.map +1 -0
  61. package/dist/reference/index.js +40 -0
  62. package/dist/reference/index.js.map +1 -0
  63. package/dist/reference/validator.d.ts +33 -0
  64. package/dist/reference/validator.d.ts.map +1 -0
  65. package/dist/reference/validator.js +56 -0
  66. package/dist/reference/validator.js.map +1 -0
  67. package/dist/resource/accessors.d.ts +140 -0
  68. package/dist/resource/accessors.d.ts.map +1 -0
  69. package/dist/resource/accessors.js +173 -0
  70. package/dist/resource/accessors.js.map +1 -0
  71. package/dist/resource/assembler.d.ts +265 -0
  72. package/dist/resource/assembler.d.ts.map +1 -0
  73. package/dist/resource/assembler.js +816 -0
  74. package/dist/resource/assembler.js.map +1 -0
  75. package/dist/resource/index.d.ts +898 -0
  76. package/dist/resource/index.d.ts.map +1 -0
  77. package/dist/resource/index.js +160 -0
  78. package/dist/resource/index.js.map +1 -0
  79. package/dist/resource/inference.d.ts +310 -0
  80. package/dist/resource/inference.d.ts.map +1 -0
  81. package/dist/resource/inference.js +17 -0
  82. package/dist/resource/inference.js.map +1 -0
  83. package/dist/resource/validator.d.ts +158 -0
  84. package/dist/resource/validator.d.ts.map +1 -0
  85. package/dist/resource/validator.js +1031 -0
  86. package/dist/resource/validator.js.map +1 -0
  87. package/dist/string/assembler.d.ts +69 -0
  88. package/dist/string/assembler.d.ts.map +1 -0
  89. package/dist/string/assembler.js +143 -0
  90. package/dist/string/assembler.js.map +1 -0
  91. package/dist/string/index.d.ts +431 -0
  92. package/dist/string/index.d.ts.map +1 -0
  93. package/dist/string/index.js +528 -0
  94. package/dist/string/index.js.map +1 -0
  95. package/dist/string/validator.d.ts +30 -0
  96. package/dist/string/validator.d.ts.map +1 -0
  97. package/dist/string/validator.js +69 -0
  98. package/dist/string/validator.js.map +1 -0
  99. package/dist/union/accessors.d.ts +137 -0
  100. package/dist/union/accessors.d.ts.map +1 -0
  101. package/dist/union/accessors.js +253 -0
  102. package/dist/union/accessors.js.map +1 -0
  103. package/dist/union/assembler.d.ts +56 -0
  104. package/dist/union/assembler.d.ts.map +1 -0
  105. package/dist/union/assembler.js +140 -0
  106. package/dist/union/assembler.js.map +1 -0
  107. package/dist/union/index.d.ts +172 -0
  108. package/dist/union/index.d.ts.map +1 -0
  109. package/dist/union/index.js +45 -0
  110. package/dist/union/index.js.map +1 -0
  111. package/dist/union/inference.d.ts +30 -0
  112. package/dist/union/inference.d.ts.map +1 -0
  113. package/dist/union/inference.js +17 -0
  114. package/dist/union/inference.js.map +1 -0
  115. package/dist/union/validator.d.ts +94 -0
  116. package/dist/union/validator.d.ts.map +1 -0
  117. package/dist/union/validator.js +171 -0
  118. package/dist/union/validator.js.map +1 -0
  119. package/dist/value/accessors.d.ts +151 -0
  120. package/dist/value/accessors.d.ts.map +1 -0
  121. package/dist/value/accessors.js +468 -0
  122. package/dist/value/accessors.js.map +1 -0
  123. package/dist/value/assembler.d.ts +129 -0
  124. package/dist/value/assembler.d.ts.map +1 -0
  125. package/dist/value/assembler.js +248 -0
  126. package/dist/value/assembler.js.map +1 -0
  127. package/dist/value/index.d.ts +309 -0
  128. package/dist/value/index.d.ts.map +1 -0
  129. package/dist/value/index.js +26 -0
  130. package/dist/value/index.js.map +1 -0
  131. package/dist/value/inference.d.ts +292 -0
  132. package/dist/value/inference.d.ts.map +1 -0
  133. package/dist/value/inference.js +17 -0
  134. package/dist/value/inference.js.map +1 -0
  135. package/dist/value/validator.d.ts +76 -0
  136. package/dist/value/validator.d.ts.map +1 -0
  137. package/dist/value/validator.js +111 -0
  138. package/dist/value/validator.js.map +1 -0
  139. package/package.json +95 -4
@@ -0,0 +1,1031 @@
1
+ /*
2
+ * Copyright © 2025-2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * Resource state and template validation.
18
+ *
19
+ * Holds a value to what a shape admits and reports everything wrong with it at once, keyed by the member at fault:
20
+ * {@link validateResource} for a resource in its own right, {@link validateResult} for one that came back narrowed by
21
+ * the template that asked for it, and {@link validateTemplate} for a template itself, so that a request is refused
22
+ * before it is issued rather than after it is served.
23
+ *
24
+ * @module
25
+ */
26
+ import { isArray, isIdentifier, isNumber, isObject, isString, opt as fold } from "@grafctory/core";
27
+ import { isTagRange } from "@grafctory/core/language";
28
+ import { all, array, fail, object } from "@grafctory/core/trace";
29
+ import { isReference, isVacuous } from "@grafctory/qest/state";
30
+ import { decodeProbe, isAggregate, isAtomic, isBinding, isBranch, isSelector, isTemplate } from "@grafctory/qest/model";
31
+ import { eager, effective } from "../value/index.js";
32
+ import { match, validateShape } from "../value/validator.js";
33
+ import { getModelBranches, getShapeBranches } from "../union/index.js";
34
+ import { checkBound, checkOption, isTemplateModel } from "../union/validator.js";
35
+ import { getShapeTarget } from "../reference/index.js";
36
+ /**
37
+ * Validates values against a resource shape.
38
+ *
39
+ * Reports a value that is not a resource as a `{kind}` violation and each member that breaks a constraint under its
40
+ * own facet, keyed by the member it is stated under, so that a caller may tell which member failed and why. A resource
41
+ * shape is closed: a value carrying a member the shape doesn't declare is rejected.
42
+ *
43
+ * The custom {@link ResourceShape.validators | checks} a shape states run at `"state"` scope alone, each reporting
44
+ * under the name of the check: a template matched by form carries no values for them to read.
45
+ *
46
+ * A captive member is stated either as the link naming its target or as the resource itself, held in turn to the
47
+ * target shape, so that a resource and the ones it holds captive travel as a single value; `depth` caps how far the
48
+ * expansion reaches. A foreign member is written by the resources it points at, so a value stating one is rejected.
49
+ *
50
+ * A member ranging over a {@link dictionary!DictionaryShape | dictionary} states the language map whole, whatever
51
+ * bounds it carries: a map wrapped in an array is rejected, as is one stated beside values of other alternatives, and
52
+ * the bounds are held against those other values alone.
53
+ *
54
+ * A member ranging over resources treats a record carrying no content at any depth, such as `{}` or `{ detail: {} }`,
55
+ * as a value left unstated. Such a record doesn't count toward the member's bounds, so a required member stated only
56
+ * that way is reported as missing. A member ranging over plain values rejects the same record as a value of the wrong
57
+ * kind.
58
+ *
59
+ * @param values The values to validate
60
+ * @param shape The shape the values are matched against
61
+ * @param opts Validation options
62
+ * @param opts.scope The {@link Scope | strictness} the shape is enforced at, defaulting to `"state"`
63
+ * @param opts.entry The identifier the resources are expected to be named by, where they state one at all
64
+ * @param opts.depth The nesting a captive member may be expanded to, counting each resource it descends into; `0`
65
+ * refuses every expansion while still admitting the identifier naming the resource
66
+ *
67
+ * @returns A trace of the violations found, or `undefined` where every value matches `shape`
68
+ */
69
+ export function validateResource(values, shape, { scope = "state", entry, depth } = {}) {
70
+ return all(
71
+ // an embedded resource naming itself is told from an expanded link only here, against a value
72
+ () => checkId(shape), () => resources(values, shape, resource => all(
73
+ // every member the shape declares, keyed by its name
74
+ ...Object.entries(shape.members).map(([name, declared]) => () => fold(declared.kind === "id" ? identifier(resource[name], shape, entry)
75
+ : declared.kind === "type" ? classifier(resource[name], shape)
76
+ : contents(resource[name], declared), trace => [{ [name]: trace }])),
77
+ // the shape is closed, so a field it doesn't declare is rejected
78
+ ...Object.keys(resource)
79
+ .filter(name => !Object.hasOwn(shape.members, name))
80
+ .map(name => () => [{ [name]: ["unexpected member"] }]),
81
+ // the checks the shape states on top of its members, held against full states alone
82
+ ...(scope === "state" ? checks(resource, shape) : []))(undefined)))(undefined);
83
+ /**
84
+ * Validates the values a member carries against its range and cardinality.
85
+ */
86
+ function contents(value, member) {
87
+ const { range: { minCount, maxCount, shape: range }, foreign, captive } = member;
88
+ // a foreign member is written by the resources it points at, not by the one exposing it
89
+ if (foreign) {
90
+ return value !== undefined ? ["unexpected foreign member"] : undefined;
91
+ }
92
+ const resolved = eager(range);
93
+ const branches = getShapeBranches(resolved);
94
+ // a member reaching a resource reads a record carrying no content at any depth as nothing stated, as a resource
95
+ // stating no member at all names nothing to hold; one reaching a value reads it as a value of the wrong kind
96
+ const nesting = branches.some(branch => branch.kind === "reference" || branch.kind === "resource");
97
+ // a localised value is a value set in its own right, holding its strings per tag at the arity its own shape
98
+ // states: a member carries it whole, never in an array and never beside the other values, and the bounds
99
+ // stated for the member count the other values alone
100
+ const present = value === undefined || isArray(value, []) || nesting && isVacuous(value) ? undefined : value;
101
+ const carried = (present === undefined ? [] : isArray(present) ? present : [present])
102
+ .filter(element => !(nesting && isVacuous(element)));
103
+ const whole = isLocalised(present, branches, scope);
104
+ const bounds = whole ? undefined : all((minCount !== undefined && carried.length < minCount)
105
+ && fail([`{minCount} expected at least <${minCount}> value(s)`]), (maxCount !== undefined && carried.length > maxCount)
106
+ && fail([`{maxCount} expected at most <${maxCount}> value(s)`]))(undefined);
107
+ // the arity is reported first, then the values, then the cardinality
108
+ return (whole ? undefined : arity(present, maxCount, branches, scope))
109
+ ?? elements(carried, resolved, captive)
110
+ ?? bounds;
111
+ }
112
+ /**
113
+ * Validates the elements a member carries, expanding the ones it holds captive.
114
+ */
115
+ function elements(carried, range, captive) {
116
+ const branches = getShapeBranches(range);
117
+ const [branch] = branches;
118
+ // captivity is stated on the member, so it reaches a target named through an alternative as well as a bare
119
+ // one: a sole alternative reports the obstacles it found, several are told apart by the one admitting the value
120
+ return !captive || !branches.some(alternative => alternative.kind === "reference")
121
+ ? validateShape(carried, range, { scope })
122
+ : branches.length === 1 && branch.kind === "reference"
123
+ ? array((value) => expanded(value, branch))(carried)
124
+ : array((value) => admitting(value, branches))(carried);
125
+ }
126
+ /**
127
+ * Validates a captive element against several alternatives, expanding the ones naming a resource.
128
+ */
129
+ function admitting(value, branches) {
130
+ return verdict(branches.filter(alternative => alternative.kind === "reference"
131
+ ? expanded(value, alternative) === undefined
132
+ : validateShape([value], alternative, { scope }) === undefined), "value");
133
+ }
134
+ /**
135
+ * Validates a captive element, stated either as a link or as the resource it points at.
136
+ */
137
+ function expanded(value, range) {
138
+ return !isObject(value) ? validateShape([value], range, { scope })
139
+ : depth === undefined || depth > 0
140
+ ? validateResource([value], eager(range.target), { scope, depth: step(depth) })
141
+ : ["exceeded the maximum nesting depth"];
142
+ }
143
+ }
144
+ /**
145
+ * Validates retrieval templates against a shape.
146
+ *
147
+ * Reports each slot of a template that asks for something the shape cannot give, keyed by the member it asks under, so
148
+ * that a caller may tell which part of a request will not be served before it is issued. A template describes what to
149
+ * retrieve rather than what is held, so the value-domain constraints are left alone: a placeholder carries no value of
150
+ * its own, and is held to asking for something the shape can give rather than to being a legal value of it.
151
+ *
152
+ * **What a slot may ask for**
153
+ *
154
+ * Every slot is one object, and the keys it carries say what it asks for: the atomic placeholder `{}` asks for the
155
+ * value as it stands, a nested template for the resource behind a link, a map of language ranges for localised text
156
+ * tag by tag, and a branch map for a polymorphic member one alternative at a time. A member that is not wanted is left
157
+ * out of the template: a slot stated as `undefined` is refused, as is any other slot that isn't an object. Cardinality
158
+ * is not stated by the notation, so a member admitting several values is asked for exactly as one admitting a single
159
+ * value is, except that its slot may carry the constraints filtering, ordering and paging the collection alongside the
160
+ * keys retrieving it. A member admitting one value has no collection to narrow and a localised member is filtered by
161
+ * its own tag ranges: both refuse a constraint, as does a branch of a polymorphic member, which stands for one value
162
+ * alone, the constraints narrowing a collection riding on the slot hosting the alternatives. A refused constraint is
163
+ * reported under the key stating it and leaves what the slot asks for held to the shape all the same, so one pass
164
+ * reports both.
165
+ *
166
+ * Within a branch map, a template may ask for members declared by different resource branches. A member several of
167
+ * them declare may take a different shape in each, and what is asked for it need fit only one of them. A localised
168
+ * branch standing among others takes a map of tag ranges under a branch map. If no other branch reaches a resource,
169
+ * the map may also be stated directly on the member. A tag range may also be a member name, so an object whose keys
170
+ * each name a member of a resource branch is read as a template, and any other object as a map of tag ranges.
171
+ *
172
+ * **What a constraint may test against**
173
+ *
174
+ * A membership filter tests the options it lists by equality, so an option is held to the type of the member alone and
175
+ * need not be a legal value of it. A localised member is filtered through the text it carries: either plainly, as the
176
+ * string or strings any tag may match, or as a map grouping the options by the tag they are to match under, a tag
177
+ * carrying as many as the filter lists whatever arity the member admits. The two forms are never mixed within one set,
178
+ * and a map keyed by anything but a language tag is reported under the key at fault.
179
+ *
180
+ * **What a projection may ask for**
181
+ *
182
+ * A collection may be asked for as a table rather than as resources, each column bound to a path through the shape and
183
+ * to the transforms reducing it. A binding naming a path the shape cannot resolve is reported, as is one repeating an
184
+ * identifier another column already binds. A binding whose path takes no step reaches the item the collection holds as
185
+ * it stands, so a link is asked for as the identifier naming its target or expanded through a nested template, while an
186
+ * embedded resource, naming no identifier to come back as, is refused. Where a projection groups the collection, every
187
+ * ordering and focus key must name a grouping key or reduce to an aggregate, as nothing else ranks a group. A grouping
188
+ * key holds one value per group, so it may rank the groups even if the member it reaches is multi-valued.
189
+ *
190
+ * A column holds one value per row, so it supplies no collection to narrow and refuses a constraint of its own; a
191
+ * collection reached below it, through a nested template, carries its constraints as any other collection does.
192
+ *
193
+ * @param values The templates to validate
194
+ * @param shape The shape the templates are matched against
195
+ * @param opts Validation options
196
+ * @param opts.plain Whether to refuse the transforms combining several values into one, leaving a template that
197
+ * retrieves rather than computes
198
+ * @param opts.depth The nesting a template may ask for, counting each resource it descends into; `0` refuses every
199
+ * nested template while still admitting the identifier naming the resource
200
+ * @param opts.limit The largest page a template may ask for; a collection asking for none is held to it, and one
201
+ * asking for more is refused. `0`, like omitting it, leaves the page to the caller
202
+ *
203
+ * @returns A trace of the violations found, or `undefined` where every template asks for what the shape can give
204
+ *
205
+ * @throws {@link @grafctory/core!TraceError | TraceError} Where `shape` reaches itself through a cycle no link
206
+ * breaks, or where a union it reaches declares a shared member name inconsistently across its branches
207
+ */
208
+ export function validateTemplate(values, shape, { plain, depth, limit } = {}) {
209
+ return resources(values, shape, value => template(value, shape, depth));
210
+ /**
211
+ * Validates a template against the shape of the resources it asks for.
212
+ */
213
+ function template(value, shape, depth) {
214
+ if (!isObject(value)) {
215
+ return ["expected <template> value"];
216
+ }
217
+ if (exhausted(depth)) {
218
+ return ["exceeded maximum nesting depth"];
219
+ }
220
+ return all(...Object.entries(value).map(([name, asked]) => () => fold(!isIdentifier(name) ? ["expected property identifier"]
221
+ : !Object.hasOwn(shape.members, name) ? ["unknown property path"]
222
+ : shape.members[name].kind === "property"
223
+ ? slot(asked, shape.members[name], depth)
224
+ : isAtomic(asked) ? undefined : ["expected <Atomic> placeholder"], // the id/type members
225
+ // the id/type members
226
+ trace => [{ [name]: trace }])))(undefined);
227
+ }
228
+ /**
229
+ * Validates what a slot asks for, retrieval keys and collection constraints together.
230
+ *
231
+ * A slot is one object partitioning its keys by what they are: a constraint narrows the collection the slot
232
+ * reaches, and every other key retrieves part of its values. Cardinality is not stated by the notation, so what
233
+ * refuses a constraint is the shape: a member admitting one value has no collection to narrow, and a localised
234
+ * member is filtered by its own tag ranges.
235
+ *
236
+ * The two partitions are faulted independently, so a slot refusing a constraint is still held to what it asks
237
+ * for and one pass reports both.
238
+ */
239
+ function slot(value, member, depth) {
240
+ if (!isObject(value)) {
241
+ return ["expected <placeholder> value"];
242
+ }
243
+ const branches = getShapeBranches(member.range.shape);
244
+ const [branch] = branches;
245
+ const localised = branches.length === 1 && branch.kind === "dictionary";
246
+ const single = member.range.maxCount === 1 || localised;
247
+ return single
248
+ ? unconstrained(value, localised
249
+ ? "unexpected constraint on a localised member"
250
+ : "unexpected constraint on a single-valued member", contents => model(contents, member.range, depth))
251
+ : collection(value);
252
+ /**
253
+ * Validates what a collection asks for, its constraints narrowing the values its other keys retrieve.
254
+ */
255
+ function collection(value) {
256
+ const entries = Object.entries(value);
257
+ const constraints = entries.filter(([key]) => isSelector(key));
258
+ const contents = Object.fromEntries(entries.filter(([key]) => !isSelector(key)));
259
+ const keys = grouping(contents);
260
+ // element keys and constraint operators are disjoint, so the two traces merge into one
261
+ return all(() => item(contents, member, depth), () => filters(constraints, member, depth, keys), () => grouped(keys, constraints))(undefined);
262
+ }
263
+ }
264
+ /**
265
+ * Validates what a placeholder asks for, the constraints it may not state set apart from it.
266
+ *
267
+ * A placeholder standing for one value supplies no collection to narrow, so every constraint key it carries is
268
+ * refused, keyed by the offending key. The two partitions are faulted independently, so what the placeholder
269
+ * asks for is validated all the same and one pass reports both.
270
+ *
271
+ * @param value The placeholder to partition
272
+ * @param refused The violation reported for each constraint the placeholder may not state
273
+ * @param retrieval Validates what the placeholder asks for, once its constraints are set apart
274
+ */
275
+ function unconstrained(value, refused, retrieval) {
276
+ const entries = isObject(value) ? Object.entries(value) : [];
277
+ const constraints = entries.filter(([key]) => isSelector(key));
278
+ const contents = isObject(value)
279
+ ? Object.fromEntries(entries.filter(([key]) => !isSelector(key)))
280
+ : value;
281
+ return all(() => retrieval(contents), ...constraints.map(([selector]) => () => [{ [selector]: [refused] }]))(undefined);
282
+ }
283
+ /**
284
+ * Validates a placeholder standing for the value a branch admits.
285
+ */
286
+ function placeholder(value, branch, depth) {
287
+ const next = step(depth);
288
+ switch (branch.kind) {
289
+ case "reference": // a link comes back as the identifier naming its target, or as the resource itself
290
+ return isAtomic(value)
291
+ ? validateShape([value], branch, { scope: "model" })
292
+ : template(value, eager(branch.target), next);
293
+ case "resource": // an embedded resource states no identifier to come back as
294
+ return isAtomic(value)
295
+ ? ["expected <template> placeholder"]
296
+ : template(value, branch, next);
297
+ default:
298
+ return validateShape([value], branch, { scope: "model" });
299
+ }
300
+ }
301
+ /**
302
+ * Validates what a single-valued slot asks for.
303
+ *
304
+ * A localised branch is asked for either as the tags wanted or as the text content negotiation settles on. Standing
305
+ * among other branches, it takes the tags under a branch map. If no branch reaches a resource, it also takes them
306
+ * directly on the slot, as the map then cannot be mistaken for a template naming members by its tag ranges.
307
+ */
308
+ function model(value, range, depth) {
309
+ const branches = getShapeBranches(range.shape);
310
+ const [branch] = branches;
311
+ // with no branch reaching a resource, an object keyed by anything but branch indices can only be a locale
312
+ const localised = branches.every(alternative => getShapeTarget(alternative) === undefined)
313
+ ? branches.find((alternative) => alternative.kind === "dictionary")
314
+ : undefined;
315
+ return branches.length > 1
316
+ // the atomic placeholder asks for the value as it stands, so it reaches every alternative coming back
317
+ // as one and needs no branch of its own
318
+ ? isAtomic(value)
319
+ ? branches.some(alternative => alternative.kind !== "resource") ? undefined
320
+ : ["{branches} no branch comes back as a value"]
321
+ : localised !== undefined && !isObject(value, (_, key) => isBranch(key)) ? locale(value, localised)
322
+ : indexed(value, branches, depth)
323
+ : branch.kind === "dictionary" ? locale(value, branch)
324
+ : placeholder(value, branch, depth);
325
+ }
326
+ /**
327
+ * Validates what a polymorphic slot asks for, one branch at a time under the index of the branch.
328
+ *
329
+ * A branch carries one value, so it states no constraint of its own: the ones narrowing a collection ride on the
330
+ * entry hosting the union, and a constraint stated on a branch is refused there.
331
+ */
332
+ function indexed(value, branches, depth) {
333
+ if (!isObject(value, (_, key) => isBranch(key))) {
334
+ return ["expected union variant map"];
335
+ }
336
+ return all(...Object.entries(value).map(([index, asked]) => () => fold(variant(asked), trace => [{ [index]: trace }])))(undefined);
337
+ /**
338
+ * Validates what one branch asks for, the constraints it may not state set apart from it.
339
+ *
340
+ * A tag range may also be a member name, so an object is read one way only. It is a template if each of its
341
+ * keys names a member of a resource branch, and a map of tag ranges otherwise. An object read as a template is
342
+ * matched against the resource branches alone: if they reject it, it is not read again as tag ranges. It may
343
+ * span several resource branches, and what is asked for each member is admitted if any branch declaring that
344
+ * member admits it.
345
+ */
346
+ function variant(asked) {
347
+ return unconstrained(asked, "unexpected constraint on a union branch", contents =>
348
+ // an object read as a template never asks for tag ranges
349
+ isTemplateModel(contents, branches) && isObject(contents)
350
+ ? all(...Object.entries(contents).map(([name, nested]) => () => member(name, nested)))(undefined)
351
+ : branches.some(branch => branch.kind === "dictionary"
352
+ ? locale(contents, branch) === undefined
353
+ : placeholder(contents, branch, depth) === undefined) ? undefined : ["{branches} no branch admits the placeholder"]);
354
+ }
355
+ /**
356
+ * Validates what a template spanning the resource branches asks for one member, against every branch declaring
357
+ * it.
358
+ */
359
+ function member(name, asked) {
360
+ const traces = branches
361
+ .filter(branch => Object.hasOwn(getShapeTarget(branch)?.members ?? {}, name))
362
+ .map(branch => placeholder({ [name]: asked }, branch, depth));
363
+ // a single declaration has its own trace to tell what it refuses
364
+ return traces.some(trace => trace === undefined) ? undefined
365
+ : traces.length === 1 ? traces[0]
366
+ : [{ [name]: ["{branches} no branch admits the placeholder"] }];
367
+ }
368
+ }
369
+ /**
370
+ * Validates what a localised slot asks for.
371
+ *
372
+ * The text is asked for either coalesced, through the atomic placeholder, which comes back as the string content
373
+ * negotiation settles on, or structurally, as a map keyed by the tag ranges wanted rather than by the tags they
374
+ * match. Per-tag arity follows the shape, so a range asks for the value and states nothing about how many strings
375
+ * a matched tag carries.
376
+ *
377
+ * @param value The placeholder the slot states
378
+ * @param shape The localised shape the slot reaches
379
+ */
380
+ function locale(value, shape) {
381
+ return isAtomic(value) ? undefined
382
+ : !isObject(value) ? ["{kind} expected <Atomic> or <Locale> placeholder"]
383
+ : tagged(value, shape);
384
+ }
385
+ /**
386
+ * Validates the tags a localised slot wants, each asking for the value a matched tag carries.
387
+ */
388
+ function tagged(value, {}) {
389
+ return object(([range, asked]) => !isTagRange(range) ? [{ [range]: ["invalid tag range"] }]
390
+ : isAtomic(asked) ? undefined
391
+ : [{ [range]: ["{type} expected <Atomic> value"] }])(value);
392
+ }
393
+ /**
394
+ * Identifies the grouping keys of a collection.
395
+ *
396
+ * @returns The {@link signature} of each grouping column, or `undefined` if no aggregate column groups it
397
+ */
398
+ function grouping(element) {
399
+ const bindings = isObject(element) ? Object.keys(element).filter(isBinding).map(decodeProbe) : [];
400
+ // the projection alone fixes the grouping: a combining column groups the collection, and the columns left
401
+ // standing are then the keys it is grouped by; a combining selector reduces one group rather than forming it
402
+ return bindings.some(aggregate)
403
+ ? new Set(bindings.filter(probe => !aggregate(probe)).map(signature))
404
+ : undefined;
405
+ }
406
+ /**
407
+ * Checks whether a selector names one of the grouping keys of a collection.
408
+ */
409
+ function keyed(probe, keys) {
410
+ return keys !== undefined && !aggregate(probe) && keys.has(signature(probe));
411
+ }
412
+ /**
413
+ * Checks whether a selector or column combines several values into one.
414
+ */
415
+ function aggregate(probe) {
416
+ return probe.pipe.some(isAggregate);
417
+ }
418
+ /**
419
+ * Identifies the expression a selector or column states, whatever operator or binding name it carries.
420
+ */
421
+ function signature(probe) {
422
+ return `${probe.path.join(".")}|${probe.pipe.join(":")}`;
423
+ }
424
+ /**
425
+ * Validates that every ordering ranks a grouped collection by something the grouping leaves standing.
426
+ */
427
+ function grouped(keys, constraints) {
428
+ const selectors = constraints.map(([selector]) => [selector, decodeProbe(selector)]);
429
+ return keys === undefined ? undefined : all(...selectors
430
+ .filter(([, probe]) => (probe.target === "^" || probe.target === "+")
431
+ && !aggregate(probe)
432
+ && !keyed(probe, keys))
433
+ .map(([selector]) => () => [{
434
+ [selector]: ["expected a grouping-key or aggregate ordering/focus expression under grouping"]
435
+ }]))(undefined);
436
+ }
437
+ /**
438
+ * Validates what a collection asks for one of its values as: a template, or a table of bound paths.
439
+ */
440
+ function item(value, member, depth) {
441
+ if (exhausted(depth)) {
442
+ return ["exceeded maximum nesting depth"];
443
+ }
444
+ const branches = getShapeBranches(member.range.shape);
445
+ const [branch] = branches;
446
+ if (branches.length > 1) {
447
+ return model(value, member.range, depth);
448
+ }
449
+ switch (branch.kind) {
450
+ case "reference":
451
+ case "resource": {
452
+ const next = step(depth);
453
+ const target = branch.kind === "reference" ? eager(branch.target) : branch;
454
+ // a template descends into the resource, while a column resolves against the item as it stands, so
455
+ // an empty path leaves a link a link, asked for as the identifier naming its target
456
+ return isAtomic(value) ? placeholder(value, branch, depth)
457
+ : Object.keys(value).every(isIdentifier) ? template(value, target, next)
458
+ : projection(value, branch, next);
459
+ }
460
+ default:
461
+ return placeholder(value, branch, depth);
462
+ }
463
+ }
464
+ /**
465
+ * Validates a table of paths bound to the columns a collection is asked for.
466
+ *
467
+ * @param shape The item the columns resolve their paths against, a link left unresolved so that a path taking
468
+ * no step reaches it as the identifier naming its target
469
+ *
470
+ * @remarks A column holds one value per row, so it supplies no collection to narrow: a constraint stated on the
471
+ * placeholder a column asks for is refused, while a collection reached below it, through a nested template,
472
+ * carries its own constraints as any other collection does.
473
+ */
474
+ function projection(value, shape, depth) {
475
+ if (!isObject(value)) {
476
+ return ["expected <projection> value"];
477
+ }
478
+ if (exhausted(depth)) {
479
+ return ["exceeded maximum nesting depth"];
480
+ }
481
+ const probes = new Map(Object.keys(value)
482
+ .filter(isBinding)
483
+ .map(binding => [binding, decodeProbe(binding)]));
484
+ // the identifiers a column may not bind twice, settled once for the whole table
485
+ const shared = new Set([...probes.values()]
486
+ .map(probe => probe.target)
487
+ .filter((target, index, targets) => targets.indexOf(target) !== index));
488
+ return all(...Object.entries(value).map(([binding, asked]) => () => fold(column(binding, asked), trace => [{ [binding]: trace }])))(undefined);
489
+ function column(binding, asked) {
490
+ const probe = probes.get(binding);
491
+ if (probe === undefined) {
492
+ return ["expected projection binding"];
493
+ }
494
+ if (depth !== undefined && probe.path.length > depth) {
495
+ return ["exceeded maximum path length"];
496
+ }
497
+ if (plain && probe.pipe.some(isAggregate)) {
498
+ return ["disabled aggregate transforms"];
499
+ }
500
+ if (shared.has(probe.target)) {
501
+ return [`duplicate projection identifier <${probe.target}>`];
502
+ }
503
+ const range = effective(shape, probe);
504
+ if (isString(range)) {
505
+ return [range];
506
+ } // the path the shape cannot resolve
507
+ // a column holds one value per row, so it neither asks for a collection nor narrows one; a collection
508
+ // reached below it, through a nested template, carries its own constraints as any other does
509
+ return isArray(asked) ? ["unexpected array in projection value"]
510
+ : unconstrained(asked, "unexpected constraint in a projection column", contents => model(contents, range, depth));
511
+ }
512
+ }
513
+ /**
514
+ * Validates the constraints filtering, ordering and paging a collection.
515
+ *
516
+ * @param keys The grouping keys of the collection, or `undefined` if it is not grouped; each holds one value per
517
+ * group, so ordering and focus admit it even where the member it reaches is multi-valued
518
+ */
519
+ function filters(constraints, member, depth, keys) {
520
+ // a selector resolves through the values the collection holds, one step below the collection itself
521
+ const next = step(depth);
522
+ if (constraints.length === 0) {
523
+ return undefined;
524
+ } // a collection stated without constraints
525
+ if (exhausted(next)) {
526
+ return ["exceeded maximum nesting depth"];
527
+ }
528
+ return all(...constraints.map(([selector, asked]) => () => fold(operator(selector, asked), trace => [{ [selector]: trace }])))(undefined);
529
+ function operator(selector, asked) {
530
+ if (!isSelector(selector)) {
531
+ return ["expected constraint operator"];
532
+ }
533
+ const probe = decodeProbe(selector);
534
+ if (next !== undefined && probe.path.length > next) {
535
+ return ["exceeded maximum path length"];
536
+ }
537
+ if (plain && probe.pipe.some(isAggregate)) {
538
+ return ["disabled aggregate transforms"];
539
+ }
540
+ const range = effective(member.range.shape, probe);
541
+ if (isString(range)) {
542
+ return [range];
543
+ } // the path the shape cannot resolve
544
+ const branches = getShapeBranches(range.shape);
545
+ // a grouping key holds one value per group, however many the member it reaches holds per item
546
+ const single = range.maxCount === 1 || keyed(probe, keys);
547
+ switch (probe.target) {
548
+ case "<":
549
+ case ">":
550
+ case "<=":
551
+ case ">=":
552
+ return bound(asked, branches);
553
+ case "~":
554
+ return keywords(asked, branches);
555
+ case "?":
556
+ case "!":
557
+ return options(asked, branches);
558
+ case "+": // a sort focus ranks one value per resource or group, so it refuses a multi-valued key
559
+ return single ? options(asked, branches) : ["expected single-valued sort focus key"];
560
+ case "^":
561
+ return order(asked, single);
562
+ case "@":
563
+ return offset(asked);
564
+ case "#":
565
+ return page(asked);
566
+ default:
567
+ return ["expected constraint operator"];
568
+ }
569
+ }
570
+ }
571
+ /**
572
+ * Validates a relational bound, which singles out the branch it filters against.
573
+ */
574
+ function bound(value, branches) {
575
+ if (branches.length === 0) {
576
+ return undefined;
577
+ } // nothing to filter against, the bound is immaterial
578
+ if (branches.length > 1) {
579
+ return verdict(branches.filter(branch => checkBound(value, branch) === undefined), "bound");
580
+ }
581
+ const [branch] = branches;
582
+ return checkBound(value, branch);
583
+ }
584
+ /**
585
+ * Validates a text search, which filters every textual branch at once rather than singling one out.
586
+ */
587
+ function keywords(value, branches) {
588
+ if (branches.length === 0) {
589
+ return undefined;
590
+ } // nothing to search, the string is immaterial
591
+ if (branches.length > 1) {
592
+ return branches.some(branch => keywords(value, [branch]) === undefined) ? undefined
593
+ : ["{branches} no branch admits the search"];
594
+ }
595
+ const [branch] = branches;
596
+ switch (branch.kind) {
597
+ case "string":
598
+ case "dictionary":
599
+ return isString(value) ? undefined : ["expected string value"];
600
+ default:
601
+ return [`unsupported constraint for <${branch.kind}> value`];
602
+ }
603
+ }
604
+ /**
605
+ * Validates the options a membership filter tests against.
606
+ */
607
+ function options(value, branches) {
608
+ if (branches.length === 0) {
609
+ return undefined;
610
+ } // nothing to match, the options are immaterial
611
+ if (branches.length > 1) {
612
+ return isArray(value) ? array(single)(value) : single(value);
613
+ }
614
+ const [branch] = branches;
615
+ if (branch.kind === "dictionary") {
616
+ // a tag map, or a plain string standing for the strings the map carries, stated singly or as a set;
617
+ // the two forms are never mixed within one set
618
+ return isArray(value, isString) ? undefined
619
+ : !isArray(value) ? checkOption(value, branch)
620
+ : value.some(value => isObject(value)) && value.some(value => isString(value))
621
+ ? ["mixed plain and tagged options"]
622
+ : [`unsupported constraint for <${branch.kind}> value`];
623
+ }
624
+ return isArray(value)
625
+ ? array((value) => checkOption(value, branch))(value)
626
+ : checkOption(value, branch);
627
+ /**
628
+ * Reports whether an option singles out one branch; an option stated as nothing at all is typeless and exempt.
629
+ */
630
+ function single(value) {
631
+ if (value === null) {
632
+ return undefined;
633
+ }
634
+ return verdict(branches.filter(branch => checkOption(value, branch) === undefined), "option");
635
+ }
636
+ }
637
+ /**
638
+ * Validates the ordering a collection is ranked by.
639
+ */
640
+ function order(value, single) {
641
+ // an order is a precedence rank counted from one, which `asc` and `desc` abbreviate, so a fraction ranks
642
+ // nothing; ranking requires one value per resource or group, a multi-valued key leaving no order to rank by
643
+ return value !== "asc" && value !== "desc" && !Number.isInteger(value)
644
+ ? ["expected <asc>, <desc>, or integer value"]
645
+ : !single ? ["expected single-valued sort key"]
646
+ : undefined;
647
+ }
648
+ /**
649
+ * Validates the point a page starts at.
650
+ */
651
+ function offset(value) {
652
+ return !isNumber(value) ? ["expected number value"]
653
+ : !Number.isInteger(value) || value < 0 ? ["expected non-negative integer"]
654
+ : undefined;
655
+ }
656
+ /**
657
+ * Validates the size a page is asked for at.
658
+ *
659
+ * A page of `0` asks for the whole set, so it is held to the limit like any other size; a limit of `0` caps
660
+ * nothing, leaving the page to the caller as it does for the default paging the same option drives.
661
+ */
662
+ function page(value) {
663
+ return !isNumber(value) ? ["expected number value"]
664
+ : !Number.isInteger(value) || value < 0 ? ["expected non-negative integer"]
665
+ : limit !== undefined && limit > 0 && (value === 0 || value > limit)
666
+ ? [`exceeded maximum result set limit <${limit}>`]
667
+ : undefined;
668
+ }
669
+ }
670
+ /**
671
+ * Validates retrieved resources against a shape, narrowed by the template that requested them.
672
+ *
673
+ * Reports each member the template asked for and the resource states wrongly, keyed by the member it is stated under,
674
+ * so that a caller may tell which part of what it asked for came back malformed. Only the members the template names
675
+ * are held to the shape: one it left out is neither required nor checked, so a partial retrieval passes on its own
676
+ * terms. The surface is closed the other way too: a member the resource states but the template didn't ask for is
677
+ * rejected, as the caller has no place to put it. The custom {@link ResourceShape.validators | checks} a shape states
678
+ * are left out, as they are written against a whole resource rather than the part of it a template asked for.
679
+ *
680
+ * A member reaching a resource comes back as the resource itself where a nested template asked for it, and as the
681
+ * identifier naming it where the atomic placeholder did; either way it is held to what was asked. A localised member
682
+ * comes back in the form its template asked for: the map it named tag ranges under, whole and never in an array, or,
683
+ * where the atomic placeholder asked for it, the text content negotiation settled on, at the arity the shape states
684
+ * per tag and held to the lengths it bounds rather than to the counts of the other alternatives.
685
+ *
686
+ * A polymorphic member comes back holding one variant alone. If the template reaches only some of its variants, the
687
+ * member may come back empty on a resource holding another, so its lower bound binds only if every variant is
688
+ * reached. If the atomic placeholder asks for localised text paired with other values, the text comes back folded
689
+ * among them as plain strings, and a value is admitted if any variant of the member admits it.
690
+ *
691
+ * @param values The retrieved resources to validate
692
+ * @param opts Validation options
693
+ * @param opts.shape The shape the resources are matched against
694
+ * @param opts.model The template that requested them, narrowing what is checked
695
+ * @param opts.entry The identifier the resources are expected to be named by, where one is expected
696
+ *
697
+ * @returns A trace of the violations found, or `undefined` where every resource matches what was asked for
698
+ */
699
+ export function validateResult(values, { shape, model, entry }) {
700
+ return resources(values, shape, resource => all(
701
+ // every member asked for; a key present in the template always asks for something
702
+ ...Object.keys(model)
703
+ .map(name => () => fold(requested(resource[name], name, model[name]), trace => [{ [name]: trace }])),
704
+ // the caller has nowhere to put a member it didn't ask for
705
+ ...Object.keys(resource)
706
+ .filter(name => !Object.hasOwn(model, name))
707
+ .map(name => () => [{ [name]: ["unexpected member"] }]))(undefined));
708
+ /**
709
+ * Validates the value a requested member came back with.
710
+ */
711
+ function requested(value, name, requested) {
712
+ const member = shape.members[name];
713
+ return member === undefined ? ["undefined member"]
714
+ : member.kind === "id" ? identifier(value, shape, entry)
715
+ : member.kind === "type" ? classifier(value, shape)
716
+ : contents(value, member, requested);
717
+ }
718
+ /**
719
+ * Validates the values a member came back with against its range and the template narrowing it.
720
+ */
721
+ function contents(value, member, requested) {
722
+ const { range: { minCount, maxCount, shape: range } } = member;
723
+ const branches = getShapeBranches(range);
724
+ const present = value === undefined || isArray(value, []) ? undefined : value;
725
+ if (present === undefined) {
726
+ return minCount !== undefined && minCount >= 1 && exhaustive(requested, branches)
727
+ ? [`{minCount} expected at least <${minCount}> value(s)`]
728
+ : undefined;
729
+ }
730
+ // a localised member asked for by the atomic placeholder comes back as the text negotiation settled on rather
731
+ // than as the map, at the arity the shape states per tag
732
+ const negotiated = branches
733
+ .flatMap(branch => branch.kind === "dictionary" ? [branch] : [])
734
+ .find(branch => plain(requested, branch));
735
+ if (negotiated !== undefined) {
736
+ // the text folds into the values of the other variants, so a value is admitted where either admits it
737
+ const others = branches.filter(branch => branch !== negotiated);
738
+ const coalesced = text(present, negotiated);
739
+ return coalesced === undefined || others.length === 0 ? coalesced
740
+ : valued(present, member, others, requested) === undefined ? undefined
741
+ : coalesced;
742
+ }
743
+ // a localised member comes back as it is carried: one map, whole and never in an array, whatever bounds it
744
+ // states of the other values, and the bounds count those other values alone
745
+ // a map is matched against the range as it stands, the template narrowing the other values alone
746
+ return isLocalised(present, branches, "state")
747
+ ? validateShape([present], eager(range))
748
+ : valued(present, member, branches, requested);
749
+ }
750
+ /**
751
+ * Validates the values a member came back with, other than a localised map, against the branches they may belong to.
752
+ */
753
+ function valued(present, member, branches, requested) {
754
+ const carried = isArray(present) ? present : [present];
755
+ return arity(present, member.range.maxCount, branches, "state")
756
+ ?? elements(carried, branches, requested)
757
+ ?? counts(carried.length, member);
758
+ }
759
+ /**
760
+ * Checks whether a request reaches every branch a member admits, so that coming back empty breaks its lower bound.
761
+ *
762
+ * A resource holds the value of one branch alone, so a request reaching only some comes back empty on a resource
763
+ * holding another, and the bound then says nothing about what the resource holds.
764
+ */
765
+ function exhaustive(requested, branches) {
766
+ const asked = isObject(requested)
767
+ ? Object.fromEntries(Object.entries(requested).filter(([key]) => !isSelector(key)))
768
+ : requested;
769
+ const keyed = isObject(asked) && Object.keys(asked).length > 0 && Object.keys(asked).every(isBranch);
770
+ const alternatives = keyed ? Object.values(asked) : [asked];
771
+ const reached = new Set(alternatives.flatMap(alternative => getModelBranches(alternative, branches) ?? []));
772
+ return branches.length === 1 || reached.size === branches.length;
773
+ }
774
+ /**
775
+ * Reports whether a placeholder asked a localised shape for the text negotiation settles on.
776
+ *
777
+ * The atomic placeholder stands for that text, which is how a localised member is asked for where the tags are not
778
+ * wanted; the tags are stated as a map of language ranges instead. The arity the text comes back at follows the
779
+ * shape rather than the placeholder.
780
+ */
781
+ function plain(requested, {}) {
782
+ return isAtomic(requested);
783
+ }
784
+ /**
785
+ * Validates the text a localised member came back with, where the atomic placeholder asked for it.
786
+ *
787
+ * Holds the text to the lengths the shape bounds; the language constraint is keyed on the tags it was negotiated
788
+ * from, which it comes back without. Where a tag stacks several strings the text comes back as the array of them,
789
+ * whose length is what that tag carried rather than what the member's bounds count, the map it stands for being
790
+ * held apart from those values too.
791
+ */
792
+ function text(value, shape) {
793
+ const { minLength, maxLength } = shape;
794
+ const bounded = (content) => all((minLength !== undefined && content.length < minLength)
795
+ && fail([`{minLength} expected string length >= <${minLength}>`]), (maxLength !== undefined && content.length > maxLength)
796
+ && fail([`{maxLength} expected string length <= <${maxLength}>`]))(undefined);
797
+ return shape.uniqueLang === true
798
+ ? isString(value) ? bounded(value) : ["{kind} expected the negotiated text"]
799
+ : !isArray(value, isString) ? ["{kind} expected an array of the negotiated text"]
800
+ : array(bounded)(value);
801
+ }
802
+ /**
803
+ * Validates the elements a member came back with against the branches its range admits.
804
+ */
805
+ function elements(carried, branches, requested) {
806
+ const [only] = branches;
807
+ return branches.length !== 1
808
+ ? array((value) => branch(value, branches, requested))(carried)
809
+ // a link comes back as the identifier naming the resource, or as the resource itself
810
+ : only.kind === "reference"
811
+ ? array((value) => isString(value)
812
+ ? isReference(value) ? undefined : ["expected an absolute IRI"]
813
+ : isObject(value) ? validateResult([value], {
814
+ shape: eager(only.target),
815
+ model: nested(requested)
816
+ }) : ["expected an IRI or the resource itself"])(carried)
817
+ : only.kind === "resource"
818
+ ? array((value) => isObject(value)
819
+ ? validateResult([value], { shape: only, model: nested(requested) })
820
+ : ["expected a nested resource"])(carried)
821
+ : validateShape(carried, only);
822
+ }
823
+ /**
824
+ * Validates a value against the branches of a polymorphic member, which it must single out one of.
825
+ */
826
+ function branch(value, branches, requested) {
827
+ const head = isArray(requested) && requested.length > 0 ? requested[0] : requested;
828
+ const fields = isObject(head) ? head : {};
829
+ const keys = Object.keys(fields);
830
+ const indexed = keys.length > 0 && keys.some(key => !isIdentifier(key));
831
+ if (indexed) {
832
+ const malformed = keys.filter(key => !isBranch(key));
833
+ if (malformed.length > 0) {
834
+ return all(...malformed.map(key => () => [{ [key]: ["expected a branch key"] }]))(undefined);
835
+ }
836
+ return verdict(branches.filter(admits => keys.some(key => fits(value, admits, fields[key]))), "value");
837
+ }
838
+ return verdict(branches.filter(admits => fits(value, admits, requested)), "value");
839
+ }
840
+ /**
841
+ * Reports whether a branch admits a value under the template narrowing it.
842
+ *
843
+ * The verdict alone is read, as it feeds the count a value is singled out by, so the trace is immaterial.
844
+ */
845
+ function fits(value, admits, requested) {
846
+ switch (admits.kind) {
847
+ case "resource": // a resource is reached only through a nested template
848
+ return isObject(requested) && elements([value], [admits], requested) === undefined;
849
+ case "reference": // a link comes back as an identifier or as the resource itself
850
+ return !isObject(value)
851
+ ? validateShape([value], admits) === undefined
852
+ : elements([value], [admits], requested) === undefined;
853
+ default: // the atomic placeholder tells no literal branch from another, so the value alone singles one out
854
+ return isAtomic(requested)
855
+ && validateShape([value], admits) === undefined;
856
+ }
857
+ }
858
+ /**
859
+ * Reports the cardinality bounds the values a member came back with break.
860
+ */
861
+ function counts(count, { range: { minCount, maxCount } }) {
862
+ return all((minCount !== undefined && count < minCount)
863
+ && fail([`{minCount} expected at least <${minCount}> value(s)`]), (maxCount !== undefined && count > maxCount)
864
+ && fail([`{maxCount} expected at most <${maxCount}> value(s)`]))(undefined);
865
+ }
866
+ /**
867
+ * Resolves the template a nested resource was requested through.
868
+ *
869
+ * A collection carries its constraints alongside the keys retrieving its values, so the per-item template is the
870
+ * node less the constraints; the atomic placeholder states no nested template at all, so every member the
871
+ * resource comes back with is unasked for.
872
+ */
873
+ function nested(requested) {
874
+ const element = isObject(requested)
875
+ ? Object.fromEntries(Object.entries(requested).filter(([key]) => !isSelector(key)))
876
+ : requested;
877
+ return isTemplate(element) ? element : {};
878
+ }
879
+ }
880
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
881
+ /**
882
+ * Checks that no member carries an embedded resource naming itself.
883
+ *
884
+ * An embedded resource has no identity of its own, so it states no identifier. A linked resource legitimately states
885
+ * one and is left alone; a union range is inspected one branch at a time.
886
+ *
887
+ * This runs as a resource is validated rather than as the shape is built: at construction an id-bearing embedded range
888
+ * reads exactly like an expanded link, whose target legitimately names itself, and the two are told apart only once a
889
+ * value is matched against them.
890
+ *
891
+ * @param shape The merged shape to check
892
+ *
893
+ * @returns A trace of the embedded resources naming themselves, or `undefined` where none does
894
+ */
895
+ function checkId(shape) {
896
+ return all(...Object.entries(shape.members)
897
+ .flatMap(([name, member]) => member.kind === "property" ? getShapeBranches(member.range.shape)
898
+ .filter(branch => branch.kind === "resource" && named(branch) !== undefined)
899
+ .map(() => fail([`{id} unexpected identifier in the resource embedded under <${name}>`]))
900
+ : []))(undefined);
901
+ }
902
+ /**
903
+ * Holds each value to a check of its own, keyed by the resource it found fault with.
904
+ *
905
+ * @param values The values to validate
906
+ * @param shape The shape the values are keyed against
907
+ * @param check The check each resource is held to
908
+ *
909
+ * @returns A trace of the violations found, keyed by the resource stating each
910
+ */
911
+ function resources(values, shape, check) {
912
+ const matching = values.filter(value => isObject(value));
913
+ const mistyped = values.length - matching.length;
914
+ return all((mistyped > 0)
915
+ && fail([`{kind} expected <resource> values${mistyped > 1 ? ` (${mistyped}/${values.length})` : ""}`]), ...matching.map((resource, index) => () => fold(check(resource), trace => [{ [key(resource, shape, index)]: trace }])))(undefined);
916
+ }
917
+ /**
918
+ * Reports whether a value, bound or option singles out exactly one of the branches it was matched against.
919
+ */
920
+ function verdict(matched, subject) {
921
+ return matched.length === 0 ? [`{branches} no branch admits the ${subject}`]
922
+ : matched.length > 1 ? [`{branches} several branches admit the ${subject}`]
923
+ : undefined;
924
+ }
925
+ /**
926
+ * Holds the values a member carries to the form its arity calls for: a single value where it admits one, an array
927
+ * where it admits several, and no localised map stated beside values of other alternatives. Reached only where the
928
+ * member does not carry the map whole, which the caller settles beforehand.
929
+ */
930
+ function arity(present, maxCount, branches, scope) {
931
+ const scalar = maxCount === 1;
932
+ return isArray(present) && present.some(element => isLocalised(element, branches, scope))
933
+ ? ["{kind} expected a single localised value"]
934
+ : present !== undefined && scalar === isArray(present)
935
+ ? [scalar ? "{kind} expected a single value" : "{kind} expected an array of values"]
936
+ : undefined;
937
+ }
938
+ /**
939
+ * Holds the value a marker states to the single absolute IRI it must be.
940
+ */
941
+ function marked(value) {
942
+ return isArray(value) ? ["{kind} expected a single value"]
943
+ : !isReference(value) ? ["{kind} expected an absolute IRI"]
944
+ : undefined;
945
+ }
946
+ /**
947
+ * Spends one step of the nesting a template or a captive member may be expanded to.
948
+ */
949
+ function step(depth) {
950
+ return depth === undefined ? undefined : depth - 1;
951
+ }
952
+ /**
953
+ * Reports whether the nesting budget is spent.
954
+ */
955
+ function exhausted(depth) {
956
+ return depth !== undefined && depth < 0;
957
+ }
958
+ /**
959
+ * Reports whether a value is the whole language map a localised member carries.
960
+ *
961
+ * A localised value is a value set in its own right, holding its strings per tag at the arity its own shape states, so
962
+ * a member carries it whole rather than among the values its bounds count: the map stands apart from the cardinality,
963
+ * and an array never holds one.
964
+ *
965
+ * @param value The value to test
966
+ * @param branches The alternatives the member ranges over
967
+ * @param scope The strictness the dictionary alternatives are enforced at
968
+ *
969
+ * @returns `true` where `value` is a language map one of `branches` admits
970
+ */
971
+ function isLocalised(value, branches, scope) {
972
+ return !isArray(value) && branches.some(branch => branch.kind === "dictionary" && validateShape([value], branch, { scope }) === undefined);
973
+ }
974
+ /**
975
+ * Validates the identifier a resource states against the constraints its shape puts on identifiers.
976
+ */
977
+ function identifier(value, shape, entry) {
978
+ const { pattern, in: allowed, hasValue: required } = shape;
979
+ const iri = isReference(value) ? value : undefined;
980
+ return value === undefined ? undefined : all(() => marked(value), (entry !== undefined && iri !== undefined && iri !== entry)
981
+ && fail([`{entry} mismatched entry <${entry}>`]), (pattern !== undefined && !(iri !== undefined && match(iri, pattern)))
982
+ && fail([`{pattern} expected an IRI matching pattern <${pattern}>`]), (allowed !== undefined && !(iri !== undefined && allowed.includes(iri)))
983
+ && fail([`{in} expected values in [${allowed.join(", ")}]`]), (required !== undefined && !(iri !== undefined && required.every(v => v === iri)))
984
+ && fail([`{hasValue} expected values to include [${required.join(", ")}]`]))(undefined);
985
+ }
986
+ /**
987
+ * Validates the class a resource states against the one its shape declares.
988
+ */
989
+ function classifier(value, shape) {
990
+ const { class: declared } = shape;
991
+ const iri = isReference(value) ? value : undefined;
992
+ return value === undefined ? undefined : all(() => marked(value),
993
+ // a class value states the class the shape declares, so a shape declaring none admits no value
994
+ (iri !== undefined && iri !== declared)
995
+ && fail([declared === undefined
996
+ ? `{class} unexpected class without one declared`
997
+ : `{class} expected the declared class <${declared}>`
998
+ ]))(undefined);
999
+ }
1000
+ /**
1001
+ * Keys a resource by the identifier it states, or by its position where it states none.
1002
+ */
1003
+ function key(value, shape, index) {
1004
+ const id = named(shape);
1005
+ const iri = id === undefined ? undefined : value[id];
1006
+ return isReference(iri) ? `<${iri}>` : `${index}`;
1007
+ }
1008
+ /**
1009
+ * Resolves the name a resource states its identifier under.
1010
+ *
1011
+ * @param shape The shape to inspect
1012
+ *
1013
+ * @returns The name of the id member of `shape`, or `undefined` where it declares none
1014
+ */
1015
+ function named(shape) {
1016
+ return Object.entries(shape.members).find(([, member]) => member.kind === "id")?.[0];
1017
+ }
1018
+ /**
1019
+ * Runs the checks a shape states on top of its members, each keyed by the name of the check.
1020
+ *
1021
+ * Every check runs, so a resource is told everything that is wrong with it at once; a check states its own name, and
1022
+ * one stating none is keyed by the position it was declared at.
1023
+ */
1024
+ function checks(value, shape) {
1025
+ return (shape.validators ?? []).map((validator, index) => () => fold(
1026
+ // the check owns whatever it reads, the members having been held to the shape already
1027
+ validator(value), // ;(cast) a resource confirmed by isObject, checked field by field above
1028
+ // ;(cast) a resource confirmed by isObject, checked field by field above
1029
+ trace => [{ [`{${validator.name || `validator[${index}]`}}`]: trace }]));
1030
+ }
1031
+ //# sourceMappingURL=validator.js.map