@grafctory/blue 0.0.0-stage → 0.16.0

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