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