@haddowg/json-api-client 1.21.0 → 1.23.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
@@ -183,7 +183,7 @@ const appendFilterValue = (parts, key, value, list = false) => {
183
183
  * (`filter[title]`, `page[number]`, `fields[albums]`) are kept literal; only values
184
184
  * are percent-encoded. `isListFilter` names the filter keys that take a list, whose array value
185
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
186
+ * `relatedQuery` entry's filters by relation. Empty/undefined entries are skipped; key order is deterministic
187
187
  * (family order, then insertion order within a family) so URLs are stable for caching.
188
188
  */
189
189
  function serializeQuery(query, isListFilter, isRelatedListFilter) {
@@ -193,9 +193,9 @@ function serializeQuery(query, isListFilter, isRelatedListFilter) {
193
193
  if (query.include) append(parts, "include", query.include.join(","));
194
194
  if (query.fields) for (const [type, names] of Object.entries(query.fields)) parts.push(`fields[${type}]=${encodeURIComponent(names.join(","))}`);
195
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(","));
196
+ for (const [relation, entry] of Object.entries(query.relatedQuery ?? {})) {
197
+ for (const [key, value] of Object.entries(entry?.filter ?? {})) appendFilterValue(parts, `relatedQuery[${relation}][filter][${key}]`, value, isRelatedListFilter?.(relation, key) ?? false);
198
+ if (entry?.sort !== void 0) append(parts, `relatedQuery[${relation}][sort]`, typeof entry.sort === "string" ? entry.sort : entry.sort.join(","));
199
199
  }
200
200
  if (query.page) for (const [key, value] of Object.entries(query.page)) append(parts, `page[${key}]`, Array.isArray(value) ? value.join(",") : value);
201
201
  return parts.join("&");
@@ -1198,6 +1198,15 @@ function parseResults(doc, ctx) {
1198
1198
  });
1199
1199
  }
1200
1200
  //#endregion
1201
+ //#region src/descriptor.ts
1202
+ /**
1203
+ * Whether a relation is polymorphic: flagged {@link RelationDescriptor.polymorphic}, or, when the
1204
+ * flag is absent, listing more than one related type.
1205
+ */
1206
+ function isPolymorphic(relation) {
1207
+ return relation.polymorphic ?? relation.types.length > 1;
1208
+ }
1209
+ //#endregion
1201
1210
  //#region src/filters.ts
1202
1211
  /**
1203
1212
  * Whether a `filter[...]` key takes a list, by the rule the server matches keys with: an exact
@@ -1332,9 +1341,9 @@ async function run(ctx, type, operation, vars, query, linkage = false, relationF
1332
1341
  req.query = params;
1333
1342
  const listFilter = listFilterMatcher(filterSpec(ctx, type, operation, vars["rel"]));
1334
1343
  if (listFilter !== void 0) req.listFilter = listFilter;
1335
- if (params.relatedQuery !== void 0) req.relatedListFilter = relatedListFilter(ctx, type);
1336
1344
  if (signal !== void 0) req.signal = signal;
1337
1345
  negotiateProfiles(ctx, type, params, req, relationForCount, operation);
1346
+ applyRelatedQuery(ctx, renderedType(ctx, type, operation, vars["rel"]), params, req);
1338
1347
  }
1339
1348
  const doc = await execute(ctx.request, req);
1340
1349
  const relation = (operation === "fetchRelated" || operation === "fetchRelationship") && vars["rel"] !== void 0 ? ctx.descriptor[type]?.relations[vars["rel"]] : void 0;
@@ -1356,40 +1365,41 @@ function filterSpec(ctx, type, operation, rel) {
1356
1365
  return types?.length === 1 ? ctx.descriptor[types[0]] : void 0;
1357
1366
  }
1358
1367
  /**
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.
1368
+ * The type whose resources an operation answers with, which keys its `relatedQuery`: the type
1369
+ * itself, or a related read's related type when the relation is monomorphic. A relationship read
1370
+ * answers with linkage, so it has none.
1362
1371
  */
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
- }
1372
+ function renderedType(ctx, type, operation, rel) {
1373
+ if (operation === "fetchRelationship") return;
1374
+ if (operation !== "fetchRelated") return type;
1375
+ const relation = rel === void 0 ? void 0 : ctx.descriptor[type]?.relations[rel];
1376
+ return relation === void 0 || isPolymorphic(relation) ? void 0 : relation.types[0];
1380
1377
  }
