@haddowg/json-api-client 1.17.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/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 = {
@@ -528,197 +846,6 @@ function relatedPaginatorKind(relation, ctx) {
528
846
  return resolvePaginator(relatedPaginator(relation, ctx)).kind;
529
847
  }
530
848
  //#endregion
531
- //#region src/types.ts
532
- /** The JSON:API media type. */
533
- const JSON_API_MEDIA_TYPE = "application/vnd.api+json";
534
- /** The Atomic Operations extension URI. */
535
- const ATOMIC_EXT = "https://jsonapi.org/ext/atomic";
536
- /**
537
- * Compose the JSON:API media type with any opted-in `ext`/`profile` parameters. Each parameter
538
- * is a space-joined, double-quoted URI list, in the canonical order `ext` then `profile` so the
539
- * output is deterministic (stable for caching/assertions). Empty/absent lists are omitted; with
540
- * neither, the bare {@link JSON_API_MEDIA_TYPE} is returned (no behaviour change for a plain
541
- * request). Used for both `Accept` and (when a body is present) `Content-Type`.
542
- */
543
- function mediaType(params = {}) {
544
- let out = JSON_API_MEDIA_TYPE;
545
- if (params.ext !== void 0 && params.ext.length > 0) out += `; ext="${params.ext.join(" ")}"`;
546
- if (params.profiles !== void 0 && params.profiles.length > 0) out += `; profile="${params.profiles.join(" ")}"`;
547
- return out;
548
- }
549
- /**
550
- * The media type for an Atomic Operations request/response: the JSON:API media type carrying
551
- * the atomic `ext` parameter. Sent as both `Content-Type` and `Accept` on a `client.atomic`
552
- * batch (per the JSON:API atomic extension).
553
- */
554
- const ATOMIC_MEDIA_TYPE = mediaType({ ext: [ATOMIC_EXT] });
555
- //#endregion
556
- //#region src/request.ts
557
- const isAbsolute = (path) => /^https?:\/\//i.test(path);
558
- const RELATIVE_ORIGIN = "http://relative.invalid";
559
- /**
560
- * Resolve a server link against `baseUrl` per RFC 3986 and check where it lands. A link on the
561
- * base's origin is followed; a relative base (e.g. `/api`) takes the page's origin in a browser and
562
- * otherwise only accepts a link that keeps the host. Anything that isn't plain http(s) is refused.
563
- */
564
- function resolveLink(link, baseUrl) {
565
- let normalised = link.replace(/[\t\n\r]/g, "");
566
- let start = 0;
567
- while (start < normalised.length && normalised.charCodeAt(start) <= 32) start++;
568
- normalised = normalised.slice(start);
569
- const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalised)?.[1]?.toLowerCase();
570
- if (scheme !== void 0 && scheme !== "http" && scheme !== "https") throw new Error(`Refusing to follow link "${link}": only http(s) links are followed`);
571
- const relativeBase = !isAbsolute(baseUrl);
572
- const page = globalThis.location?.href;
573
- const base = new URL(baseUrl, relativeBase ? typeof page === "string" ? page : RELATIVE_ORIGIN : void 0);
574
- const resolved = new URL(link, base);
575
- const sameOrigin = resolved.origin === base.origin && (scheme === void 0 || /^https?:\/\//i.test(normalised));
576
- if (!sameOrigin) return {
577
- url: resolved.href,
578
- sameOrigin
579
- };
580
- return {
581
- url: relativeBase ? resolved.pathname + resolved.search + resolved.hash : resolved.href,
582
- sameOrigin
583
- };
584
- }
585
- const append = (parts, key, value) => {
586
- if (value === void 0 || value === null || value === "") return;
587
- parts.push(`${key}=${encodeURIComponent(String(value))}`);
588
- };
589
- const isPlainObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
590
- /**
591
- * Append a filter value under its (already-bracketed) key. A plain object is a STRUCTURED filter
592
- * value — a `Range`/`DateRange` deepObject (`{ min, max }`) — and recurses into nested bracketed
593
- * keys (`filter[k][min]=`), matching the server's deepObject wire shape; an array goes out once per
594
- * member as `filter[k][]=` for a filter that takes a list, so a member may hold a comma, and joins
595
- * with `,` otherwise; a scalar is appended directly. Without the object branch a `{ min, max }` value would reach the
596
- * wire as `filter[k]=[object Object]` and be silently ignored by the server.
597
- */
598
- const appendFilterValue = (parts, key, value, list = false) => {
599
- if (isPlainObject$1(value)) {
600
- for (const [subKey, subValue] of Object.entries(value)) appendFilterValue(parts, `${key}[${subKey}]`, subValue);
601
- return;
602
- }
603
- if (list && Array.isArray(value)) {
604
- for (const member of value) append(parts, `${key}[]`, member);
605
- return;
606
- }
607
- append(parts, key, Array.isArray(value) ? value.join(",") : value);
608
- };
609
- /**
610
- * Serialise a read query to a query string (no leading `?`). Bracketed keys
611
- * (`filter[title]`, `page[number]`, `fields[albums]`) are kept literal; only values
612
- * are percent-encoded. `isListFilter` names the filter keys that take a list, whose array value
613
- * goes out as `filter[<key>][]` once per member, and `isRelatedListFilter` does the same for a
614
- * `relatedQuery` entry's filters by include path. Empty/undefined entries are skipped; key order is deterministic
615
- * (family order, then insertion order within a family) so URLs are stable for caching.
616
- */
617
- function serializeQuery(query, isListFilter, isRelatedListFilter) {
618
- const parts = [];
619
- if (query.filter) for (const [key, value] of Object.entries(query.filter)) appendFilterValue(parts, `filter[${key}]`, value, isListFilter?.(key) ?? false);
620
- if (query.sort !== void 0) append(parts, "sort", Array.isArray(query.sort) ? query.sort.join(",") : query.sort);
621
- if (query.include) append(parts, "include", query.include.join(","));
622
- if (query.fields) for (const [type, names] of Object.entries(query.fields)) parts.push(`fields[${type}]=${encodeURIComponent(names.join(","))}`);
623
- if (query.withCount && query.withCount.length > 0) append(parts, "withCount", query.withCount.join(","));
624
- for (const [path, entry] of Object.entries(query.relatedQuery ?? {})) {
625
- for (const [key, value] of Object.entries(entry?.filter ?? {})) appendFilterValue(parts, `relatedQuery[${path}][filter][${key}]`, value, isRelatedListFilter?.(path, key) ?? false);
626
- if (entry?.sort !== void 0) append(parts, `relatedQuery[${path}][sort]`, typeof entry.sort === "string" ? entry.sort : entry.sort.join(","));
627
- }
628
- if (query.page) for (const [key, value] of Object.entries(query.page)) append(parts, `page[${key}]`, Array.isArray(value) ? value.join(",") : value);
629
- return parts.join("&");
630
- }
631
- /**
632
- * Execute a request: build the URL (a server link resolved against `baseUrl` and held to its
633
- * origin, an absolute path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request headers,
634
- * then drive the transport. A 2xx with a body parses to a {@link Document}; an empty /
635
- * 204 body resolves to `undefined`. A non-2xx throws a {@link JsonApiError} carrying the
636
- * parsed error objects (tolerating a non-JSON error body with an empty list).
637
- */
638
- async function execute(ctx, req) {
639
- return parseDocument((await send(ctx, req)).body);
640
- }
641
- async function executeRaw(ctx, req, as) {
642
- const res = await send(ctx, req, as === "text" ? void 0 : as);
643
- if (as === "text") return res.body === "" ? void 0 : res.body;
644
- if (res.status === 204) return;
645
- 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.");
646
- return res.binary;
647
- }
648
- /**
649
- * Build the URL (a server link resolved against `baseUrl` and held to its origin, an absolute
650
- * path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request
651
- * headers, then drive the transport. A non-2xx throws a {@link JsonApiError} carrying the parsed
652
- * error objects (tolerating a non-JSON error body with an empty list).
653
- */
654
- async function send(ctx, req, responseType) {
655
- let url;
656
- let sendHeaders = true;
657
- if (req.link) {
658
- const link = resolveLink(req.path, ctx.baseUrl);
659
- 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)`);
660
- url = link.url;
661
- sendHeaders = link.sameOrigin;
662
- } else url = isAbsolute(req.path) ? req.path : ctx.baseUrl + req.path;
663
- if (req.query) {
664
- const qs = serializeQuery(req.query, req.listFilter, req.relatedListFilter);
665
- if (qs) url += (url.includes("?") ? "&" : "?") + qs;
666
- }
667
- const negotiated = mediaType({
668
- ext: req.ext,
669
- profiles: req.profiles
670
- });
671
- const headers = { Accept: req.accept ?? negotiated };
672
- const transportReq = {
673
- method: req.method,
674
- url,
675
- headers
676
- };
677
- if (req.signal !== void 0) transportReq.signal = req.signal;
678
- if (responseType !== void 0) transportReq.responseType = responseType;
679
- if (req.body !== void 0 || req.method.toUpperCase() === "POST") {
680
- const contentType = req.contentType === void 0 ? negotiated : req.contentType;
681
- if (contentType !== null) headers["Content-Type"] = contentType;
682
- }
683
- if (typeof req.body === "string" && req.raw) transportReq.body = req.body;
684
- else if (req.raw && isRawBody(req.body)) transportReq.rawBody = req.body;
685
- else if (req.body !== void 0) transportReq.body = JSON.stringify(req.body);
686
- if (ctx.headers && sendHeaders) mergeHeaders(headers, await ctx.headers());
687
- const res = await ctx.transport(transportReq);
688
- if (res.status >= 200 && res.status < 300) return res;
689
- throw new JsonApiError(res.status, parseErrors(res.body));
690
- }
691
- /** Whether a raw body goes to the transport as is rather than through `JSON.stringify`. */
692
- function isRawBody(body) {
693
- 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;
694
- }
695
- /**
696
- * Merge a `HeadersInit` (object / tuple array / `Headers`) into the outgoing map,
697
- * preserving the caller's casing (unlike the WHATWG `Headers`, which lowercases). The
698
- * caller's headers override the runtime defaults, so per-request `Accept` etc. can win.
699
- */
700
- function mergeHeaders(into, extra) {
701
- if (extra instanceof Headers) extra.forEach((value, key) => {
702
- into[key] = value;
703
- });
704
- else if (Array.isArray(extra)) {
705
- for (const [key, value] of extra) if (key !== void 0 && value !== void 0) into[key] = String(value);
706
- } else for (const [key, value] of Object.entries(extra)) into[key] = String(value);
707
- }
708
- function parseDocument(body) {
709
- if (body === "") return;
710
- return JSON.parse(body);
711
- }
712
- function parseErrors(body) {
713
- if (body === "") return [];
714
- try {
715
- const doc = JSON.parse(body);
716
- return Array.isArray(doc.errors) ? doc.errors : [];
717
- } catch {
718
- return [];
719
- }
720
- }
721
- //#endregion
722
849
  //#region src/serialize-write.ts
723
850
  /** Per-edge writable pivot data, supplied on a to-many member as the `$pivot` key. */
724
851
  const PIVOT_KEY = "$pivot";
@@ -1288,10 +1415,27 @@ function writeQuery(opts) {
1288
1415
  }
1289
1416
  return Object.keys(query).length > 0 ? query : void 0;
1290
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
+ }
1291
1434
  /**
1292
1435
  * Drive a write: fill the path template, attach the body (and any `include`/`fields` query),
1293
1436
  * execute, and materialise the response (`undefined` for a `204`/no body — so create/update
1294
- * 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.
1295
1439
  * On a thrown {@link JsonApiError}, each error's flat `path` is populated (via `spec.remap`)
1296
1440
  * before it propagates, so a caller's `byPath()` keys are the flat input shape.
1297
1441
  */
@@ -1304,14 +1448,17 @@ async function runWrite(ctx, spec) {
1304
1448
  body: spec.body
1305
1449
  };
1306
1450
  if (spec.query !== void 0) req.query = spec.query;
1307
- let doc;
1451
+ if (spec.wait?.signal !== void 0) req.signal = spec.wait.signal;
1452
+ let res;
1308
1453
  try {
1309
- doc = await execute(ctx.request, req);
1454
+ res = await executeResponse(ctx.request, req);
1310
1455
  } catch (error) {
1311
1456
  if (error instanceof JsonApiError) throw spec.remap(error);
1312
1457
  throw error;
1313
1458
  }
1314
- return doc === void 0 ? void 0 : materialise(doc, ctx.materialise, spec.linkage ?? false);
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);
1315
1462
  }
1316
1463
  /**
1317
1464
  * Invoke a custom action over its declared HTTP method (`action.method`, default `POST`) at its
@@ -1334,7 +1481,8 @@ async function runWrite(ctx, spec) {
1334
1481
  * `ActionLocation` and never follows it. An action declaring `rawOutput` answers in the media type
1335
1482
  * the caller picks with `options.accept`: JSON:API as above, or a `string`, a `Blob` or
1336
1483
  * `ArrayBuffer`, or parsed JSON by the media type's kind. A collection action that takes filters
1337
- * 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.
1338
1486
  */
1339
1487
  async function runAction(ctx, action, vars, input, options = {}) {
1340
1488
  const req = {
@@ -1371,20 +1519,33 @@ async function runAction(ctx, action, vars, input, options = {}) {
1371
1519
  const text = await executeRaw(ctx.request, req, "text");
1372
1520
  return raw.kind === "json" && text !== void 0 ? JSON.parse(text) : text;
1373
1521
  }
1374
- const doc = await execute(ctx.request, req);
1375
- if (action.location !== void 0) {
1376
- const location = doc === void 0 ? void 0 : readActionLocation(doc, action.location);
1377
- if (location !== void 0) return location;
1378
- if (action.output === "location") throw new Error("The action answered without the location document it declares.");
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
+ });
1379
1531
  }
1380
- if (action.output === "none" || action.output === "location" || doc === void 0) return;
1381
- if (action.output === "meta") return doc.meta;
1382
- return materialise(doc, ctx.materialise);
1532
+ return complete(res.document);
1383
1533
  } catch (error) {
1384
1534
  if (remap !== void 0 && error instanceof JsonApiError) throw remap(error);
1385
1535
  throw error;
1386
1536
  }
1387
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
+ }
1388
1549
  /**
1389
1550
  * The request media type an action with several (`inputMedia`) sends: the caller's pick, matched
1390
1551
  * exactly or through a declared wildcard such as `image/*`, else JSON:API when listed, else the
@@ -1560,7 +1721,9 @@ function resourceHandle(ctx, type, id) {
1560
1721
  method: "PATCH",
1561
1722
  body: toDocument(ctx.descriptor, type, patch, { id }),
1562
1723
  query: writeQuery(opts),
1563
- 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)
1564
1727
  }),
1565
1728
  delete: () => runWrite(ctx, {
1566
1729
  type,
@@ -1590,7 +1753,9 @@ function typeAccessor(ctx, type) {
1590
1753
  method: "POST",
1591
1754
  body: toDocument(ctx.descriptor, type, input),
1592
1755
  query: writeQuery(opts),
1593
- 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)
1594
1759
  }),
1595
1760
  id: (id) => resourceHandle(ctx, type, id),
1596
1761
  actions: actionsAccessor(ctx, type, "collection", {})
@@ -1666,19 +1831,23 @@ exports.CANONICAL_PAGE_KEYS = CANONICAL_PAGE_KEYS;
1666
1831
  exports.HANDLE_RESERVED = HANDLE_RESERVED;
1667
1832
  exports.JSON_API_MEDIA_TYPE = JSON_API_MEDIA_TYPE;
1668
1833
  exports.JsonApiError = JsonApiError;
1834
+ exports.PollTimeoutError = PollTimeoutError;
1669
1835
  exports.StructuralGuardError = StructuralGuardError;
1670
1836
  exports.assertJsonApiDocument = assertJsonApiDocument;
1671
1837
  exports.createClient = createClient;
1672
1838
  exports.execute = execute;
1673
1839
  exports.executeRaw = executeRaw;
1840
+ exports.executeResponse = executeResponse;
1674
1841
  exports.fetchTransport = fetchTransport;
1675
1842
  exports.findError = findError;
1676
1843
  exports.hasErrorCode = hasErrorCode;
1844
+ exports.isAccepted = isAccepted;
1677
1845
  exports.isActionLocation = isActionLocation;
1678
1846
  exports.isPolymorphic = isPolymorphic;
1679
1847
  exports.listFilterMatcher = listFilterMatcher;
1680
1848
  exports.materialise = materialise;
1681
1849
  exports.mediaType = mediaType;
1850
+ exports.parseRetryAfter = parseRetryAfter;
1682
1851
  exports.readActionLocation = readActionLocation;
1683
1852
  exports.relatedPaginator = relatedPaginator;
1684
1853
  exports.relatedPaginatorKind = relatedPaginatorKind;