@haddowg/json-api-client 1.26.0 → 1.28.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.
- package/README.md +11 -1
- package/dist/ajv.cjs +20 -2
- package/dist/ajv.d.cts +5 -1
- package/dist/ajv.d.cts.map +1 -1
- package/dist/ajv.d.mts +5 -1
- package/dist/ajv.d.mts.map +1 -1
- package/dist/ajv.mjs +20 -2
- package/dist/ajv.mjs.map +1 -1
- package/dist/index.cjs +192 -240
- package/dist/index.d.cts +32 -6
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +32 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +175 -228
- package/dist/index.mjs.map +1 -1
- package/dist/validate-BvO7NhkT.mjs +418 -0
- package/dist/validate-BvO7NhkT.mjs.map +1 -0
- package/dist/validate-DMRQn0XN.cjs +481 -0
- package/dist/{validate-C9ekU8fM.d.cts → validate-Dj6pkoNM.d.cts} +515 -61
- package/dist/validate-Dj6pkoNM.d.cts.map +1 -0
- package/dist/{validate-C9ekU8fM.d.mts → validate-Dj6pkoNM.d.mts} +515 -61
- package/dist/validate-Dj6pkoNM.d.mts.map +1 -0
- package/package.json +1 -1
- package/dist/validate-C9ekU8fM.d.cts.map +0 -1
- package/dist/validate-C9ekU8fM.d.mts.map +0 -1
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
//#region src/errors.ts
|
|
2
|
+
/**
|
|
3
|
+
* Thrown by the always-on light structural guards when a parsed response is not a
|
|
4
|
+
* JSON:API document, or a `data`/`included` member is not a resource object carrying `type`+`id`.
|
|
5
|
+
* Distinct from {@link JsonApiError} (a non-2xx server response): this signals the wire shape the
|
|
6
|
+
* runtime relies on was violated, not an application error the server reported. The opt-in
|
|
7
|
+
* per-field validator throws its engine's own error type, never this one.
|
|
8
|
+
*/
|
|
9
|
+
var StructuralGuardError = class extends Error {
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "StructuralGuardError";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Thrown for any non-2xx JSON:API response. Carries the parsed error document plus
|
|
17
|
+
* expressive status matchers and pointer-grouping helpers.
|
|
18
|
+
*
|
|
19
|
+
* `C` types each error object's `code` (see {@link JsonApiErrorObject}). It is a compile-time
|
|
20
|
+
* hint only: the runtime never checks a code against it.
|
|
21
|
+
*/
|
|
22
|
+
var JsonApiError = class extends Error {
|
|
23
|
+
status;
|
|
24
|
+
errors;
|
|
25
|
+
constructor(status, errors, message) {
|
|
26
|
+
super(message ?? `JSON:API request failed with status ${status}`);
|
|
27
|
+
this.name = "JsonApiError";
|
|
28
|
+
this.status = status;
|
|
29
|
+
this.errors = errors;
|
|
30
|
+
}
|
|
31
|
+
hasStatus(status) {
|
|
32
|
+
return this.status === status;
|
|
33
|
+
}
|
|
34
|
+
is4xx() {
|
|
35
|
+
return this.status >= 400 && this.status < 500;
|
|
36
|
+
}
|
|
37
|
+
is5xx() {
|
|
38
|
+
return this.status >= 500 && this.status < 600;
|
|
39
|
+
}
|
|
40
|
+
isBadRequest() {
|
|
41
|
+
return this.status === 400;
|
|
42
|
+
}
|
|
43
|
+
isUnauthorized() {
|
|
44
|
+
return this.status === 401;
|
|
45
|
+
}
|
|
46
|
+
isForbidden() {
|
|
47
|
+
return this.status === 403;
|
|
48
|
+
}
|
|
49
|
+
isNotFound() {
|
|
50
|
+
return this.status === 404;
|
|
51
|
+
}
|
|
52
|
+
isNotAcceptable() {
|
|
53
|
+
return this.status === 406;
|
|
54
|
+
}
|
|
55
|
+
isConflict() {
|
|
56
|
+
return this.status === 409;
|
|
57
|
+
}
|
|
58
|
+
isUnsupportedMediaType() {
|
|
59
|
+
return this.status === 415;
|
|
60
|
+
}
|
|
61
|
+
isUnprocessable() {
|
|
62
|
+
return this.status === 422;
|
|
63
|
+
}
|
|
64
|
+
/** Alias of {@link isUnprocessable} — the JSON:API validation status. */
|
|
65
|
+
isValidationError() {
|
|
66
|
+
return this.status === 422;
|
|
67
|
+
}
|
|
68
|
+
isRateLimited() {
|
|
69
|
+
return this.status === 429;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Group errors by user-facing input path (falls back to the raw pointer, then the
|
|
73
|
+
* query parameter). The payoff for form/validation UX — 422 `source.pointer`s are
|
|
74
|
+
* remapped to the flat shape the caller actually supplied.
|
|
75
|
+
*/
|
|
76
|
+
byPath() {
|
|
77
|
+
const out = {};
|
|
78
|
+
for (const e of this.errors) {
|
|
79
|
+
const key = e.path ?? e.source?.pointer ?? e.source?.parameter ?? "_";
|
|
80
|
+
(out[key] ??= []).push(e);
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* True when `err` is a {@link JsonApiError} and any of its error objects carries `code`. Takes
|
|
87
|
+
* any string, so it also matches codes the server never documented. A generated client exports a
|
|
88
|
+
* `hasErrorCode` bound to its server's `ErrorCode` union, which rejects a misspelt code at
|
|
89
|
+
* compile time; reach for this one only to match an undocumented code.
|
|
90
|
+
*/
|
|
91
|
+
function hasErrorCode(err, code) {
|
|
92
|
+
return err instanceof JsonApiError && err.errors.some((e) => e.code === code);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The first error object in `err` carrying `code`, or `undefined` when `err` is not a
|
|
96
|
+
* {@link JsonApiError} or none of its errors carries it. Takes any string; a generated client
|
|
97
|
+
* exports a `findError` bound to its documented codes and their `meta`, which types the result.
|
|
98
|
+
*/
|
|
99
|
+
function findError(err, code) {
|
|
100
|
+
return err instanceof JsonApiError ? err.errors.find((e) => e.code === code) : void 0;
|
|
101
|
+
}
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region src/nested-fieldset.ts
|
|
104
|
+
const NONE = Object.freeze({});
|
|
105
|
+
/**
|
|
106
|
+
* The {@link NestedFieldset} of one type's `fields[type]` members. The path is everything after the
|
|
107
|
+
* first full stop, as the server reads it, and a member with an empty key at any level selects
|
|
108
|
+
* nothing.
|
|
109
|
+
*/
|
|
110
|
+
function nestedFieldset(listed) {
|
|
111
|
+
if (listed === void 0) return NONE;
|
|
112
|
+
const members = listed.map(listItself);
|
|
113
|
+
const whole = new Set(members.filter((member) => !member.includes(".")));
|
|
114
|
+
const out = {};
|
|
115
|
+
for (const member of members) {
|
|
116
|
+
const dot = member.indexOf(".");
|
|
117
|
+
if (dot <= 0) continue;
|
|
118
|
+
const attribute = member.slice(0, dot);
|
|
119
|
+
if (whole.has(attribute)) continue;
|
|
120
|
+
const path = member.slice(dot + 1);
|
|
121
|
+
if (path.split(".").includes("")) continue;
|
|
122
|
+
const paths = out[attribute] ??= [];
|
|
123
|
+
if (!paths.includes(path)) paths.push(path);
|
|
124
|
+
}
|
|
125
|
+
for (const [attribute, paths] of Object.entries(out)) out[attribute] = paths.filter((path) => !paths.some((other) => other !== path && path.startsWith(`${other}.`)));
|
|
126
|
+
return Object.keys(out).length === 0 ? NONE : out;
|
|
127
|
+
}
|
|
128
|
+
/** A member ending in `.*` with the wildcard dropped, since it names the list itself. */
|
|
129
|
+
function listItself(member) {
|
|
130
|
+
let out = member;
|
|
131
|
+
while (out.endsWith(".*")) out = out.slice(0, -2);
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The `fields[type]` members a request URL carries, by type, for a link the client follows as
|
|
136
|
+
* given, such as a `next` page, whose query it didn't build.
|
|
137
|
+
*/
|
|
138
|
+
function fieldsOfUrl(url) {
|
|
139
|
+
let params;
|
|
140
|
+
try {
|
|
141
|
+
params = new URL(url, "http://link.invalid").searchParams;
|
|
142
|
+
} catch {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
let out;
|
|
146
|
+
params.forEach((value, name) => {
|
|
147
|
+
const type = /^fields\[(.+)\]$/.exec(name)?.[1];
|
|
148
|
+
if (type !== void 0) (out ??= {})[type] = value === "" ? [] : value.split(",");
|
|
149
|
+
});
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region src/validate.ts
|
|
154
|
+
/** Whether a `validate` option is the schema-driven config (vs a bare validator function). */
|
|
155
|
+
function isConfig(option) {
|
|
156
|
+
return typeof option === "object" && option !== null && !Array.isArray(option);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Normalise the `validate?` option to a single per-resource validator. The config form looks the
|
|
160
|
+
* schema up by `resource.type` and skips a type with no schema (the seam stays graceful for a
|
|
161
|
+
* partially-covered bundle); the bare-function form calls the validator with `schema = undefined`,
|
|
162
|
+
* delegating the whole decision to the caller. Returns `undefined` when validation is off.
|
|
163
|
+
*/
|
|
164
|
+
function resolveValidator(option) {
|
|
165
|
+
if (option === void 0) return;
|
|
166
|
+
if (isConfig(option)) {
|
|
167
|
+
const { schemas, validator } = option;
|
|
168
|
+
const sparse = sparseSchemas();
|
|
169
|
+
return { validate(resource, fields) {
|
|
170
|
+
const schema = schemas[resource.type];
|
|
171
|
+
if (schema === void 0) return;
|
|
172
|
+
if (fields === void 0) validator(resource, schema);
|
|
173
|
+
else validator(resource, sparse(schema, fields), { fields });
|
|
174
|
+
} };
|
|
175
|
+
}
|
|
176
|
+
return { validate(resource, fields) {
|
|
177
|
+
if (fields === void 0) option(resource, void 0);
|
|
178
|
+
else option(resource, void 0, { fields });
|
|
179
|
+
} };
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* A cache of {@link sparseSchema} results, by schema and fieldset, so each pair is relaxed once.
|
|
183
|
+
* A schema with no fieldset comes back as it is.
|
|
184
|
+
*/
|
|
185
|
+
function sparseSchemas() {
|
|
186
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
187
|
+
return (schema, fields) => {
|
|
188
|
+
if (fields === void 0 || !isObject(schema)) return schema;
|
|
189
|
+
let bySet = cache.get(schema);
|
|
190
|
+
if (bySet === void 0) {
|
|
191
|
+
bySet = /* @__PURE__ */ new Map();
|
|
192
|
+
cache.set(schema, bySet);
|
|
193
|
+
}
|
|
194
|
+
const key = fields.join(",");
|
|
195
|
+
if (!bySet.has(key)) bySet.set(key, sparseSchema(schema, fields));
|
|
196
|
+
return bySet.get(key);
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/** The {@link Narrowing} of key paths relative to one level, such as `b`, `c.d` or `*.sku`. */
|
|
200
|
+
function narrowingOf(paths) {
|
|
201
|
+
const keep = /* @__PURE__ */ new Set();
|
|
202
|
+
const whole = /* @__PURE__ */ new Set();
|
|
203
|
+
const deeper = /* @__PURE__ */ new Map();
|
|
204
|
+
for (const path of paths) {
|
|
205
|
+
const dot = path.indexOf(".");
|
|
206
|
+
const head = dot < 0 ? path : path.slice(0, dot);
|
|
207
|
+
keep.add(head);
|
|
208
|
+
if (dot < 0) whole.add(head);
|
|
209
|
+
else {
|
|
210
|
+
const rest = deeper.get(head) ?? [];
|
|
211
|
+
rest.push(path.slice(dot + 1));
|
|
212
|
+
deeper.set(head, rest);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const children = /* @__PURE__ */ new Map();
|
|
216
|
+
for (const [head, rest] of deeper) if (!whole.has(head)) children.set(head, narrowingOf(rest));
|
|
217
|
+
return {
|
|
218
|
+
keep,
|
|
219
|
+
children
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* One {@link Narrowing} for a schema several keys share, such as a map's `additionalProperties`:
|
|
224
|
+
* a key stays required only when every sharer renders it, and a key one sharer narrows is narrowed.
|
|
225
|
+
*/
|
|
226
|
+
function merged(narrowings) {
|
|
227
|
+
if (narrowings.length === 1) return narrowings[0];
|
|
228
|
+
const keep = new Set([...narrowings[0].keep].filter((key) => narrowings.every((n) => n.keep.has(key))));
|
|
229
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
230
|
+
for (const narrowing of narrowings) for (const [key, child] of narrowing.children) grouped.set(key, [...grouped.get(key) ?? [], child]);
|
|
231
|
+
const children = /* @__PURE__ */ new Map();
|
|
232
|
+
for (const [key, group] of grouped) children.set(key, merged(group));
|
|
233
|
+
return {
|
|
234
|
+
keep,
|
|
235
|
+
children
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/** The schema a local `$ref` such as `#/$defs/Address` points at within `root`. */
|
|
239
|
+
function resolveRef(root, ref) {
|
|
240
|
+
if (!ref.startsWith("#")) return;
|
|
241
|
+
let node = root;
|
|
242
|
+
for (const raw of ref.slice(1).split("/").slice(1)) {
|
|
243
|
+
const segment = decodeURIComponent(raw).replace(/~1/g, "/").replace(/~0/g, "~");
|
|
244
|
+
node = isObject(node) ? node[segment] : void 0;
|
|
245
|
+
}
|
|
246
|
+
return node;
|
|
247
|
+
}
|
|
248
|
+
/** `schema` with `narrowing` applied: its `required` cut to what the level renders, its narrowed keys relaxed in turn. */
|
|
249
|
+
function narrowed(root, schema, narrowing, depth = 0) {
|
|
250
|
+
if (!isObject(schema) || depth > 64) return schema;
|
|
251
|
+
if (typeof schema["$ref"] === "string") {
|
|
252
|
+
const { $ref: ref, ...siblings } = schema;
|
|
253
|
+
const target = resolveRef(root, ref);
|
|
254
|
+
if (isObject(target)) return narrowed(root, {
|
|
255
|
+
...target,
|
|
256
|
+
...siblings
|
|
257
|
+
}, narrowing, depth + 1);
|
|
258
|
+
}
|
|
259
|
+
const out = { ...schema };
|
|
260
|
+
const discriminator = isObject(out["discriminator"]) ? out["discriminator"]["propertyName"] : null;
|
|
261
|
+
const branchNarrowing = typeof discriminator === "string" ? {
|
|
262
|
+
keep: /* @__PURE__ */ new Set([...narrowing.keep, discriminator]),
|
|
263
|
+
children: narrowing.children
|
|
264
|
+
} : narrowing;
|
|
265
|
+
for (const key of [
|
|
266
|
+
"anyOf",
|
|
267
|
+
"oneOf",
|
|
268
|
+
"allOf"
|
|
269
|
+
]) {
|
|
270
|
+
const branches = out[key];
|
|
271
|
+
if (Array.isArray(branches)) out[key] = branches.map((branch) => narrowed(root, branch, branchNarrowing, depth + 1));
|
|
272
|
+
}
|
|
273
|
+
if (Array.isArray(out["oneOf"]) && typeof discriminator !== "string") {
|
|
274
|
+
const { oneOf, ...rest } = out;
|
|
275
|
+
return out["anyOf"] === void 0 ? narrowedLevel(root, {
|
|
276
|
+
...rest,
|
|
277
|
+
anyOf: oneOf
|
|
278
|
+
}, narrowing, depth) : narrowedLevel(root, {
|
|
279
|
+
...rest,
|
|
280
|
+
allOf: [...rest["allOf"] ?? [], { anyOf: oneOf }]
|
|
281
|
+
}, narrowing, depth);
|
|
282
|
+
}
|
|
283
|
+
return narrowedLevel(root, out, narrowing, depth);
|
|
284
|
+
}
|
|
285
|
+
/** The rest of {@link narrowed}: one level's own `required` and keys. */
|
|
286
|
+
function narrowedLevel(root, out, narrowing, depth) {
|
|
287
|
+
const required = out["required"];
|
|
288
|
+
if (Array.isArray(required)) out["required"] = required.filter((key) => typeof key === "string" && narrowing.keep.has(key));
|
|
289
|
+
const properties = isObject(out["properties"]) ? { ...out["properties"] } : void 0;
|
|
290
|
+
const patterns = isObject(out["patternProperties"]) ? out["patternProperties"] : void 0;
|
|
291
|
+
const shared = /* @__PURE__ */ new Map();
|
|
292
|
+
const share = (target, child) => {
|
|
293
|
+
shared.set(target, [...shared.get(target) ?? [], child]);
|
|
294
|
+
};
|
|
295
|
+
for (const [key, child] of narrowing.children) {
|
|
296
|
+
if (key === "*") {
|
|
297
|
+
if (isObject(out["items"])) out["items"] = narrowed(root, out["items"], child, depth + 1);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (properties !== void 0 && key in properties) {
|
|
301
|
+
properties[key] = narrowed(root, properties[key], child, depth + 1);
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
const matching = Object.keys(patterns ?? {}).filter((pattern) => matches(pattern, key));
|
|
305
|
+
if (matching.length > 0) matching.forEach((pattern) => share(`pattern:${pattern}`, child));
|
|
306
|
+
else if (isObject(out["additionalProperties"])) share("additional", child);
|
|
307
|
+
}
|
|
308
|
+
if (properties !== void 0) out["properties"] = properties;
|
|
309
|
+
if (patterns !== void 0) {
|
|
310
|
+
const next = { ...patterns };
|
|
311
|
+
for (const pattern of Object.keys(patterns)) {
|
|
312
|
+
const group = shared.get(`pattern:${pattern}`);
|
|
313
|
+
if (group !== void 0) next[pattern] = narrowed(root, patterns[pattern], merged(group), depth + 1);
|
|
314
|
+
}
|
|
315
|
+
out["patternProperties"] = next;
|
|
316
|
+
}
|
|
317
|
+
const additional = shared.get("additional");
|
|
318
|
+
if (additional !== void 0) out["additionalProperties"] = narrowed(root, out["additionalProperties"], merged(additional), depth + 1);
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
321
|
+
/** Whether a `patternProperties` pattern matches `key`; an unreadable pattern matches nothing. */
|
|
322
|
+
function matches(pattern, key) {
|
|
323
|
+
try {
|
|
324
|
+
return new RegExp(pattern, "u").test(key);
|
|
325
|
+
} catch {
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* A resource object schema relaxed for a response to a request whose sparse fieldset for the type
|
|
331
|
+
* named `members`. An attribute or relation the fieldset leaves out is no longer required, and an
|
|
332
|
+
* attribute it narrows to some of its keys, such as `address.city`, `location.geo.lat` or
|
|
333
|
+
* `lines.*.sku`, requires only the keys selected at each level along those paths. A member the
|
|
334
|
+
* fieldset also lists whole is left as declared, as the server renders it whole. Everything else
|
|
335
|
+
* in the schema is kept, so a selected value is still checked, but for its `$id`: the copy is a
|
|
336
|
+
* schema of its own.
|
|
337
|
+
*/
|
|
338
|
+
function sparseSchema(schema, members) {
|
|
339
|
+
if (!isObject(schema)) return schema;
|
|
340
|
+
const selection = nestedFieldset(members);
|
|
341
|
+
const selected = /* @__PURE__ */ new Set([...members.map((member) => member.replace(/(?:\.\*)+$/, "")).filter((member) => member !== "" && !member.includes(".")), ...Object.keys(selection)]);
|
|
342
|
+
const children = /* @__PURE__ */ new Map();
|
|
343
|
+
for (const [attribute, paths] of Object.entries(selection)) children.set(attribute, narrowingOf(paths));
|
|
344
|
+
const required = Array.isArray(schema["required"]) ? schema["required"] : [];
|
|
345
|
+
const out = narrowed(schema, schema, {
|
|
346
|
+
keep: new Set(required.filter((key) => typeof key === "string" && key !== "attributes" && key !== "relationships")),
|
|
347
|
+
children: /* @__PURE__ */ new Map([["attributes", {
|
|
348
|
+
keep: selected,
|
|
349
|
+
children
|
|
350
|
+
}], ["relationships", {
|
|
351
|
+
keep: selected,
|
|
352
|
+
children: /* @__PURE__ */ new Map()
|
|
353
|
+
}]])
|
|
354
|
+
});
|
|
355
|
+
delete out["$id"];
|
|
356
|
+
return out;
|
|
357
|
+
}
|
|
358
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
359
|
+
/**
|
|
360
|
+
* The light structural guards every parsed response passes through (ADR 0004): assert the body
|
|
361
|
+
* is a JSON:API document and that each `data`/`included` member carries a string `type` (and,
|
|
362
|
+
* for a full resource, an `id`). This is the always-on, engine-free floor — it never duplicates
|
|
363
|
+
* the opt-in per-field validation; it only proves the envelope invariant the runtime relies on.
|
|
364
|
+
*
|
|
365
|
+
* A primary-`data` resource and every `included` resource must carry `type`+`id`. A relationship
|
|
366
|
+
* endpoint's primary data is pure resource-identifier linkage, which also carries `type`+`id`, so
|
|
367
|
+
* the same guard holds; `linkage` is accepted for symmetry with the materialiser but the assertion
|
|
368
|
+
* is identical (an identifier is `type`+`id`). `data: null` (an empty to-one) and a missing
|
|
369
|
+
* `data` (a meta-only document) are valid and pass.
|
|
370
|
+
*/
|
|
371
|
+
function assertJsonApiDocument(body) {
|
|
372
|
+
if (!isObject(body)) throw new StructuralGuardError("Response body is not a JSON:API document (expected an object)");
|
|
373
|
+
if (!("data" in body) && !("meta" in body)) throw new StructuralGuardError("Response body is not a JSON:API document (missing top-level \"data\" or \"meta\")");
|
|
374
|
+
const data = body["data"];
|
|
375
|
+
if (Array.isArray(data)) data.forEach((member, i) => assertResource(member, `data[${i}]`));
|
|
376
|
+
else if (data !== null && data !== void 0) assertResource(data, "data");
|
|
377
|
+
const included = body["included"];
|
|
378
|
+
if (included !== void 0) {
|
|
379
|
+
if (!Array.isArray(included)) throw new StructuralGuardError("Response \"included\" is not an array");
|
|
380
|
+
included.forEach((member, i) => assertResource(member, `included[${i}]`));
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/** Assert a single member is a resource object/identifier carrying string `type` + `id`. */
|
|
384
|
+
function assertResource(member, at) {
|
|
385
|
+
if (!isObject(member)) throw new StructuralGuardError(`${at} is not a JSON:API resource object`);
|
|
386
|
+
if (typeof member["type"] !== "string") throw new StructuralGuardError(`${at} is missing a string "type"`);
|
|
387
|
+
if (typeof member["id"] !== "string") throw new StructuralGuardError(`${at} (type "${member["type"]}") is missing a string "id"`);
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Run the opt-in validator over every wire resource in a document's `data` + `included`, each
|
|
391
|
+
* against its per-type schema. Called only when a validator is configured (off by default). The
|
|
392
|
+
* structural guards have already proven each member carries `type`+`id`, so the cast is sound.
|
|
393
|
+
*/
|
|
394
|
+
function validateDocument(body, validator, fields) {
|
|
395
|
+
const data = body.data;
|
|
396
|
+
if (Array.isArray(data)) for (const member of data) validateResourceMember(member, validator, fields);
|
|
397
|
+
else if (data !== null && data !== void 0) validateResourceMember(data, validator, fields);
|
|
398
|
+
if (body.included !== void 0) for (const member of body.included) {
|
|
399
|
+
const resource = member;
|
|
400
|
+
validator.validate(resource, fields?.[resource.type]);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Validate a `data` member, but only when it is a full RESOURCE OBJECT. A relationship-linkage
|
|
405
|
+
* endpoint's `data` is bare resource IDENTIFIERS (`type`+`id`[+`meta`], no `attributes`/
|
|
406
|
+
* `relationships`); the per-type schema describes the resource object, so running it over an
|
|
407
|
+
* identifier would spuriously fail. The structural guard already covered the identifier shape.
|
|
408
|
+
*/
|
|
409
|
+
function validateResourceMember(member, validator, fields) {
|
|
410
|
+
if (isObject(member) && ("attributes" in member || "relationships" in member)) {
|
|
411
|
+
const resource = member;
|
|
412
|
+
validator.validate(resource, fields?.[resource.type]);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
//#endregion
|
|
416
|
+
Object.defineProperty(exports, "JsonApiError", {
|
|
417
|
+
enumerable: true,
|
|
418
|
+
get: function() {
|
|
419
|
+
return JsonApiError;
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
Object.defineProperty(exports, "StructuralGuardError", {
|
|
423
|
+
enumerable: true,
|
|
424
|
+
get: function() {
|
|
425
|
+
return StructuralGuardError;
|
|
426
|
+
}
|
|
427
|
+
});
|
|
428
|
+
Object.defineProperty(exports, "assertJsonApiDocument", {
|
|
429
|
+
enumerable: true,
|
|
430
|
+
get: function() {
|
|
431
|
+
return assertJsonApiDocument;
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
Object.defineProperty(exports, "fieldsOfUrl", {
|
|
435
|
+
enumerable: true,
|
|
436
|
+
get: function() {
|
|
437
|
+
return fieldsOfUrl;
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
Object.defineProperty(exports, "findError", {
|
|
441
|
+
enumerable: true,
|
|
442
|
+
get: function() {
|
|
443
|
+
return findError;
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
Object.defineProperty(exports, "hasErrorCode", {
|
|
447
|
+
enumerable: true,
|
|
448
|
+
get: function() {
|
|
449
|
+
return hasErrorCode;
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
Object.defineProperty(exports, "nestedFieldset", {
|
|
453
|
+
enumerable: true,
|
|
454
|
+
get: function() {
|
|
455
|
+
return nestedFieldset;
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
Object.defineProperty(exports, "resolveValidator", {
|
|
459
|
+
enumerable: true,
|
|
460
|
+
get: function() {
|
|
461
|
+
return resolveValidator;
|
|
462
|
+
}
|
|
463
|
+
});
|
|
464
|
+
Object.defineProperty(exports, "sparseSchema", {
|
|
465
|
+
enumerable: true,
|
|
466
|
+
get: function() {
|
|
467
|
+
return sparseSchema;
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
Object.defineProperty(exports, "sparseSchemas", {
|
|
471
|
+
enumerable: true,
|
|
472
|
+
get: function() {
|
|
473
|
+
return sparseSchemas;
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
Object.defineProperty(exports, "validateDocument", {
|
|
477
|
+
enumerable: true,
|
|
478
|
+
get: function() {
|
|
479
|
+
return validateDocument;
|
|
480
|
+
}
|
|
481
|
+
});
|