1381
- /** Whether a `relatedQuery` carries a filter or sort for any path, so it reaches the wire. */
1378
+ /** Whether a `relatedQuery` carries a filter or sort for any relation, so it reaches the wire. */
1382
1379
  function sendsRelatedQuery(relatedQuery) {
1383
1380
  return Object.values(relatedQuery ?? {}).some((entry) => Object.keys(entry?.filter ?? {}).length > 0 || entry?.sort !== void 0 && entry.sort.length > 0);
1384
1381
  }
1385
1382
  /**
1386
- * Add any profiles a query's parameters require to the request's negotiated `profiles`. A
1387
- * `withCount` read or write needs the Countable profile in `Accept`, else the server rejects it
1388
- * (400) under strict query-param validation. The profile URI is read from the descriptor (never
1383
+ * Prepare a request's `relatedQuery` for resources of type `rendered`: match each entry's list
1384
+ * filters against its relation's related-read vocabulary, and negotiate the type's Relationship
1385
+ * Queries profile, after any Countable one, when the query sends an entry.
1386
+ */
1387
+ function applyRelatedQuery(ctx, rendered, query, req) {
1388
+ if (rendered === void 0 || !sendsRelatedQuery(query.relatedQuery)) return;
1389
+ const matchers = /* @__PURE__ */ new Map();
1390
+ req.relatedListFilter = (rel, key) => {
1391
+ if (!matchers.has(rel)) matchers.set(rel, listFilterMatcher(filterSpec(ctx, rendered, "fetchRelated", rel)));
1392
+ return matchers.get(rel)?.(key) ?? false;
1393
+ };
1394
+ const profile = ctx.descriptor[rendered]?.relatedQuery?.profile;
1395
+ if (profile !== void 0 && !(req.profiles ?? []).includes(profile)) req.profiles = [...req.profiles ?? [], profile];
1396
+ }
1397
+ /**
1398
+ * Add the Countable profile a query's `withCount` requires to the request's negotiated
1399
+ * `profiles`. A `withCount` read or write needs it in `Accept`, else the server rejects it (400)
1400
+ * under strict query-param validation. The profile URI is read from the descriptor (never
1389
1401
  * hardcoded): the relation's `countable` for a related or relationship read, the operation's
1390
1402
  * `resourceCountable` entry for a single-resource read or a write, else the type's `countable`.
1391
- * A `relatedQuery` on a collection or single read likewise adds the type's Relationship Queries
1392
- * profile, after any Countable one.
1393
1403
  */
1394
1404
  function negotiateProfiles(ctx, type, query, req, relationForCount, operation) {
1395
1405
  const profiles = [];
@@ -1398,10 +1408,6 @@ function negotiateProfiles(ctx, type, query, req, relationForCount, operation) {
1398
1408
  const profile = relationForCount !== void 0 ? descriptor?.relations[relationForCount]?.countable?.profile : (isResourceCountOperation(operation) ? descriptor?.resourceCountable?.[operation]?.profile : void 0) ?? descriptor?.countable?.profile;
1399
1409
  if (profile !== void 0) profiles.push(profile);
1400
1410
  }
1401
- if (relationForCount === void 0 && sendsRelatedQuery(query.relatedQuery)) {
1402
- const profile = ctx.descriptor[type]?.relatedQuery?.profile;
1403
- if (profile !== void 0 && !profiles.includes(profile)) profiles.push(profile);
1404
- }
1405
1411
  if (profiles.length > 0) req.profiles = [...req.profiles ?? [], ...profiles];
1406
1412
  }
1407
1413
  /** Whether an operation is one answering with one resource that may take `withCount`. */
