@haddowg/json-api-client 1.16.0 → 1.18.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 +20 -0
- package/dist/ajv.d.cts +1 -1
- package/dist/ajv.d.mts +1 -1
- package/dist/index.cjs +426 -207
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +423 -208
- package/dist/index.mjs.map +1 -1
- package/dist/{validate-DCMTndv-.d.cts → validate-Cknhw9k7.d.cts} +311 -30
- package/dist/validate-Cknhw9k7.d.cts.map +1 -0
- package/dist/{validate-DCMTndv-.d.mts → validate-Cknhw9k7.d.mts} +311 -30
- package/dist/validate-Cknhw9k7.d.mts.map +1 -0
- package/package.json +1 -1
- package/dist/validate-DCMTndv-.d.cts.map +0 -1
- package/dist/validate-DCMTndv-.d.mts.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -101,6 +101,324 @@ function findError(err, code) {
|
|
|
101
101
|
return err instanceof JsonApiError ? err.errors.find((e) => e.code === code) : void 0;
|
|
102
102
|
}
|
|
103
103
|
//#endregion
|
|
104
|
+
//#region src/types.ts
|
|
105
|
+
/** The JSON:API media type. */
|
|
106
|
+
const JSON_API_MEDIA_TYPE = "application/vnd.api+json";
|
|
107
|
+
/** The Atomic Operations extension URI. */
|
|
108
|
+
const ATOMIC_EXT = "https://jsonapi.org/ext/atomic";
|
|
109
|
+
/**
|
|
110
|
+
* Compose the JSON:API media type with any opted-in `ext`/`profile` parameters. Each parameter
|
|
111
|
+
* is a space-joined, double-quoted URI list, in the canonical order `ext` then `profile` so the
|
|
112
|
+
* output is deterministic (stable for caching/assertions). Empty/absent lists are omitted; with
|
|
113
|
+
* neither, the bare {@link JSON_API_MEDIA_TYPE} is returned (no behaviour change for a plain
|
|
114
|
+
* request). Used for both `Accept` and (when a body is present) `Content-Type`.
|
|
115
|
+
*/
|
|
116
|
+
function mediaType(params = {}) {
|
|
117
|
+
let out = JSON_API_MEDIA_TYPE;
|
|
118
|
+
if (params.ext !== void 0 && params.ext.length > 0) out += `; ext="${params.ext.join(" ")}"`;
|
|
119
|
+
if (params.profiles !== void 0 && params.profiles.length > 0) out += `; profile="${params.profiles.join(" ")}"`;
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The media type for an Atomic Operations request/response: the JSON:API media type carrying
|
|
124
|
+
* the atomic `ext` parameter. Sent as both `Content-Type` and `Accept` on a `client.atomic`
|
|
125
|
+
* batch (per the JSON:API atomic extension).
|
|
126
|
+
*/
|
|
127
|
+
const ATOMIC_MEDIA_TYPE = mediaType({ ext: [ATOMIC_EXT] });
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/request.ts
|
|
130
|
+
const isAbsolute = (path) => /^https?:\/\//i.test(path);
|
|
131
|
+
const RELATIVE_ORIGIN = "http://relative.invalid";
|
|
132
|
+
/**
|
|
133
|
+
* Resolve a server link against `baseUrl` per RFC 3986 and check where it lands. A link on the
|
|
134
|
+
* base's origin is followed; a relative base (e.g. `/api`) takes the page's origin in a browser and
|
|
135
|
+
* otherwise only accepts a link that keeps the host. Anything that isn't plain http(s) is refused.
|
|
136
|
+
*/
|
|
137
|
+
function resolveLink(link, baseUrl) {
|
|
138
|
+
let normalised = link.replace(/[\t\n\r]/g, "");
|
|
139
|
+
let start = 0;
|
|
140
|
+
while (start < normalised.length && normalised.charCodeAt(start) <= 32) start++;
|
|
141
|
+
normalised = normalised.slice(start);
|
|
142
|
+
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalised)?.[1]?.toLowerCase();
|
|
143
|
+
if (scheme !== void 0 && scheme !== "http" && scheme !== "https") throw new Error(`Refusing to follow link "${link}": only http(s) links are followed`);
|
|
144
|
+
const relativeBase = !isAbsolute(baseUrl);
|
|
145
|
+
const page = globalThis.location?.href;
|
|
146
|
+
const base = new URL(baseUrl, relativeBase ? typeof page === "string" ? page : RELATIVE_ORIGIN : void 0);
|
|
147
|
+
const resolved = new URL(link, base);
|
|
148
|
+
const sameOrigin = resolved.origin === base.origin && (scheme === void 0 || /^https?:\/\//i.test(normalised));
|
|
149
|
+
if (!sameOrigin) return {
|
|
150
|
+
url: resolved.href,
|
|
151
|
+
sameOrigin
|
|
152
|
+
};
|
|
153
|
+
return {
|
|
154
|
+
url: relativeBase ? resolved.pathname + resolved.search + resolved.hash : resolved.href,
|
|
155
|
+
sameOrigin
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
const append = (parts, key, value) => {
|
|
159
|
+
if (value === void 0 || value === null || value === "") return;
|
|
160
|
+
parts.push(`${key}=${encodeURIComponent(String(value))}`);
|
|
161
|
+
};
|
|
162
|
+
const isPlainObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
163
|
+
/**
|
|
164
|
+
* Append a filter value under its (already-bracketed) key. A plain object is a STRUCTURED filter
|
|
165
|
+
* value — a `Range`/`DateRange` deepObject (`{ min, max }`) — and recurses into nested bracketed
|
|
166
|
+
* keys (`filter[k][min]=`), matching the server's deepObject wire shape; an array goes out once per
|
|
167
|
+
* member as `filter[k][]=` for a filter that takes a list, so a member may hold a comma, and joins
|
|
168
|
+
* with `,` otherwise; a scalar is appended directly. Without the object branch a `{ min, max }` value would reach the
|
|
169
|
+
* wire as `filter[k]=[object Object]` and be silently ignored by the server.
|
|
170
|
+
*/
|
|
171
|
+
const appendFilterValue = (parts, key, value, list = false) => {
|
|
172
|
+
if (isPlainObject$1(value)) {
|
|
173
|
+
for (const [subKey, subValue] of Object.entries(value)) appendFilterValue(parts, `${key}[${subKey}]`, subValue);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (list && Array.isArray(value)) {
|
|
177
|
+
for (const member of value) append(parts, `${key}[]`, member);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
append(parts, key, Array.isArray(value) ? value.join(",") : value);
|
|
181
|
+
};
|
|
182
|
+
/**
|
|
183
|
+
* Serialise a read query to a query string (no leading `?`). Bracketed keys
|
|
184
|
+
* (`filter[title]`, `page[number]`, `fields[albums]`) are kept literal; only values
|
|
185
|
+
* are percent-encoded. `isListFilter` names the filter keys that take a list, whose array value
|
|
186
|
+
* goes out as `filter[<key>][]` once per member, and `isRelatedListFilter` does the same for a
|
|
187
|
+
* `relatedQuery` entry's filters by include path. Empty/undefined entries are skipped; key order is deterministic
|
|
188
|
+
* (family order, then insertion order within a family) so URLs are stable for caching.
|
|
189
|
+
*/
|
|
190
|
+
function serializeQuery(query, isListFilter, isRelatedListFilter) {
|
|
191
|
+
const parts = [];
|
|
192
|
+
if (query.filter) for (const [key, value] of Object.entries(query.filter)) appendFilterValue(parts, `filter[${key}]`, value, isListFilter?.(key) ?? false);
|
|
193
|
+
if (query.sort !== void 0) append(parts, "sort", Array.isArray(query.sort) ? query.sort.join(",") : query.sort);
|
|
194
|
+
if (query.include) append(parts, "include", query.include.join(","));
|
|
195
|
+
if (query.fields) for (const [type, names] of Object.entries(query.fields)) parts.push(`fields[${type}]=${encodeURIComponent(names.join(","))}`);
|
|
196
|
+
if (query.withCount && query.withCount.length > 0) append(parts, "withCount", query.withCount.join(","));
|
|
197
|
+
for (const [path, entry] of Object.entries(query.relatedQuery ?? {})) {
|
|
198
|
+
for (const [key, value] of Object.entries(entry?.filter ?? {})) appendFilterValue(parts, `relatedQuery[${path}][filter][${key}]`, value, isRelatedListFilter?.(path, key) ?? false);
|
|
199
|
+
if (entry?.sort !== void 0) append(parts, `relatedQuery[${path}][sort]`, typeof entry.sort === "string" ? entry.sort : entry.sort.join(","));
|
|
200
|
+
}
|
|
201
|
+
if (query.page) for (const [key, value] of Object.entries(query.page)) append(parts, `page[${key}]`, Array.isArray(value) ? value.join(",") : value);
|
|
202
|
+
return parts.join("&");
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Execute a request: build the URL (a server link resolved against `baseUrl` and held to its
|
|
206
|
+
* origin, an absolute path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request headers,
|
|
207
|
+
* then drive the transport. A 2xx with a body parses to a {@link Document}; an empty /
|
|
208
|
+
* 204 body resolves to `undefined`. A non-2xx throws a {@link JsonApiError} carrying the
|
|
209
|
+
* parsed error objects (tolerating a non-JSON error body with an empty list).
|
|
210
|
+
*/
|
|
211
|
+
async function execute(ctx, req) {
|
|
212
|
+
return parseDocument((await send(ctx, req)).body);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Execute a request as {@link execute} does, keeping the response's status and headers. With
|
|
216
|
+
* `seeOther`, a `303` the transport didn't follow resolves with no document instead of throwing,
|
|
217
|
+
* so the caller can read its `Location`.
|
|
218
|
+
*/
|
|
219
|
+
async function executeResponse(ctx, req, seeOther = false) {
|
|
220
|
+
const res = await send(ctx, req, void 0, seeOther);
|
|
221
|
+
return {
|
|
222
|
+
status: res.status,
|
|
223
|
+
headers: res.headers,
|
|
224
|
+
document: res.status === 303 ? void 0 : parseDocument(res.body)
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
async function executeRaw(ctx, req, as) {
|
|
228
|
+
const res = await send(ctx, req, as === "text" ? void 0 : as);
|
|
229
|
+
if (as === "text") return res.body === "" ? void 0 : res.body;
|
|
230
|
+
if (res.status === 204) return;
|
|
231
|
+
if (res.binary === void 0) throw new Error("The transport returned no binary body for a request that asked for one; a custom transport must read the response as binary when the request sets responseType.");
|
|
232
|
+
return res.binary;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Build the URL (a server link resolved against `baseUrl` and held to its origin, an absolute
|
|
236
|
+
* path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request
|
|
237
|
+
* headers, then drive the transport. A non-2xx throws a {@link JsonApiError} carrying the parsed
|
|
238
|
+
* error objects (tolerating a non-JSON error body with an empty list).
|
|
239
|
+
*/
|
|
240
|
+
async function send(ctx, req, responseType, seeOther = false) {
|
|
241
|
+
let url;
|
|
242
|
+
let sendHeaders = true;
|
|
243
|
+
if (req.link) {
|
|
244
|
+
const link = resolveLink(req.path, ctx.baseUrl);
|
|
245
|
+
if (!link.sameOrigin && ctx.allowCrossOriginLinks !== true) throw new Error(`Refusing to follow link "${req.path}": it leaves the base URL's origin (set allowCrossOriginLinks to follow it without the configured headers)`);
|
|
246
|
+
url = link.url;
|
|
247
|
+
sendHeaders = link.sameOrigin;
|
|
248
|
+
} else url = isAbsolute(req.path) ? req.path : ctx.baseUrl + req.path;
|
|
249
|
+
if (req.query) {
|
|
250
|
+
const qs = serializeQuery(req.query, req.listFilter, req.relatedListFilter);
|
|
251
|
+
if (qs) url += (url.includes("?") ? "&" : "?") + qs;
|
|
252
|
+
}
|
|
253
|
+
const negotiated = mediaType({
|
|
254
|
+
ext: req.ext,
|
|
255
|
+
profiles: req.profiles
|
|
256
|
+
});
|
|
257
|
+
const headers = { Accept: req.accept ?? negotiated };
|
|
258
|
+
const transportReq = {
|
|
259
|
+
method: req.method,
|
|
260
|
+
url,
|
|
261
|
+
headers
|
|
262
|
+
};
|
|
263
|
+
if (req.signal !== void 0) transportReq.signal = req.signal;
|
|
264
|
+
if (responseType !== void 0) transportReq.responseType = responseType;
|
|
265
|
+
if (req.body !== void 0 || req.method.toUpperCase() === "POST") {
|
|
266
|
+
const contentType = req.contentType === void 0 ? negotiated : req.contentType;
|
|
267
|
+
if (contentType !== null) headers["Content-Type"] = contentType;
|
|
268
|
+
}
|
|
269
|
+
if (typeof req.body === "string" && req.raw) transportReq.body = req.body;
|
|
270
|
+
else if (req.raw && isRawBody(req.body)) transportReq.rawBody = req.body;
|
|
271
|
+
else if (req.body !== void 0) transportReq.body = JSON.stringify(req.body);
|
|
272
|
+
if (ctx.headers && sendHeaders) mergeHeaders(headers, await ctx.headers());
|
|
273
|
+
const res = await ctx.transport(transportReq);
|
|
274
|
+
if (res.status >= 200 && res.status < 300 || seeOther && res.status === 303) return res;
|
|
275
|
+
throw new JsonApiError(res.status, parseErrors(res.body));
|
|
276
|
+
}
|
|
277
|
+
/** Whether a raw body goes to the transport as is rather than through `JSON.stringify`. */
|
|
278
|
+
function isRawBody(body) {
|
|
279
|
+
return typeof Blob !== "undefined" && body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof FormData !== "undefined" && body instanceof FormData || typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Merge a `HeadersInit` (object / tuple array / `Headers`) into the outgoing map,
|
|
283
|
+
* preserving the caller's casing (unlike the WHATWG `Headers`, which lowercases). The
|
|
284
|
+
* caller's headers override the runtime defaults, so per-request `Accept` etc. can win.
|
|
285
|
+
*/
|
|
286
|
+
function mergeHeaders(into, extra) {
|
|
287
|
+
if (extra instanceof Headers) extra.forEach((value, key) => {
|
|
288
|
+
into[key] = value;
|
|
289
|
+
});
|
|
290
|
+
else if (Array.isArray(extra)) {
|
|
291
|
+
for (const [key, value] of extra) if (key !== void 0 && value !== void 0) into[key] = String(value);
|
|
292
|
+
} else for (const [key, value] of Object.entries(extra)) into[key] = String(value);
|
|
293
|
+
}
|
|
294
|
+
function parseDocument(body) {
|
|
295
|
+
if (body === "") return;
|
|
296
|
+
return JSON.parse(body);
|
|
297
|
+
}
|
|
298
|
+
function parseErrors(body) {
|
|
299
|
+
if (body === "") return [];
|
|
300
|
+
try {
|
|
301
|
+
const doc = JSON.parse(body);
|
|
302
|
+
return Array.isArray(doc.errors) ? doc.errors : [];
|
|
303
|
+
} catch {
|
|
304
|
+
return [];
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
//#endregion
|
|
308
|
+
//#region src/accepted.ts
|
|
309
|
+
/** Thrown when a job is still pending when the poll's timeout runs out. */
|
|
310
|
+
var PollTimeoutError = class extends Error {
|
|
311
|
+
contentLocation;
|
|
312
|
+
timeout;
|
|
313
|
+
constructor(contentLocation, timeout) {
|
|
314
|
+
super(`The job at ${contentLocation} was still pending after ${timeout}ms`);
|
|
315
|
+
this.name = "PollTimeoutError";
|
|
316
|
+
this.contentLocation = contentLocation;
|
|
317
|
+
this.timeout = timeout;
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
const ACCEPTED = Symbol.for("@haddowg/json-api-client/accepted");
|
|
321
|
+
/** Whether a write's result is an {@link Accepted} job rather than its normal result. */
|
|
322
|
+
function isAccepted(value) {
|
|
323
|
+
return typeof value === "object" && value !== null && ACCEPTED in value;
|
|
324
|
+
}
|
|
325
|
+
const DEFAULT_TIMEOUT = 300 * 1e3;
|
|
326
|
+
const DEFAULT_INTERVAL = 1e3;
|
|
327
|
+
/** A response header by name, whatever case the transport wrote it in. */
|
|
328
|
+
function header(headers, name) {
|
|
329
|
+
const wanted = name.toLowerCase();
|
|
330
|
+
for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === wanted) return value;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* A `Retry-After` value in seconds: delta-seconds as sent, an HTTP date as the seconds left until
|
|
334
|
+
* it, rounded up and never negative. `undefined` when absent or unreadable.
|
|
335
|
+
*/
|
|
336
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
337
|
+
const trimmed = value?.trim();
|
|
338
|
+
if (trimmed === void 0 || trimmed === "") return;
|
|
339
|
+
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
|
340
|
+
const at = Date.parse(trimmed);
|
|
341
|
+
return Number.isNaN(at) ? void 0 : Math.max(0, Math.ceil((at - now) / 1e3));
|
|
342
|
+
}
|
|
343
|
+
/** Whether a document is a meta-only one: no primary `data` member. */
|
|
344
|
+
const isMetaOnly = (doc) => doc === void 0 || !("data" in doc);
|
|
345
|
+
/** The `type` of a document's single primary resource, if it has one. */
|
|
346
|
+
function primaryType(doc) {
|
|
347
|
+
const data = doc?.data;
|
|
348
|
+
return typeof data === "object" && data !== null && !Array.isArray(data) ? data["type"] : void 0;
|
|
349
|
+
}
|
|
350
|
+
/** Build the {@link Accepted} for a `202` response. */
|
|
351
|
+
function toAccepted(target, res) {
|
|
352
|
+
const contentLocation = header(res.headers, "Content-Location");
|
|
353
|
+
if (contentLocation === void 0) throw new Error("The server answered 202 Accepted without a Content-Location to poll.");
|
|
354
|
+
const metaJob = isMetaOnly(res.document);
|
|
355
|
+
const retryAfter = parseRetryAfter(header(res.headers, "Retry-After"));
|
|
356
|
+
const value = {
|
|
357
|
+
job: target.job(res.document),
|
|
358
|
+
contentLocation,
|
|
359
|
+
retryAfter
|
|
360
|
+
};
|
|
361
|
+
Object.defineProperty(value, ACCEPTED, {
|
|
362
|
+
value: true,
|
|
363
|
+
enumerable: false
|
|
364
|
+
});
|
|
365
|
+
Object.defineProperty(value, "$poll", {
|
|
366
|
+
value: (options) => poll(target, contentLocation, metaJob, retryAfter, options),
|
|
367
|
+
enumerable: false
|
|
368
|
+
});
|
|
369
|
+
return value;
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Poll the job URL. A `2xx` still holding the job (its type, or a meta-only document for a
|
|
373
|
+
* meta-only job) is pending: wait for its `Retry-After`, else the `202`'s, else a second. A `303`
|
|
374
|
+
* the transport didn't follow is done, and its `Location` is fetched; any other `2xx` is the
|
|
375
|
+
* redirect already followed. A non-2xx throws the usual {@link JsonApiError}.
|
|
376
|
+
*/
|
|
377
|
+
async function poll(target, contentLocation, metaJob, acceptedRetryAfter, options = {}) {
|
|
378
|
+
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
|
|
379
|
+
const signal = options.signal;
|
|
380
|
+
const deadline = Date.now() + timeout;
|
|
381
|
+
const get = (path, seeOther) => executeResponse(target.request, {
|
|
382
|
+
method: "GET",
|
|
383
|
+
path,
|
|
384
|
+
link: true,
|
|
385
|
+
...signal !== void 0 ? { signal } : {}
|
|
386
|
+
}, seeOther);
|
|
387
|
+
const holdsJob = (doc) => doc !== void 0 && (primaryType(doc) === target.jobType || metaJob && isMetaOnly(doc));
|
|
388
|
+
let delay = (acceptedRetryAfter ?? DEFAULT_INTERVAL / 1e3) * 1e3;
|
|
389
|
+
for (;;) {
|
|
390
|
+
const remaining = deadline - Date.now();
|
|
391
|
+
if (remaining <= 0) throw new PollTimeoutError(contentLocation, timeout);
|
|
392
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
393
|
+
const res = await get(contentLocation, true);
|
|
394
|
+
if (res.status === 303) {
|
|
395
|
+
const location = header(res.headers, "Location");
|
|
396
|
+
if (location === void 0) throw new Error(`The job at ${contentLocation} answered 303 without a Location.`);
|
|
397
|
+
return target.complete((await get(location, false)).document);
|
|
398
|
+
}
|
|
399
|
+
if (!holdsJob(res.document)) return target.complete(res.document);
|
|
400
|
+
delay = (parseRetryAfter(header(res.headers, "Retry-After")) ?? acceptedRetryAfter ?? DEFAULT_INTERVAL / 1e3) * 1e3;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** Resolve after `ms`, or reject with the signal's reason when it aborts first. */
|
|
404
|
+
function sleep(ms, signal) {
|
|
405
|
+
return new Promise((resolve, reject) => {
|
|
406
|
+
if (signal?.aborted) {
|
|
407
|
+
reject(signal.reason);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const onAbort = () => {
|
|
411
|
+
clearTimeout(timer);
|
|
412
|
+
reject(signal.reason);
|
|
413
|
+
};
|
|
414
|
+
const timer = setTimeout(() => {
|
|
415
|
+
signal?.removeEventListener("abort", onAbort);
|
|
416
|
+
resolve();
|
|
417
|
+
}, ms);
|
|
418
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
//#endregion
|
|
104
422
|
//#region src/pagination.ts
|
|
105
423
|
/** The wire key for each role when the server keeps the default names. */
|
|
106
424
|
const CANONICAL_PAGE_KEYS = {
|
|
@@ -238,6 +556,11 @@ const defineGetter = (target, key, get) => {
|
|
|
238
556
|
configurable: true
|
|
239
557
|
});
|
|
240
558
|
};
|
|
559
|
+
/** A relationship object's `meta.total` when it is a finite number, else `undefined`. */
|
|
560
|
+
const relationTotal = (rel) => {
|
|
561
|
+
const total = rel?.meta?.["total"];
|
|
562
|
+
return typeof total === "number" && Number.isFinite(total) ? total : void 0;
|
|
563
|
+
};
|
|
241
564
|
/**
|
|
242
565
|
* Materialise a JSON:API document into a hydrated graph (ADR 0002):
|
|
243
566
|
*
|
|
@@ -342,7 +665,7 @@ function resolveMember(member, env, index, nodes, ctx, relationEdge) {
|
|
|
342
665
|
if (included) return buildEdgeView(buildNode(included, env, index, nodes, ctx), member, relationEdge);
|
|
343
666
|
return buildIdentifierView(member, relationEdge);
|
|
344
667
|
}
|
|
345
|
-
/** Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$rel). */
|
|
668
|
+
/** Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$rel/$count). */
|
|
346
669
|
function attachResourceEnvelope(node, raw, env, rels) {
|
|
347
670
|
defineGetter(node, "$meta", () => raw.meta);
|
|
348
671
|
defineGetter(node, "$links", () => raw.links);
|
|
@@ -358,6 +681,7 @@ function attachResourceEnvelope(node, raw, env, rels) {
|
|
|
358
681
|
if (rel.meta !== void 0) view.meta = rel.meta;
|
|
359
682
|
return view;
|
|
360
683
|
});
|
|
684
|
+
define(node, "$count", (name) => Object.hasOwn(rels, name) ? relationTotal(rels[name]) : void 0);
|
|
361
685
|
}
|
|
362
686
|
/**
|
|
363
687
|
* A per-edge VIEW over a node: a distinct wrapper per membership that reads through to the
|
|
@@ -376,7 +700,8 @@ function buildEdgeView(node, member, relationEdge) {
|
|
|
376
700
|
"$self",
|
|
377
701
|
"$document",
|
|
378
702
|
"$raw",
|
|
379
|
-
"$rel"
|
|
703
|
+
"$rel",
|
|
704
|
+
"$count"
|
|
380
705
|
]) delegate(view, node, k);
|
|
381
706
|
attachEdgeEnvelope(view, member, false, relationEdge);
|
|
382
707
|
return view;
|
|
@@ -450,6 +775,7 @@ function augmentRelationArray(members, rel, paginator, ctx) {
|
|
|
450
775
|
const links = rel.links;
|
|
451
776
|
defineGetter(arr, "$links", () => links);
|
|
452
777
|
defineGetter(arr, "$meta", () => rel.meta);
|
|
778
|
+
defineGetter(arr, "$count", () => relationTotal(rel));
|
|
453
779
|
attachPage(arr, paginator, pageMeta(rel.meta), links, ctx, false);
|
|
454
780
|
return arr;
|
|
455
781
|
}
|
|
@@ -520,192 +846,6 @@ function relatedPaginatorKind(relation, ctx) {
|
|
|
520
846
|
return resolvePaginator(relatedPaginator(relation, ctx)).kind;
|
|
521
847
|
}
|
|
522
848
|
//#endregion
|
|
523
|
-
//#region src/types.ts
|
|
524
|
-
/** The JSON:API media type. */
|
|
525
|
-
const JSON_API_MEDIA_TYPE = "application/vnd.api+json";
|
|
526
|
-
/** The Atomic Operations extension URI. */
|
|
527
|
-
const ATOMIC_EXT = "https://jsonapi.org/ext/atomic";
|
|
528
|
-
/**
|
|
529
|
-
* Compose the JSON:API media type with any opted-in `ext`/`profile` parameters. Each parameter
|
|
530
|
-
* is a space-joined, double-quoted URI list, in the canonical order `ext` then `profile` so the
|
|
531
|
-
* output is deterministic (stable for caching/assertions). Empty/absent lists are omitted; with
|
|
532
|
-
* neither, the bare {@link JSON_API_MEDIA_TYPE} is returned (no behaviour change for a plain
|
|
533
|
-
* request). Used for both `Accept` and (when a body is present) `Content-Type`.
|
|
534
|
-
*/
|
|
535
|
-
function mediaType(params = {}) {
|
|
536
|
-
let out = JSON_API_MEDIA_TYPE;
|
|
537
|
-
if (params.ext !== void 0 && params.ext.length > 0) out += `; ext="${params.ext.join(" ")}"`;
|
|
538
|
-
if (params.profiles !== void 0 && params.profiles.length > 0) out += `; profile="${params.profiles.join(" ")}"`;
|
|
539
|
-
return out;
|
|
540
|
-
}
|
|
541
|
-
/**
|
|
542
|
-
* The media type for an Atomic Operations request/response: the JSON:API media type carrying
|
|
543
|
-
* the atomic `ext` parameter. Sent as both `Content-Type` and `Accept` on a `client.atomic`
|
|
544
|
-
* batch (per the JSON:API atomic extension).
|
|
545
|
-
*/
|
|
546
|
-
const ATOMIC_MEDIA_TYPE = mediaType({ ext: [ATOMIC_EXT] });
|
|
547
|
-
//#endregion
|
|
548
|
-
//#region src/request.ts
|
|
549
|
-
const isAbsolute = (path) => /^https?:\/\//i.test(path);
|
|
550
|
-
const RELATIVE_ORIGIN = "http://relative.invalid";
|
|
551
|
-
/**
|
|
552
|
-
* Resolve a server link against `baseUrl` per RFC 3986 and check where it lands. A link on the
|
|
553
|
-
* base's origin is followed; a relative base (e.g. `/api`) takes the page's origin in a browser and
|
|
554
|
-
* otherwise only accepts a link that keeps the host. Anything that isn't plain http(s) is refused.
|
|
555
|
-
*/
|
|
556
|
-
function resolveLink(link, baseUrl) {
|
|
557
|
-
let normalised = link.replace(/[\t\n\r]/g, "");
|
|
558
|
-
let start = 0;
|
|
559
|
-
while (start < normalised.length && normalised.charCodeAt(start) <= 32) start++;
|
|
560
|
-
normalised = normalised.slice(start);
|
|
561
|
-
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalised)?.[1]?.toLowerCase();
|
|
562
|
-
if (scheme !== void 0 && scheme !== "http" && scheme !== "https") throw new Error(`Refusing to follow link "${link}": only http(s) links are followed`);
|
|
563
|
-
const relativeBase = !isAbsolute(baseUrl);
|
|
564
|
-
const page = globalThis.location?.href;
|
|
565
|
-
const base = new URL(baseUrl, relativeBase ? typeof page === "string" ? page : RELATIVE_ORIGIN : void 0);
|
|
566
|
-
const resolved = new URL(link, base);
|
|
567
|
-
const sameOrigin = resolved.origin === base.origin && (scheme === void 0 || /^https?:\/\//i.test(normalised));
|
|
568
|
-
if (!sameOrigin) return {
|
|
569
|
-
url: resolved.href,
|
|
570
|
-
sameOrigin
|
|
571
|
-
};
|
|
572
|
-
return {
|
|
573
|
-
url: relativeBase ? resolved.pathname + resolved.search + resolved.hash : resolved.href,
|
|
574
|
-
sameOrigin
|
|
575
|
-
};
|
|
576
|
-
}
|
|
577
|
-
const append = (parts, key, value) => {
|
|
578
|
-
if (value === void 0 || value === null || value === "") return;
|
|
579
|
-
parts.push(`${key}=${encodeURIComponent(String(value))}`);
|
|
580
|
-
};
|
|
581
|
-
const isPlainObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
582
|
-
/**
|
|
583
|
-
* Append a filter value under its (already-bracketed) key. A plain object is a STRUCTURED filter
|
|
584
|
-
* value — a `Range`/`DateRange` deepObject (`{ min, max }`) — and recurses into nested bracketed
|
|
585
|
-
* keys (`filter[k][min]=`), matching the server's deepObject wire shape; an array goes out once per
|
|
586
|
-
* member as `filter[k][]=` for a filter that takes a list, so a member may hold a comma, and joins
|
|
587
|
-
* with `,` otherwise; a scalar is appended directly. Without the object branch a `{ min, max }` value would reach the
|
|
588
|
-
* wire as `filter[k]=[object Object]` and be silently ignored by the server.
|
|
589
|
-
*/
|
|
590
|
-
const appendFilterValue = (parts, key, value, list = false) => {
|
|
591
|
-
if (isPlainObject$1(value)) {
|
|
592
|
-
for (const [subKey, subValue] of Object.entries(value)) appendFilterValue(parts, `${key}[${subKey}]`, subValue);
|
|
593
|
-
return;
|
|
594
|
-
}
|
|
595
|
-
if (list && Array.isArray(value)) {
|
|
596
|
-
for (const member of value) append(parts, `${key}[]`, member);
|
|
597
|
-
return;
|
|
598
|
-
}
|
|
599
|
-
append(parts, key, Array.isArray(value) ? value.join(",") : value);
|
|
600
|
-
};
|
|
601
|
-
/**
|
|
602
|
-
* Serialise a read query to a query string (no leading `?`). Bracketed keys
|
|
603
|
-
* (`filter[title]`, `page[number]`, `fields[albums]`) are kept literal; only values
|
|
604
|
-
* are percent-encoded. `isListFilter` names the filter keys that take a list, whose array value
|
|
605
|
-
* goes out as `filter[<key>][]` once per member. Empty/undefined entries are skipped; key order is deterministic
|
|
606
|
-
* (family order, then insertion order within a family) so URLs are stable for caching.
|
|
607
|
-
*/
|
|
608
|
-
function serializeQuery(query, isListFilter) {
|
|
609
|
-
const parts = [];
|
|
610
|
-
if (query.filter) for (const [key, value] of Object.entries(query.filter)) appendFilterValue(parts, `filter[${key}]`, value, isListFilter?.(key) ?? false);
|
|
611
|
-
if (query.sort !== void 0) append(parts, "sort", Array.isArray(query.sort) ? query.sort.join(",") : query.sort);
|
|
612
|
-
if (query.include) append(parts, "include", query.include.join(","));
|
|
613
|
-
if (query.fields) for (const [type, names] of Object.entries(query.fields)) parts.push(`fields[${type}]=${encodeURIComponent(names.join(","))}`);
|
|
614
|
-
if (query.withCount && query.withCount.length > 0) append(parts, "withCount", query.withCount.join(","));
|
|
615
|
-
if (query.page) for (const [key, value] of Object.entries(query.page)) append(parts, `page[${key}]`, Array.isArray(value) ? value.join(",") : value);
|
|
616
|
-
return parts.join("&");
|
|
617
|
-
}
|
|
618
|
-
/**
|
|
619
|
-
* Execute a request: build the URL (a server link resolved against `baseUrl` and held to its
|
|
620
|
-
* origin, an absolute path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request headers,
|
|
621
|
-
* then drive the transport. A 2xx with a body parses to a {@link Document}; an empty /
|
|
622
|
-
* 204 body resolves to `undefined`. A non-2xx throws a {@link JsonApiError} carrying the
|
|
623
|
-
* parsed error objects (tolerating a non-JSON error body with an empty list).
|
|
624
|
-
*/
|
|
625
|
-
async function execute(ctx, req) {
|
|
626
|
-
return parseDocument((await send(ctx, req)).body);
|
|
627
|
-
}
|
|
628
|
-
async function executeRaw(ctx, req, as) {
|
|
629
|
-
const res = await send(ctx, req, as === "text" ? void 0 : as);
|
|
630
|
-
if (as === "text") return res.body === "" ? void 0 : res.body;
|
|
631
|
-
if (res.status === 204) return;
|
|
632
|
-
if (res.binary === void 0) throw new Error("The transport returned no binary body for a request that asked for one; a custom transport must read the response as binary when the request sets responseType.");
|
|
633
|
-
return res.binary;
|
|
634
|
-
}
|
|
635
|
-
/**
|
|
636
|
-
* Build the URL (a server link resolved against `baseUrl` and held to its origin, an absolute
|
|
637
|
-
* path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request
|
|
638
|
-
* headers, then drive the transport. A non-2xx throws a {@link JsonApiError} carrying the parsed
|
|
639
|
-
* error objects (tolerating a non-JSON error body with an empty list).
|
|
640
|
-
*/
|
|
641
|
-
async function send(ctx, req, responseType) {
|
|
642
|
-
let url;
|
|
643
|
-
let sendHeaders = true;
|
|
644
|
-
if (req.link) {
|
|
645
|
-
const link = resolveLink(req.path, ctx.baseUrl);
|
|
646
|
-
if (!link.sameOrigin && ctx.allowCrossOriginLinks !== true) throw new Error(`Refusing to follow link "${req.path}": it leaves the base URL's origin (set allowCrossOriginLinks to follow it without the configured headers)`);
|
|
647
|
-
url = link.url;
|
|
648
|
-
sendHeaders = link.sameOrigin;
|
|
649
|
-
} else url = isAbsolute(req.path) ? req.path : ctx.baseUrl + req.path;
|
|
650
|
-
if (req.query) {
|
|
651
|
-
const qs = serializeQuery(req.query, req.listFilter);
|
|
652
|
-
if (qs) url += (url.includes("?") ? "&" : "?") + qs;
|
|
653
|
-
}
|
|
654
|
-
const negotiated = mediaType({
|
|
655
|
-
ext: req.ext,
|
|
656
|
-
profiles: req.profiles
|
|
657
|
-
});
|
|
658
|
-
const headers = { Accept: req.accept ?? negotiated };
|
|
659
|
-
const transportReq = {
|
|
660
|
-
method: req.method,
|
|
661
|
-
url,
|
|
662
|
-
headers
|
|
663
|
-
};
|
|
664
|
-
if (req.signal !== void 0) transportReq.signal = req.signal;
|
|
665
|
-
if (responseType !== void 0) transportReq.responseType = responseType;
|
|
666
|
-
if (req.body !== void 0 || req.method.toUpperCase() === "POST") {
|
|
667
|
-
const contentType = req.contentType === void 0 ? negotiated : req.contentType;
|
|
668
|
-
if (contentType !== null) headers["Content-Type"] = contentType;
|
|
669
|
-
}
|
|
670
|
-
if (typeof req.body === "string" && req.raw) transportReq.body = req.body;
|
|
671
|
-
else if (req.raw && isRawBody(req.body)) transportReq.rawBody = req.body;
|
|
672
|
-
else if (req.body !== void 0) transportReq.body = JSON.stringify(req.body);
|
|
673
|
-
if (ctx.headers && sendHeaders) mergeHeaders(headers, await ctx.headers());
|
|
674
|
-
const res = await ctx.transport(transportReq);
|
|
675
|
-
if (res.status >= 200 && res.status < 300) return res;
|
|
676
|
-
throw new JsonApiError(res.status, parseErrors(res.body));
|
|
677
|
-
}
|
|
678
|
-
/** Whether a raw body goes to the transport as is rather than through `JSON.stringify`. */
|
|
679
|
-
function isRawBody(body) {
|
|
680
|
-
return typeof Blob !== "undefined" && body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof FormData !== "undefined" && body instanceof FormData || typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams;
|
|
681
|
-
}
|
|
682
|
-
/**
|
|
683
|
-
* Merge a `HeadersInit` (object / tuple array / `Headers`) into the outgoing map,
|
|
684
|
-
* preserving the caller's casing (unlike the WHATWG `Headers`, which lowercases). The
|
|
685
|
-
* caller's headers override the runtime defaults, so per-request `Accept` etc. can win.
|
|
686
|
-
*/
|
|
687
|
-
function mergeHeaders(into, extra) {
|
|
688
|
-
if (extra instanceof Headers) extra.forEach((value, key) => {
|
|
689
|
-
into[key] = value;
|
|
690
|
-
});
|
|
691
|
-
else if (Array.isArray(extra)) {
|
|
692
|
-
for (const [key, value] of extra) if (key !== void 0 && value !== void 0) into[key] = String(value);
|
|
693
|
-
} else for (const [key, value] of Object.entries(extra)) into[key] = String(value);
|
|
694
|
-
}
|
|
695
|
-
function parseDocument(body) {
|
|
696
|
-
if (body === "") return;
|
|
697
|
-
return JSON.parse(body);
|
|
698
|
-
}
|
|
699
|
-
function parseErrors(body) {
|
|
700
|
-
if (body === "") return [];
|
|
701
|
-
try {
|
|
702
|
-
const doc = JSON.parse(body);
|
|
703
|
-
return Array.isArray(doc.errors) ? doc.errors : [];
|
|
704
|
-
} catch {
|
|
705
|
-
return [];
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
//#endregion
|
|
709
849
|
//#region src/serialize-write.ts
|
|
710
850
|
/** Per-edge writable pivot data, supplied on a to-many member as the `$pivot` key. */
|
|
711
851
|
const PIVOT_KEY = "$pivot";
|
|
@@ -1193,6 +1333,7 @@ async function run(ctx, type, operation, vars, query, linkage = false, relationF
|
|
|
1193
1333
|
req.query = params;
|
|
1194
1334
|
const listFilter = listFilterMatcher(filterSpec(ctx, type, operation, vars["rel"]));
|
|
1195
1335
|
if (listFilter !== void 0) req.listFilter = listFilter;
|
|
1336
|
+
if (params.relatedQuery !== void 0) req.relatedListFilter = relatedListFilter(ctx, type);
|
|
1196
1337
|
if (signal !== void 0) req.signal = signal;
|
|
1197
1338
|
negotiateProfiles(ctx, type, params, req, relationForCount);
|
|
1198
1339
|
}
|
|
@@ -1216,15 +1357,51 @@ function filterSpec(ctx, type, operation, rel) {
|
|
|
1216
1357
|
return types?.length === 1 ? ctx.descriptor[types[0]] : void 0;
|
|
1217
1358
|
}
|
|
1218
1359
|
/**
|
|
1360
|
+
* Whether a `relatedQuery` entry's filter key takes a list, matched against the vocabulary of the
|
|
1361
|
+
* relation its include path ends on, as that relation's related read matches it. A path through a
|
|
1362
|
+
* polymorphic relation continues from the first member type declaring the next relation.
|
|
1363
|
+
*/
|
|
1364
|
+
function relatedListFilter(ctx, type) {
|
|
1365
|
+
const matchers = /* @__PURE__ */ new Map();
|
|
1366
|
+
return (path, key) => {
|
|
1367
|
+
if (!matchers.has(path)) matchers.set(path, listFilterMatcher(relatedQuerySpec(ctx, type, path)));
|
|
1368
|
+
return matchers.get(path)?.(key) ?? false;
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
/** The filter vocabulary of the relation an include path from `type` ends on. */
|
|
1372
|
+
function relatedQuerySpec(ctx, type, path) {
|
|
1373
|
+
const names = path.split(".");
|
|
1374
|
+
let owners = [type];
|
|
1375
|
+
for (const [index, name] of names.entries()) {
|
|
1376
|
+
const owner = owners.find((t) => ctx.descriptor[t]?.relations[name] !== void 0);
|
|
1377
|
+
if (owner === void 0) return;
|
|
1378
|
+
if (index === names.length - 1) return filterSpec(ctx, owner, "fetchRelated", name);
|
|
1379
|
+
owners = ctx.descriptor[owner].relations[name].types;
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
/** Whether a `relatedQuery` carries a filter or sort for any path, so it reaches the wire. */
|
|
1383
|
+
function sendsRelatedQuery(relatedQuery) {
|
|
1384
|
+
return Object.values(relatedQuery ?? {}).some((entry) => Object.keys(entry?.filter ?? {}).length > 0 || entry?.sort !== void 0 && entry.sort.length > 0);
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1219
1387
|
* Add any profiles a query's parameters require to the request's negotiated `profiles`. A
|
|
1220
1388
|
* `withCount` read needs the type's Countable profile in `Accept` — else the server rejects it
|
|
1221
1389
|
* (400) under strict query-param validation. The profile URI is read from the descriptor's
|
|
1222
|
-
* `countable` block (never hardcoded); absent when the type advertises no Countable profile.
|
|
1390
|
+
* `countable` block (never hardcoded); absent when the type advertises no Countable profile. A
|
|
1391
|
+
* `relatedQuery` on a collection or single read likewise adds the type's Relationship Queries
|
|
1392
|
+
* profile, after any Countable one.
|
|
1223
1393
|
*/
|
|
1224
1394
|
function negotiateProfiles(ctx, type, query, req, relationForCount) {
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1395
|
+
const profiles = [];
|
|
1396
|
+
if (query.withCount !== void 0 && query.withCount.length > 0) {
|
|
1397
|
+
const profile = relationForCount !== void 0 ? ctx.descriptor[type]?.relations[relationForCount]?.countable?.profile : ctx.descriptor[type]?.countable?.profile;
|
|
1398
|
+
if (profile !== void 0) profiles.push(profile);
|
|
1399
|
+
}
|
|
1400
|
+
if (relationForCount === void 0 && sendsRelatedQuery(query.relatedQuery)) {
|
|
1401
|
+
const profile = ctx.descriptor[type]?.relatedQuery?.profile;
|
|
1402
|
+
if (profile !== void 0 && !profiles.includes(profile)) profiles.push(profile);
|
|
1403
|
+
}
|
|
1404
|
+
if (profiles.length > 0) req.profiles = [...req.profiles ?? [], ...profiles];
|
|
1228
1405
|
}
|
|
1229
1406
|
/** Project a write's opts to the read-query families the response honours (`include`/`fields`). */
|
|
1230
1407
|
function writeQuery(opts) {
|
|
@@ -1238,10 +1415,27 @@ function writeQuery(opts) {
|
|
|
1238
1415
|
}
|
|
1239
1416
|
return Object.keys(query).length > 0 ? query : void 0;
|
|
1240
1417
|
}
|
|
1418
|
+
/** The poll options a call's `wait` asks for, or `undefined` when it doesn't wait. */
|
|
1419
|
+
const waitOptions = (wait) => wait === true ? {} : wait === false ? void 0 : wait;
|
|
1420
|
+
/**
|
|
1421
|
+
* Answer a `202` the operation declares with an `Accepted`, or with its result when the caller
|
|
1422
|
+
* waits. The job is materialised, or is the top-level `meta` of a meta-only document; `complete`
|
|
1423
|
+
* shapes the document the job URL finally answers with, as the operation shapes its own.
|
|
1424
|
+
*/
|
|
1425
|
+
function answerAccepted(ctx, accepted, res, complete, wait) {
|
|
1426
|
+
const value = toAccepted({
|
|
1427
|
+
request: ctx.request,
|
|
1428
|
+
jobType: accepted.jobType,
|
|
1429
|
+
job: (doc) => doc === void 0 || !("data" in doc) ? doc?.meta ?? {} : materialise(doc, ctx.materialise),
|
|
1430
|
+
complete
|
|
1431
|
+
}, res);
|
|
1432
|
+
return wait === void 0 ? value : value.$poll(wait);
|
|
1433
|
+
}
|
|
1241
1434
|
/**
|
|
1242
1435
|
* Drive a write: fill the path template, attach the body (and any `include`/`fields` query),
|
|
1243
1436
|
* execute, and materialise the response (`undefined` for a `204`/no body — so create/update
|
|
1244
|
-
* return the resource and delete/`204` relationship mutations resolve `undefined`/`void`).
|
|
1437
|
+
* return the resource and delete/`204` relationship mutations resolve `undefined`/`void`). A
|
|
1438
|
+
* `202` the write declares resolves to an `Accepted` job, or with `wait` to the polled result.
|
|
1245
1439
|
* On a thrown {@link JsonApiError}, each error's flat `path` is populated (via `spec.remap`)
|
|
1246
1440
|
* before it propagates, so a caller's `byPath()` keys are the flat input shape.
|
|
1247
1441
|
*/
|
|
@@ -1254,14 +1448,17 @@ async function runWrite(ctx, spec) {
|
|
|
1254
1448
|
body: spec.body
|
|
1255
1449
|
};
|
|
1256
1450
|
if (spec.query !== void 0) req.query = spec.query;
|
|
1257
|
-
|
|
1451
|
+
if (spec.wait?.signal !== void 0) req.signal = spec.wait.signal;
|
|
1452
|
+
let res;
|
|
1258
1453
|
try {
|
|
1259
|
-
|
|
1454
|
+
res = await executeResponse(ctx.request, req);
|
|
1260
1455
|
} catch (error) {
|
|
1261
1456
|
if (error instanceof JsonApiError) throw spec.remap(error);
|
|
1262
1457
|
throw error;
|
|
1263
1458
|
}
|
|
1264
|
-
|
|
1459
|
+
const complete = (doc) => doc === void 0 ? void 0 : materialise(doc, ctx.materialise, spec.linkage ?? false);
|
|
1460
|
+
if (res.status === 202 && spec.accepted !== void 0) return answerAccepted(ctx, spec.accepted, res, complete, spec.wait);
|
|
1461
|
+
return complete(res.document);
|
|
1265
1462
|
}
|
|
1266
1463
|
/**
|
|
1267
1464
|
* Invoke a custom action over its declared HTTP method (`action.method`, default `POST`) at its
|
|
@@ -1284,7 +1481,8 @@ async function runWrite(ctx, spec) {
|
|
|
1284
1481
|
* `ActionLocation` and never follows it. An action declaring `rawOutput` answers in the media type
|
|
1285
1482
|
* the caller picks with `options.accept`: JSON:API as above, or a `string`, a `Blob` or
|
|
1286
1483
|
* `ArrayBuffer`, or parsed JSON by the media type's kind. A collection action that takes filters
|
|
1287
|
-
* sends `options.filter` in the query string as a collection read does.
|
|
1484
|
+
* sends `options.filter` in the query string as a collection read does. A `202` the action
|
|
1485
|
+
* declares resolves to an `Accepted` job, or with `options.wait` to the value its job URL ends at.
|
|
1288
1486
|
*/
|
|
1289
1487
|
async function runAction(ctx, action, vars, input, options = {}) {
|
|
1290
1488
|
const req = {
|
|
@@ -1321,20 +1519,33 @@ async function runAction(ctx, action, vars, input, options = {}) {
|
|
|
1321
1519
|
const text = await executeRaw(ctx.request, req, "text");
|
|
1322
1520
|
return raw.kind === "json" && text !== void 0 ? JSON.parse(text) : text;
|
|
1323
1521
|
}
|
|
1324
|
-
const
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1522
|
+
const res = await executeResponse(ctx.request, req);
|
|
1523
|
+
const complete = (doc) => actionValue(ctx, action, doc);
|
|
1524
|
+
if (res.status === 202 && action.accepted !== void 0) {
|
|
1525
|
+
const wait = waitOptions(options.wait);
|
|
1526
|
+
const signal = wait?.signal ?? options.signal;
|
|
1527
|
+
return answerAccepted(ctx, action.accepted, res, complete, wait === void 0 || signal === void 0 ? wait : {
|
|
1528
|
+
...wait,
|
|
1529
|
+
signal
|
|
1530
|
+
});
|
|
1329
1531
|
}
|
|
1330
|
-
|
|
1331
|
-
if (action.output === "meta") return doc.meta;
|
|
1332
|
-
return materialise(doc, ctx.materialise);
|
|
1532
|
+
return complete(res.document);
|
|
1333
1533
|
} catch (error) {
|
|
1334
1534
|
if (remap !== void 0 && error instanceof JsonApiError) throw remap(error);
|
|
1335
1535
|
throw error;
|
|
1336
1536
|
}
|
|
1337
1537
|
}
|
|
1538
|
+
/** Shape an action's JSON:API answer by its declared `output`, or its `location`. */
|
|
1539
|
+
function actionValue(ctx, action, doc) {
|
|
1540
|
+
if (action.location !== void 0) {
|
|
1541
|
+
const location = doc === void 0 ? void 0 : readActionLocation(doc, action.location);
|
|
1542
|
+
if (location !== void 0) return location;
|
|
1543
|
+
if (action.output === "location") throw new Error("The action answered without the location document it declares.");
|
|
1544
|
+
}
|
|
1545
|
+
if (action.output === "none" || action.output === "location" || doc === void 0) return;
|
|
1546
|
+
if (action.output === "meta") return doc.meta;
|
|
1547
|
+
return materialise(doc, ctx.materialise);
|
|
1548
|
+
}
|
|
1338
1549
|
/**
|
|
1339
1550
|
* The request media type an action with several (`inputMedia`) sends: the caller's pick, matched
|
|
1340
1551
|
* exactly or through a declared wildcard such as `image/*`, else JSON:API when listed, else the
|
|
@@ -1510,7 +1721,9 @@ function resourceHandle(ctx, type, id) {
|
|
|
1510
1721
|
method: "PATCH",
|
|
1511
1722
|
body: toDocument(ctx.descriptor, type, patch, { id }),
|
|
1512
1723
|
query: writeQuery(opts),
|
|
1513
|
-
remap: (error) => withRemappedPaths(error, ctx.descriptor, type)
|
|
1724
|
+
remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
|
|
1725
|
+
accepted: ctx.descriptor[type]?.accepted?.update,
|
|
1726
|
+
wait: waitOptions(opts?.wait)
|
|
1514
1727
|
}),
|
|
1515
1728
|
delete: () => runWrite(ctx, {
|
|
1516
1729
|
type,
|
|
@@ -1540,7 +1753,9 @@ function typeAccessor(ctx, type) {
|
|
|
1540
1753
|
method: "POST",
|
|
1541
1754
|
body: toDocument(ctx.descriptor, type, input),
|
|
1542
1755
|
query: writeQuery(opts),
|
|
1543
|
-
remap: (error) => withRemappedPaths(error, ctx.descriptor, type)
|
|
1756
|
+
remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
|
|
1757
|
+
accepted: ctx.descriptor[type]?.accepted?.create,
|
|
1758
|
+
wait: waitOptions(opts?.wait)
|
|
1544
1759
|
}),
|
|
1545
1760
|
id: (id) => resourceHandle(ctx, type, id),
|
|
1546
1761
|
actions: actionsAccessor(ctx, type, "collection", {})
|
|
@@ -1616,19 +1831,23 @@ exports.CANONICAL_PAGE_KEYS = CANONICAL_PAGE_KEYS;
|
|
|
1616
1831
|
exports.HANDLE_RESERVED = HANDLE_RESERVED;
|
|
1617
1832
|
exports.JSON_API_MEDIA_TYPE = JSON_API_MEDIA_TYPE;
|
|
1618
1833
|
exports.JsonApiError = JsonApiError;
|
|
1834
|
+
exports.PollTimeoutError = PollTimeoutError;
|
|
1619
1835
|
exports.StructuralGuardError = StructuralGuardError;
|
|
1620
1836
|
exports.assertJsonApiDocument = assertJsonApiDocument;
|
|
1621
1837
|
exports.createClient = createClient;
|
|
1622
1838
|
exports.execute = execute;
|
|
1623
1839
|
exports.executeRaw = executeRaw;
|
|
1840
|
+
exports.executeResponse = executeResponse;
|
|
1624
1841
|
exports.fetchTransport = fetchTransport;
|
|
1625
1842
|
exports.findError = findError;
|
|
1626
1843
|
exports.hasErrorCode = hasErrorCode;
|
|
1844
|
+
exports.isAccepted = isAccepted;
|
|
1627
1845
|
exports.isActionLocation = isActionLocation;
|
|
1628
1846
|
exports.isPolymorphic = isPolymorphic;
|
|
1629
1847
|
exports.listFilterMatcher = listFilterMatcher;
|
|
1630
1848
|
exports.materialise = materialise;
|
|
1631
1849
|
exports.mediaType = mediaType;
|
|
1850
|
+
exports.parseRetryAfter = parseRetryAfter;
|
|
1632
1851
|
exports.readActionLocation = readActionLocation;
|
|
1633
1852
|
exports.relatedPaginator = relatedPaginator;
|
|
1634
1853
|
exports.relatedPaginatorKind = relatedPaginatorKind;
|