@@ -1409,14 +1415,15 @@ function isResourceCountOperation(operation) {
1409
1415
  return operation === "fetchOne" || operation === "create" || operation === "update";
1410
1416
  }
1411
1417
  /**
1412
- * Project a write's opts to the read-query families the response honours: `include`, `fields`
1413
- * and `withCount`.
1418
+ * Project a write's opts to the read-query families the response honours: `include`, `fields`,
1419
+ * `withCount` and `relatedQuery`.
1414
1420
  */
1415
1421
  function writeQuery(opts) {
1416
1422
  if (opts === void 0) return;
1417
1423
  const query = {};
1418
1424
  if (opts.include !== void 0) query.include = [...opts.include];
1419
1425
  if (opts.withCount !== void 0) query.withCount = [...opts.withCount];
1426
+ if (opts.relatedQuery !== void 0) query.relatedQuery = opts.relatedQuery;
1420
1427
  if (opts.fields !== void 0) {
1421
1428
  const fields = {};
1422
1429
  for (const [k, v] of Object.entries(opts.fields)) fields[k] = [...v];
@@ -1459,6 +1466,7 @@ async function runWrite(ctx, spec) {
1459
1466
  if (spec.query !== void 0) {
1460
1467
  req.query = spec.query;
1461
1468
  negotiateProfiles(ctx, spec.type, spec.query, req, void 0, spec.operation);
1469
+ applyRelatedQuery(ctx, spec.type, spec.query, req);
1462
1470
  if (req.profiles !== void 0) req.contentType = JSON_API_MEDIA_TYPE;
1463
1471
  }
1464
1472
  if (spec.wait?.signal !== void 0) req.signal = spec.wait.signal;
@@ -1494,7 +1502,8 @@ async function runWrite(ctx, spec) {
1494
1502
  * `ActionLocation` and never follows it. An action declaring `rawOutput` answers in the media type
1495
1503
  * the caller picks with `options.accept`: JSON:API as above, or a `string`, a `Blob` or
1496
1504
  * `ArrayBuffer`, or parsed JSON by the media type's kind. A collection action that takes filters
1497
- * sends `options.filter` in the query string as a collection read does. A `202` the action
1505
+ * sends `options.filter` in the query string as a collection read does, and an action answering
1506
+ * with a resource sends `options.relatedQuery` as a read does. A `202` the action
1498
1507
  * declares resolves to an `Accepted` job, or with `options.wait` to the value its job URL ends at.
1499
1508
  */
1500
1509
  async function runAction(ctx, action, vars, input, options = {}) {
@@ -1508,6 +1517,13 @@ async function runAction(ctx, action, vars, input, options = {}) {
1508
1517
  const listFilter = listFilterMatcher(action);
1509
1518
  if (listFilter !== void 0) req.listFilter = listFilter;
1510
1519
  }
1520
+ if (options.relatedQuery !== void 0) {
1521
+ req.query = {
1522
+ ...req.query,
1523
+ relatedQuery: options.relatedQuery
1524
+ };
1525
+ applyRelatedQuery(ctx, action.outputType, req.query, req);
1526
+ }
1511
1527
  let remap;
1512
1528
  const media = requestMedia(action, options.contentType);
1513
1529
  if (media !== void 0 && media.kind !== "document") {
@@ -1524,6 +1540,7 @@ async function runAction(ctx, action, vars, input, options = {}) {
1524
1540
  req.contentType = sentContentType(action.contentType ?? "*/*", void 0, req.body);
1525
1541
  req.raw = true;
1526
1542
  }
1543
+ if (req.profiles !== void 0 && req.contentType === void 0) req.contentType = JSON_API_MEDIA_TYPE;
1527
1544
  const raw = responseMedia(action, options.accept);
1528
1545
  try {
1529
1546
  if (raw !== void 0) {
@@ -1665,16 +1682,17 @@ function actionsAccessor(ctx, type, scope, vars) {
1665
1682
  return out;
1666
1683
  }
1667
1684
  /**
1668
- * Build the relationship accessor for `client.<type>.id(id).<rel>`: reads
1685
+ * Build the relationship accessor for `client.<type>.id(id).<rel>`, or a singleton's
1686
+ * `client.<type>.<rel>` with no `id` in `vars`: reads
1669
1687
  * (`.get()` linkage / `.related()` collection) plus mutations — to-many `.add` (POST) /
1670
1688
  * `.remove` (DELETE) / `.replace` (PATCH) and to-one `.set` (PATCH). Every mutation posts
1671
1689
  * a `{ data: <linkage> }` body to `fetchRelationship` and materialises the response as
1672
1690
  * linkage (or `undefined`/`void` for a `204`). The cardinality is read off the descriptor
1673
1691
  * so the linkage is coerced correctly; the static types gate which verb is callable.
1674
1692
  */
1675
- function relationshipAccessor(ctx, type, id, rel) {
1693
+ function relationshipAccessor(ctx, type, owner, rel) {
1676
1694
  const vars = {
1677
- id,
1695
+ ...owner,
1678
1696
  rel
1679
1697
  };
1680
1698
  const relation = ctx.descriptor[type]?.relations[rel];
@@ -1720,39 +1738,72 @@ const HANDLE_RESERVED = /* @__PURE__ */ new Set([
1720
1738
  "actions",
1721
1739
  "then"
1722
1740
  ]);
1741
+ /**
1742
+ * Run a type's update. `vars` fill its path (`{ id }`, or nothing for a singleton) and `id` is
1743
+ * the one the body carries.
1744
+ */
1745
+ function runUpdate(ctx, type, vars, id, patch, opts) {
1746
+ return runWrite(ctx, {
1747
+ type,
1748
+ operation: "update",
1749
+ vars,
1750
+ method: "PATCH",
1751
+ body: toDocument(ctx.descriptor, type, patch, { id }),
1752
+ query: writeQuery(opts),
1753
+ remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
1754
+ accepted: ctx.descriptor[type]?.accepted?.update,
1755
+ wait: waitOptions(opts?.wait)
1756
+ });
1757
+ }
1758
+ /**
1759
+ * Wrap a handle's verbs in a Proxy resolving each relation not shadowed by a reserved member to
1760
+ * its relationship accessor, addressed by `vars`.
1761
+ */
1762
+ function withRelations(ctx, type, vars, base) {
1763
+ const relations = ctx.descriptor[type]?.relations ?? {};
1764
+ return new Proxy(base, { get(target, prop, receiver) {
1765
+ if (typeof prop === "string" && !HANDLE_RESERVED.has(prop) && prop in relations) return relationshipAccessor(ctx, type, vars, prop);
1766
+ return Reflect.get(target, prop, receiver);
1767
+ } });
1768
+ }
1723
1769
  /** Build the id-scoped resource handle (a Proxy resolving relation accessors by name). */
1724
1770
  function resourceHandle(ctx, type, id) {
1725
- const relations = ctx.descriptor[type]?.relations ?? {};
1726
- const base = {
1771
+ const vars = { id };
1772
+ return withRelations(ctx, type, vars, {
1727
1773
  type,
1728
1774
  id,
1729
- get: (query) => run(ctx, type, "fetchOne", { id }, query),
1730
- update: (patch, opts) => runWrite(ctx, {
1731
- type,
1732
- operation: "update",
1733
- vars: { id },
1734
- method: "PATCH",
1735
- body: toDocument(ctx.descriptor, type, patch, { id }),
1736
- query: writeQuery(opts),
1737
- remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
1738
- accepted: ctx.descriptor[type]?.accepted?.update,
1739
- wait: waitOptions(opts?.wait)
1740
- }),
1775
+ get: (query) => run(ctx, type, "fetchOne", vars, query),
1776
+ update: (patch, opts) => runUpdate(ctx, type, vars, id, patch, opts),
1741
1777
  delete: () => runWrite(ctx, {
1742
1778
  type,
1743
1779
  operation: "delete",
1744
- vars: { id },
1780
+ vars,
1745
1781
  method: "DELETE",
1746
1782
  body: void 0,
1747
1783
  remap: (error) => withRemappedPaths(error, ctx.descriptor, type)
1748
1784
  }),
1749
- rel: (name) => relationshipAccessor(ctx, type, id, name),
1750
- actions: actionsAccessor(ctx, type, "resource", { id })
1751
- };
1752
- return new Proxy(base, { get(target, prop, receiver) {
1753
- if (typeof prop === "string" && !HANDLE_RESERVED.has(prop) && prop in relations) return relationshipAccessor(ctx, type, id, prop);
1754
- return Reflect.get(target, prop, receiver);
1755
- } });
1785
+ rel: (name) => relationshipAccessor(ctx, type, vars, name),
1786
+ actions: actionsAccessor(ctx, type, "resource", vars)
1787
+ });
1788
+ }
1789
+ /**
1790
+ * Build the accessor of a singleton type (`client.inboxes`): a handle on the caller's one
1791
+ * resource, whose paths carry no id. Its update takes the resource's `id` in the input, since
1792
+ * the server reads it from the body.
1793
+ */
1794
+ function singletonAccessor(ctx, type) {
1795
+ const vars = {};
1796
+ return withRelations(ctx, type, vars, {
1797
+ type,
1798
+ get: (query) => run(ctx, type, "fetchOne", vars, query),
1799
+ update: (input, opts) => {
1800
+ const { id, ...patch } = input;
1801
+ if (typeof id !== "string" || id === "") return Promise.reject(/* @__PURE__ */ new Error(`Updating the "${type}" singleton needs its id in the input, such as the id of the resource its get() read.`));
1802
+ return runUpdate(ctx, type, vars, id, patch, opts);
1803
+ },
1804
+ rel: (name) => relationshipAccessor(ctx, type, vars, name),
1805
+ actions: actionsAccessor(ctx, type, "resource", vars)
1806
+ });
1756
1807
  }
1757
1808
  /** Build the collection-scoped accessor for one wire type (`client.albums`). */
1758
1809
  function typeAccessor(ctx, type) {
@@ -1776,7 +1827,8 @@ function typeAccessor(ctx, type) {
1776
1827
  }
1777
1828
  /**
1778
1829
  * Build a descriptor-driven read client. Generic at runtime (a Proxy over the descriptor),
1779
- * not per-type codegen: `client.<type>` yields a {@link TypeAccessor}, `.id(id)` a handle,
1830
+ * not per-type codegen: `client.<type>` yields a {@link TypeAccessor}, or a
1831
+ * {@link SingletonAccessor} for a singleton type, `.id(id)` a handle,
1780
1832
  * and a handle's relation accessors drive the relationship/related endpoints. Navigation
1781
1833
  * (`$next()`/`$prev()`, related links) is wired through `materialise`'s `navigate` seam,
1782
1834
  * which resolves the server's link against `baseUrl`, executes it and re-materialises.
@@ -1818,7 +1870,7 @@ function createClient(descriptor, options) {
1818
1870
  if (typeof prop !== "string" || !(prop in descriptor)) return;
1819
1871
  let accessor = accessors.get(prop);
1820
1872
  if (accessor === void 0) {
1821
- accessor = typeAccessor(ctx, prop);
1873
+ accessor = descriptor[prop]?.singleton === true ? singletonAccessor(ctx, prop) : typeAccessor(ctx, prop);
1822
1874
  accessors.set(prop, accessor);
1823
1875
  }
1824
1876
  return accessor;
@@ -1829,15 +1881,6 @@ function createClient(descriptor, options) {
1829
1881
  });
1830
1882
  }
1831
1883
  //#endregion
1832
- //#region src/descriptor.ts
1833
- /**
1834
- * Whether a relation is polymorphic: flagged {@link RelationDescriptor.polymorphic}, or, when the
1835
- * flag is absent, listing more than one related type.
1836
- */
1837
- function isPolymorphic(relation) {
1838
- return relation.polymorphic ?? relation.types.length > 1;
1839
- }
1840
- //#endregion
1841
1884
  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 };
1842
1885
 
1843
1886
  //# sourceMappingURL=index.mjs.map