@haddowg/json-api-client 1.15.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -126,6 +126,26 @@ reads (no single-`get` endpoint advertises it). The client negotiates the Counta
126
126
 
127
127
  ```ts
128
128
  const albums = await client.albums.list({ withCount: ['tracks'] })
129
+ albums[0]!.$count('tracks') // number: the list asked to count tracks
130
+ ```
131
+
132
+ The server puts each count in the relationship object's `meta.total`. `$count(name)` reads it off
133
+ the resource, even when the relationship carries no data, and a to-many relationship array has
134
+ the same value as `$count`. Both are `undefined` when the server sent no finite number.
135
+
136
+ ### `relatedQuery` (the Relationship Queries profile)
137
+
138
+ Where a type's `list` or `get` advertises it, `relatedQuery` filters and sorts a relationship
139
+ from the primary read, keyed by include path. Each entry's `filter` and `sort` take what the
140
+ relation's own related read takes. The client negotiates the profile in `Accept`, beside the
141
+ Countable one when `withCount` is set too.
142
+
143
+ ```ts
144
+ const runs = await client['campaign-template-runs'].list({
145
+ withCount: ['items'],
146
+ relatedQuery: { items: { filter: { state: 'failed' } } },
147
+ })
148
+ runs[0]!.$count('items') // the run's failed items
129
149
  ```
130
150
 
131
151
  ### Pagination & cursor
@@ -209,7 +229,7 @@ off a handle (`.id(id)`). The body shape follows the action's declared `input`
209
229
  ```ts
210
230
  // Resource-scoped, document in / document out.
211
231
  const reissued = await client.albums.id('1').actions.reissue({
212
- data: { type: 'albums', attributes: { title: 'OK Computer' } },
232
+ releasedAt: '2001-10-01T00:00:00+00:00',
213
233
  })
214
234
 
215
235
  // Collection-scoped, no input.
package/dist/ajv.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as Validator, n as SchemaMap } from "./validate-BbaMiYmY.cjs";
1
+ import { a as Validator, n as SchemaMap } from "./validate-sTJePeDg.cjs";
2
2
  import { ValidateFunction } from "ajv";
3
3
 
4
4
  //#region src/ajv.d.ts
package/dist/ajv.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as Validator, n as SchemaMap } from "./validate-BbaMiYmY.mjs";
1
+ import { a as Validator, n as SchemaMap } from "./validate-sTJePeDg.mjs";
2
2
  import { ValidateFunction } from "ajv";
3
3
 
4
4
  //#region src/ajv.d.ts
package/dist/index.cjs CHANGED
@@ -238,6 +238,11 @@ const defineGetter = (target, key, get) => {
238
238
  configurable: true
239
239
  });
240
240
  };
241
+ /** A relationship object's `meta.total` when it is a finite number, else `undefined`. */
242
+ const relationTotal = (rel) => {
243
+ const total = rel?.meta?.["total"];
244
+ return typeof total === "number" && Number.isFinite(total) ? total : void 0;
245
+ };
241
246
  /**
242
247
  * Materialise a JSON:API document into a hydrated graph (ADR 0002):
243
248
  *
@@ -342,7 +347,7 @@ function resolveMember(member, env, index, nodes, ctx, relationEdge) {
342
347
  if (included) return buildEdgeView(buildNode(included, env, index, nodes, ctx), member, relationEdge);
343
348
  return buildIdentifierView(member, relationEdge);
344
349
  }
345
- /** Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$rel). */
350
+ /** Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$rel/$count). */
346
351
  function attachResourceEnvelope(node, raw, env, rels) {
347
352
  defineGetter(node, "$meta", () => raw.meta);
348
353
  defineGetter(node, "$links", () => raw.links);
@@ -358,6 +363,7 @@ function attachResourceEnvelope(node, raw, env, rels) {
358
363
  if (rel.meta !== void 0) view.meta = rel.meta;
359
364
  return view;
360
365
  });
366
+ define(node, "$count", (name) => Object.hasOwn(rels, name) ? relationTotal(rels[name]) : void 0);
361
367
  }
362
368
  /**
363
369
  * A per-edge VIEW over a node: a distinct wrapper per membership that reads through to the
@@ -376,7 +382,8 @@ function buildEdgeView(node, member, relationEdge) {
376
382
  "$self",
377
383
  "$document",
378
384
  "$raw",
379
- "$rel"
385
+ "$rel",
386
+ "$count"
380
387
  ]) delegate(view, node, k);
381
388
  attachEdgeEnvelope(view, member, false, relationEdge);
382
389
  return view;
@@ -450,6 +457,7 @@ function augmentRelationArray(members, rel, paginator, ctx) {
450
457
  const links = rel.links;
451
458
  defineGetter(arr, "$links", () => links);
452
459
  defineGetter(arr, "$meta", () => rel.meta);
460
+ defineGetter(arr, "$count", () => relationTotal(rel));
453
461
  attachPage(arr, paginator, pageMeta(rel.meta), links, ctx, false);
454
462
  return arr;
455
463
  }
@@ -602,16 +610,21 @@ const appendFilterValue = (parts, key, value, list = false) => {
602
610
  * Serialise a read query to a query string (no leading `?`). Bracketed keys
603
611
  * (`filter[title]`, `page[number]`, `fields[albums]`) are kept literal; only values
604
612
  * are percent-encoded. `isListFilter` names the filter keys that take a list, whose array value
605
- * goes out as `filter[<key>][]` once per member. Empty/undefined entries are skipped; key order is deterministic
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
606
615
  * (family order, then insertion order within a family) so URLs are stable for caching.
607
616
  */
608
- function serializeQuery(query, isListFilter) {
617
+ function serializeQuery(query, isListFilter, isRelatedListFilter) {
609
618
  const parts = [];
610
619
  if (query.filter) for (const [key, value] of Object.entries(query.filter)) appendFilterValue(parts, `filter[${key}]`, value, isListFilter?.(key) ?? false);
611
620
  if (query.sort !== void 0) append(parts, "sort", Array.isArray(query.sort) ? query.sort.join(",") : query.sort);
612
621
  if (query.include) append(parts, "include", query.include.join(","));
613
622
  if (query.fields) for (const [type, names] of Object.entries(query.fields)) parts.push(`fields[${type}]=${encodeURIComponent(names.join(","))}`);
614
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
+ }
615
628
  if (query.page) for (const [key, value] of Object.entries(query.page)) append(parts, `page[${key}]`, Array.isArray(value) ? value.join(",") : value);
616
629
  return parts.join("&");
617
630
  }
@@ -648,7 +661,7 @@ async function send(ctx, req, responseType) {
648
661
  sendHeaders = link.sameOrigin;
649
662
  } else url = isAbsolute(req.path) ? req.path : ctx.baseUrl + req.path;
650
663
  if (req.query) {
651
- const qs = serializeQuery(req.query, req.listFilter);
664
+ const qs = serializeQuery(req.query, req.listFilter, req.relatedListFilter);
652
665
  if (qs) url += (url.includes("?") ? "&" : "?") + qs;
653
666
  }
654
667
  const negotiated = mediaType({
@@ -1193,6 +1206,7 @@ async function run(ctx, type, operation, vars, query, linkage = false, relationF
1193
1206
  req.query = params;
1194
1207
  const listFilter = listFilterMatcher(filterSpec(ctx, type, operation, vars["rel"]));
1195
1208
  if (listFilter !== void 0) req.listFilter = listFilter;
1209
+ if (params.relatedQuery !== void 0) req.relatedListFilter = relatedListFilter(ctx, type);
1196
1210
  if (signal !== void 0) req.signal = signal;
1197
1211
  negotiateProfiles(ctx, type, params, req, relationForCount);
1198
1212
  }
@@ -1204,24 +1218,63 @@ async function run(ctx, type, operation, vars, query, linkage = false, relationF
1204
1218
  return doc === void 0 ? void 0 : materialise(doc, ctx.materialise, linkage, primaryType, paginatorOverride);
1205
1219
  }
1206
1220
  /**
1207
- * The filter vocabulary a read's `filter` is matched against: the type's for its collection read,
1208
- * and the related type's for a related or relationship read of a relation with one related type.
1221
+ * The filter vocabulary a read's `filter` is matched against: the type's for its collection read.
1222
+ * A related or relationship read takes the relation's own when its descriptor declares one, else
1223
+ * the related type's when the relation has one related type.
1209
1224
  */
1210
1225
  function filterSpec(ctx, type, operation, rel) {
1211
1226
  if (operation === "fetchMany") return ctx.descriptor[type];
1212
- const types = rel === void 0 ? void 0 : ctx.descriptor[type]?.relations[rel]?.types;
1227
+ const relation = rel === void 0 ? void 0 : ctx.descriptor[type]?.relations[rel];
1228
+ if (relation?.filterable !== void 0 || relation?.filterFamilies !== void 0) return relation;
1229
+ const types = relation?.types;
1213
1230
  return types?.length === 1 ? ctx.descriptor[types[0]] : void 0;
1214
1231
  }
1215
1232
  /**
1233
+ * Whether a `relatedQuery` entry's filter key takes a list, matched against the vocabulary of the
1234
+ * relation its include path ends on, as that relation's related read matches it. A path through a
1235
+ * polymorphic relation continues from the first member type declaring the next relation.
1236
+ */
1237
+ function relatedListFilter(ctx, type) {
1238
+ const matchers = /* @__PURE__ */ new Map();
1239
+ return (path, key) => {
1240
+ if (!matchers.has(path)) matchers.set(path, listFilterMatcher(relatedQuerySpec(ctx, type, path)));
1241
+ return matchers.get(path)?.(key) ?? false;
1242
+ };
1243
+ }
1244
+ /** The filter vocabulary of the relation an include path from `type` ends on. */
1245
+ function relatedQuerySpec(ctx, type, path) {
1246
+ const names = path.split(".");
1247
+ let owners = [type];
1248
+ for (const [index, name] of names.entries()) {
1249
+ const owner = owners.find((t) => ctx.descriptor[t]?.relations[name] !== void 0);
1250
+ if (owner === void 0) return;
1251
+ if (index === names.length - 1) return filterSpec(ctx, owner, "fetchRelated", name);
1252
+ owners = ctx.descriptor[owner].relations[name].types;
1253
+ }
1254
+ }
1255
+ /** Whether a `relatedQuery` carries a filter or sort for any path, so it reaches the wire. */
1256
+ function sendsRelatedQuery(relatedQuery) {
1257
+ return Object.values(relatedQuery ?? {}).some((entry) => Object.keys(entry?.filter ?? {}).length > 0 || entry?.sort !== void 0 && entry.sort.length > 0);
1258
+ }
1259
+ /**
1216
1260
  * Add any profiles a query's parameters require to the request's negotiated `profiles`. A
1217
1261
  * `withCount` read needs the type's Countable profile in `Accept` — else the server rejects it
1218
1262
  * (400) under strict query-param validation. The profile URI is read from the descriptor's
1219
- * `countable` block (never hardcoded); absent when the type advertises no Countable profile.
1263
+ * `countable` block (never hardcoded); absent when the type advertises no Countable profile. A
1264
+ * `relatedQuery` on a collection or single read likewise adds the type's Relationship Queries
1265
+ * profile, after any Countable one.
1220
1266
  */
1221
1267
  function negotiateProfiles(ctx, type, query, req, relationForCount) {
1222
- if (query.withCount === void 0 || query.withCount.length === 0) return;
1223
- const profile = relationForCount !== void 0 ? ctx.descriptor[type]?.relations[relationForCount]?.countable?.profile : ctx.descriptor[type]?.countable?.profile;
1224
- if (profile !== void 0) req.profiles = [...req.profiles ?? [], profile];
1268
+ const profiles = [];
1269
+ if (query.withCount !== void 0 && query.withCount.length > 0) {
1270
+ const profile = relationForCount !== void 0 ? ctx.descriptor[type]?.relations[relationForCount]?.countable?.profile : ctx.descriptor[type]?.countable?.profile;
1271
+ if (profile !== void 0) profiles.push(profile);
1272
+ }
1273
+ if (relationForCount === void 0 && sendsRelatedQuery(query.relatedQuery)) {
1274
+ const profile = ctx.descriptor[type]?.relatedQuery?.profile;
1275
+ if (profile !== void 0 && !profiles.includes(profile)) profiles.push(profile);
1276
+ }
1277
+ if (profiles.length > 0) req.profiles = [...req.profiles ?? [], ...profiles];
1225
1278
  }
1226
1279
  /** Project a write's opts to the read-query families the response honours (`include`/`fields`). */
1227
1280
  function writeQuery(opts) {
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as MemberName, $t as ResourceLinks, A as BinaryBody, An as MenuDescriptor, At as AtomicRef, B as ErrorCodeOf, Bn as RelationMutations, Bt as MediaTypeParams, C as TransportRawBody, Cn as Cardinality, Ct as isActionLocation, D as ActionCallOptions, Dn as InputMedia, Dt as AtomicDeleteHandle, E as fetchTransport, En as FilterFamilyDescriptor, Et as AtomicCreateInput, F as CreateInput, Fn as PaginatorStrategy, Ft as runAtomic, G as HydratedMember, Gn as isPolymorphic, Gt as Edge, H as FieldsMap, Hn as ResourceExamples, Ht as mediaType, I as DefaultActionTypes, In as PivotDescriptor, It as ATOMIC_EXT, J as IncludedRelations, Jt as LinkObject, K as IdentifierMember, Kt as EdgeEnvelope, L as DefaultAttributes, Ln as RawMediaKind, Lt as ATOMIC_MEDIA_TYPE, M as Client, Mn as PaginatorDescriptor, Mt as AtomicResults, N as Collection, Nn as PaginatorKind, Nt as AtomicUpdateHandle, O as ActionsAccessor, On as InputMediaKind, Ot as AtomicHandle, P as CountToken, Pn as PaginatorRole, Pt as AtomicUpdateInput, Q as ListPageParams, Qt as ResourceEnvelope, R as DefaultWriteAttributes, Rn as RawOutputMedia, Rt as JSON_API_MEDIA_TYPE, S as JsonApiTransport, Sn as AtomicDescriptor, St as ActionLocation, T as TransportResponse, Tn as CountableDescriptor, Tt as AtomicCreateHandle, U as FilterKey, Un as SortFamilyDescriptor, Ut as ArrayEnvelope, V as FieldSelectionMap, Vn as ResourceDescriptor, Vt as ResourceIdentifier, W as FilterQuery, Wn as StrategyDescriptor, Wt as DocumentEnvelope, X as IncludedType, Xt as NavigateOptions, Y as IncludedResource, Yt as MaterialiseContext, Z as LinkageRef, Zt as RelationView, _ as serializeQuery, _n as ActionLocationDescriptor, _t as TypeName, a as Validator, an as Page, at as RelationName, b as HeadersInit, bn as ApiDescriptor, bt as WithLinks, c as resolveValidator, cn as PageMeta, ct as RelationReadQuery, d as JsonApiContext, dn as PageParamsOf, dt as ResourceHandle, en as materialise, et as PivotInput, f as JsonApiRequest, fn as ResolvedPaginator, ft as ResourceObjectView, g as executeRaw, gn as ActionInput, gt as TypeAccessor, h as execute, hn as ActionDescriptor, ht as SortToken, i as ValidationOption, in as ExactPageParams, it as RelatedIncludedType, j as BinaryResponseType, jn as OperationExamples, jt as AtomicResult, k as AtomicResultOf, kn as MediaExamples, kt as AtomicRecorder, l as validateDocument, ln as PageOf, lt as RelationshipAccessor, m as ReadQuery, mn as resolvePaginator, mt as SortQuery, n as SchemaMap, nn as relatedPaginatorKind, nt as ReadableRelationName, o as WireResource, on as PageKeys, ot as RelationPageParams, p as RawResponseType, pn as TypedPage, pt as SingleReadQuery, q as IncludePath, qt as Link, r as ValidationConfig, rn as CANONICAL_PAGE_KEYS, rt as RelatedIncludedResource, s as assertJsonApiDocument, sn as PageLinks, st as RelationPaginator, t as ResolvedValidator, tn as relatedPaginator, tt as ReadResult, u as Document, un as PageParams, ut as ResourceAccessors, v as ClientOptions, vn as ActionOutput, vt as TypedReadQuery, w as TransportRequest, wn as ClientIdPolicy, wt as readActionLocation, x as createClient, xn as ApiExamples, xt as WriteOptions, y as HANDLE_RESERVED, yn as ActionScope, yt as UpdateInput, z as EdgeMembers, zn as RelationDescriptor, zt as LocalIdentifier } from "./validate-BbaMiYmY.cjs";
1
+ import { $ as LinkageRef, $n as RelationMutations, $t as ArrayEnvelope, A as BinaryBody, An as ActionScope, At as WithLinks, B as DefaultWriteAttributes, Bn as MediaExamples, Bt as AtomicRef, C as TransportRawBody, Cn as ResolvedPaginator, Ct as SortQuery, D as ActionCallOptions, Dn as ActionInput, Dt as TypedReadQuery, E as fetchTransport, En as ActionDescriptor, Et as TypeName, F as CountToken, Fn as ClientIdPolicy, Ft as AtomicCreateHandle, G as FilterKey, Gn as PaginatorRole, Gt as runAtomic, H as ErrorCodeOf, Hn as OperationExamples, Ht as AtomicResults, I as CountedRelationName, In as CountableDescriptor, It as AtomicCreateInput, J as IdentifierMember, Jn as RawMediaKind, Jt as JSON_API_MEDIA_TYPE, K as FilterQuery, Kn as PaginatorStrategy, Kt as ATOMIC_EXT, L as CreateInput, Ln as FilterFamilyDescriptor, Lt as AtomicDeleteHandle, M as Client, Mn as ApiExamples, Mt as ActionLocation, N as Collection, Nn as AtomicDescriptor, Nt as isActionLocation, O as ActionsAccessor, On as ActionLocationDescriptor, Ot as TypedRelationReadQuery, P as CountAccessor, Pn as Cardinality, Pt as readActionLocation, Q as IncludedType, Qn as RelationDescriptor, Qt as mediaType, R as DefaultActionTypes, Rn as InputMedia, Rt as AtomicHandle, S as JsonApiTransport, Sn as PageParamsOf, St as SingleReadQuery, T as TransportResponse, Tn as resolvePaginator, Tt as TypeAccessor, U as FieldSelectionMap, Un as PaginatorDescriptor, Ut as AtomicUpdateHandle, V as EdgeMembers, Vn as MenuDescriptor, Vt as AtomicResult, W as FieldsMap, Wn as PaginatorKind, Wt as AtomicUpdateInput, X as IncludedRelations, Xn as RelatedQueryDescriptor, Xt as MediaTypeParams, Y as IncludePath, Yn as RawOutputMedia, Yt as LocalIdentifier, Z as IncludedResource, Zn as RelatedQueryOperation, Zt as ResourceIdentifier, _ as serializeQuery, _n as PageKeys, _t as RelationSortQuery, a as Validator, an as MaterialiseContext, at as ReadableRelationName, b as HeadersInit, bn as PageOf, bt as ResourceHandle, c as resolveValidator, cn as RelationView, ct as RelatedQuery, d as JsonApiContext, dn as materialise, dt as RelationCollection, en as DocumentEnvelope, er as ResourceDescriptor, et as ListPageParams, f as JsonApiRequest, fn as relatedPaginator, ft as RelationFilterQuery, g as executeRaw, gn as Page, gt as RelationReadQuery, h as execute, hn as ExactPageParams, ht as RelationPaginator, i as ValidationOption, in as LinkObject, ir as isPolymorphic, it as ReadResult, j as BinaryResponseType, jn as ApiDescriptor, jt as WriteOptions, k as AtomicResultOf, kn as ActionOutput, kt as UpdateInput, l as validateDocument, ln as ResourceEnvelope, lt as RelatedQueryEntry, m as ReadQuery, mn as CANONICAL_PAGE_KEYS, mt as RelationPageParams, n as SchemaMap, nn as EdgeEnvelope, nr as SortFamilyDescriptor, nt as MemberName, o as WireResource, on as NavigateOptions, ot as RelatedIncludedResource, p as RawResponseType, pn as relatedPaginatorKind, pt as RelationName, q as HydratedMember, qn as PivotDescriptor, qt as ATOMIC_MEDIA_TYPE, r as ValidationConfig, rn as Link, rr as StrategyDescriptor, rt as PivotInput, s as assertJsonApiDocument, sn as RelationArrayEnvelope, st as RelatedIncludedType, t as ResolvedValidator, tn as Edge, tr as ResourceExamples, tt as LooseRelatedQueryEntry, u as Document, un as ResourceLinks, ut as RelatedQueryParam, v as ClientOptions, vn as PageLinks, vt as RelationshipAccessor, w as TransportRequest, wn as TypedPage, wt as SortToken, x as createClient, xn as PageParams, xt as ResourceObjectView, y as HANDLE_RESERVED, yn as PageMeta, yt as ResourceAccessors, z as DefaultAttributes, zn as InputMediaKind, zt as AtomicRecorder } from "./validate-sTJePeDg.cjs";
2
2
 
3
3
  //#region src/errors.d.ts
4
4
  /**
@@ -253,5 +253,5 @@ declare function withRemappedRelationshipPaths(error: JsonApiError, rel: string,
253
253
  */
254
254
  declare function withRemappedAtomicPaths(error: JsonApiError, descriptor: ApiDescriptor, typeForOp: (opIndex: number) => string | undefined): JsonApiError;
255
255
  //#endregion
256
- export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, ActionCallOptions, ActionDescriptor, ActionInput, ActionLocation, ActionLocationDescriptor, ActionOutput, ActionScope, ActionsAccessor, ApiDescriptor, ApiExamples, ArrayEnvelope, AtomicCreateHandle, AtomicCreateInput, AtomicDeleteHandle, AtomicDescriptor, AtomicHandle, AtomicRecorder, AtomicRef, AtomicResult, AtomicResultOf, AtomicResults, AtomicUpdateHandle, AtomicUpdateInput, BinaryBody, BinaryResponseType, CANONICAL_PAGE_KEYS, Cardinality, Client, ClientIdPolicy, ClientOptions, CodedErrorObject, Collection, CountToken, CountableDescriptor, CreateInput, DefaultActionTypes, DefaultAttributes, DefaultWriteAttributes, Document, DocumentEnvelope, Edge, EdgeEnvelope, EdgeMembers, ErrorCodeGuard, ErrorCodeOf, ErrorFinder, ExactPageParams, FieldSelectionMap, FieldsMap, FilterFamilyDescriptor, FilterKey, FilterQuery, FilterSpec, HANDLE_RESERVED, HeadersInit, HydratedMember, IdentifierMember, IncludePath, IncludedRelations, IncludedResource, IncludedType, InputMedia, InputMediaKind, JSON_API_MEDIA_TYPE, JsonApiContext, JsonApiError, JsonApiErrorObject, JsonApiRequest, JsonApiTransport, Link, LinkObject, LinkageRef, ListPageParams, LocalIdentifier, MaterialiseContext, MediaExamples, MediaTypeParams, MemberName, MenuDescriptor, NavigateOptions, OperationExamples, Page, PageKeys, PageLinks, PageMeta, PageOf, PageParams, PageParamsOf, PaginatorDescriptor, PaginatorKind, PaginatorRole, PaginatorStrategy, PivotDescriptor, PivotInput, RawMediaKind, RawOutputMedia, RawResponseType, ReadQuery, ReadResult, ReadableRelationName, RelatedIncludedResource, RelatedIncludedType, RelationDescriptor, RelationMutations, RelationName, RelationPageParams, RelationPaginator, RelationReadQuery, RelationView, RelationshipAccessor, RelationshipDocument, ResolvedPaginator, ResolvedValidator, ResourceAccessors, ResourceDescriptor, ResourceEnvelope, ResourceExamples, ResourceHandle, ResourceIdentifier, ResourceLinks, ResourceObjectView, SchemaMap, SingleReadQuery, SortFamilyDescriptor, SortQuery, SortToken, StrategyDescriptor, StructuralGuardError, ToDocumentOptions, TransportRawBody, TransportRequest, TransportResponse, TypeAccessor, TypeName, TypedPage, TypedReadQuery, UpdateInput, ValidationConfig, ValidationOption, Validator, WireResource, WithLinks, WriteDocument, WriteOptions, 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 };
256
+ export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, ActionCallOptions, ActionDescriptor, ActionInput, ActionLocation, ActionLocationDescriptor, ActionOutput, ActionScope, ActionsAccessor, ApiDescriptor, ApiExamples, ArrayEnvelope, AtomicCreateHandle, AtomicCreateInput, AtomicDeleteHandle, AtomicDescriptor, AtomicHandle, AtomicRecorder, AtomicRef, AtomicResult, AtomicResultOf, AtomicResults, AtomicUpdateHandle, AtomicUpdateInput, BinaryBody, BinaryResponseType, CANONICAL_PAGE_KEYS, Cardinality, Client, ClientIdPolicy, ClientOptions, CodedErrorObject, Collection, CountAccessor, CountToken, CountableDescriptor, CountedRelationName, CreateInput, DefaultActionTypes, DefaultAttributes, DefaultWriteAttributes, Document, DocumentEnvelope, Edge, EdgeEnvelope, EdgeMembers, ErrorCodeGuard, ErrorCodeOf, ErrorFinder, ExactPageParams, FieldSelectionMap, FieldsMap, FilterFamilyDescriptor, FilterKey, FilterQuery, FilterSpec, HANDLE_RESERVED, HeadersInit, HydratedMember, IdentifierMember, IncludePath, IncludedRelations, IncludedResource, IncludedType, InputMedia, InputMediaKind, JSON_API_MEDIA_TYPE, JsonApiContext, JsonApiError, JsonApiErrorObject, JsonApiRequest, JsonApiTransport, Link, LinkObject, LinkageRef, ListPageParams, LocalIdentifier, LooseRelatedQueryEntry, MaterialiseContext, MediaExamples, MediaTypeParams, MemberName, MenuDescriptor, NavigateOptions, OperationExamples, Page, PageKeys, PageLinks, PageMeta, PageOf, PageParams, PageParamsOf, PaginatorDescriptor, PaginatorKind, PaginatorRole, PaginatorStrategy, PivotDescriptor, PivotInput, RawMediaKind, RawOutputMedia, RawResponseType, ReadQuery, ReadResult, ReadableRelationName, RelatedIncludedResource, RelatedIncludedType, RelatedQuery, RelatedQueryDescriptor, RelatedQueryEntry, RelatedQueryOperation, RelatedQueryParam, RelationArrayEnvelope, RelationCollection, RelationDescriptor, RelationFilterQuery, RelationMutations, RelationName, RelationPageParams, RelationPaginator, RelationReadQuery, RelationSortQuery, RelationView, RelationshipAccessor, RelationshipDocument, ResolvedPaginator, ResolvedValidator, ResourceAccessors, ResourceDescriptor, ResourceEnvelope, ResourceExamples, ResourceHandle, ResourceIdentifier, ResourceLinks, ResourceObjectView, SchemaMap, SingleReadQuery, SortFamilyDescriptor, SortQuery, SortToken, StrategyDescriptor, StructuralGuardError, ToDocumentOptions, TransportRawBody, TransportRequest, TransportResponse, TypeAccessor, TypeName, TypedPage, TypedReadQuery, TypedRelationReadQuery, UpdateInput, ValidationConfig, ValidationOption, Validator, WireResource, WithLinks, WriteDocument, WriteOptions, 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 };
257
257
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as MemberName, $t as ResourceLinks, A as BinaryBody, An as MenuDescriptor, At as AtomicRef, B as ErrorCodeOf, Bn as RelationMutations, Bt as MediaTypeParams, C as TransportRawBody, Cn as Cardinality, Ct as isActionLocation, D as ActionCallOptions, Dn as InputMedia, Dt as AtomicDeleteHandle, E as fetchTransport, En as FilterFamilyDescriptor, Et as AtomicCreateInput, F as CreateInput, Fn as PaginatorStrategy, Ft as runAtomic, G as HydratedMember, Gn as isPolymorphic, Gt as Edge, H as FieldsMap, Hn as ResourceExamples, Ht as mediaType, I as DefaultActionTypes, In as PivotDescriptor, It as ATOMIC_EXT, J as IncludedRelations, Jt as LinkObject, K as IdentifierMember, Kt as EdgeEnvelope, L as DefaultAttributes, Ln as RawMediaKind, Lt as ATOMIC_MEDIA_TYPE, M as Client, Mn as PaginatorDescriptor, Mt as AtomicResults, N as Collection, Nn as PaginatorKind, Nt as AtomicUpdateHandle, O as ActionsAccessor, On as InputMediaKind, Ot as AtomicHandle, P as CountToken, Pn as PaginatorRole, Pt as AtomicUpdateInput, Q as ListPageParams, Qt as ResourceEnvelope, R as DefaultWriteAttributes, Rn as RawOutputMedia, Rt as JSON_API_MEDIA_TYPE, S as JsonApiTransport, Sn as AtomicDescriptor, St as ActionLocation, T as TransportResponse, Tn as CountableDescriptor, Tt as AtomicCreateHandle, U as FilterKey, Un as SortFamilyDescriptor, Ut as ArrayEnvelope, V as FieldSelectionMap, Vn as ResourceDescriptor, Vt as ResourceIdentifier, W as FilterQuery, Wn as StrategyDescriptor, Wt as DocumentEnvelope, X as IncludedType, Xt as NavigateOptions, Y as IncludedResource, Yt as MaterialiseContext, Z as LinkageRef, Zt as RelationView, _ as serializeQuery, _n as ActionLocationDescriptor, _t as TypeName, a as Validator, an as Page, at as RelationName, b as HeadersInit, bn as ApiDescriptor, bt as WithLinks, c as resolveValidator, cn as PageMeta, ct as RelationReadQuery, d as JsonApiContext, dn as PageParamsOf, dt as ResourceHandle, en as materialise, et as PivotInput, f as JsonApiRequest, fn as ResolvedPaginator, ft as ResourceObjectView, g as executeRaw, gn as ActionInput, gt as TypeAccessor, h as execute, hn as ActionDescriptor, ht as SortToken, i as ValidationOption, in as ExactPageParams, it as RelatedIncludedType, j as BinaryResponseType, jn as OperationExamples, jt as AtomicResult, k as AtomicResultOf, kn as MediaExamples, kt as AtomicRecorder, l as validateDocument, ln as PageOf, lt as RelationshipAccessor, m as ReadQuery, mn as resolvePaginator, mt as SortQuery, n as SchemaMap, nn as relatedPaginatorKind, nt as ReadableRelationName, o as WireResource, on as PageKeys, ot as RelationPageParams, p as RawResponseType, pn as TypedPage, pt as SingleReadQuery, q as IncludePath, qt as Link, r as ValidationConfig, rn as CANONICAL_PAGE_KEYS, rt as RelatedIncludedResource, s as assertJsonApiDocument, sn as PageLinks, st as RelationPaginator, t as ResolvedValidator, tn as relatedPaginator, tt as ReadResult, u as Document, un as PageParams, ut as ResourceAccessors, v as ClientOptions, vn as ActionOutput, vt as TypedReadQuery, w as TransportRequest, wn as ClientIdPolicy, wt as readActionLocation, x as createClient, xn as ApiExamples, xt as WriteOptions, y as HANDLE_RESERVED, yn as ActionScope, yt as UpdateInput, z as EdgeMembers, zn as RelationDescriptor, zt as LocalIdentifier } from "./validate-BbaMiYmY.mjs";
1
+ import { $ as LinkageRef, $n as RelationMutations, $t as ArrayEnvelope, A as BinaryBody, An as ActionScope, At as WithLinks, B as DefaultWriteAttributes, Bn as MediaExamples, Bt as AtomicRef, C as TransportRawBody, Cn as ResolvedPaginator, Ct as SortQuery, D as ActionCallOptions, Dn as ActionInput, Dt as TypedReadQuery, E as fetchTransport, En as ActionDescriptor, Et as TypeName, F as CountToken, Fn as ClientIdPolicy, Ft as AtomicCreateHandle, G as FilterKey, Gn as PaginatorRole, Gt as runAtomic, H as ErrorCodeOf, Hn as OperationExamples, Ht as AtomicResults, I as CountedRelationName, In as CountableDescriptor, It as AtomicCreateInput, J as IdentifierMember, Jn as RawMediaKind, Jt as JSON_API_MEDIA_TYPE, K as FilterQuery, Kn as PaginatorStrategy, Kt as ATOMIC_EXT, L as CreateInput, Ln as FilterFamilyDescriptor, Lt as AtomicDeleteHandle, M as Client, Mn as ApiExamples, Mt as ActionLocation, N as Collection, Nn as AtomicDescriptor, Nt as isActionLocation, O as ActionsAccessor, On as ActionLocationDescriptor, Ot as TypedRelationReadQuery, P as CountAccessor, Pn as Cardinality, Pt as readActionLocation, Q as IncludedType, Qn as RelationDescriptor, Qt as mediaType, R as DefaultActionTypes, Rn as InputMedia, Rt as AtomicHandle, S as JsonApiTransport, Sn as PageParamsOf, St as SingleReadQuery, T as TransportResponse, Tn as resolvePaginator, Tt as TypeAccessor, U as FieldSelectionMap, Un as PaginatorDescriptor, Ut as AtomicUpdateHandle, V as EdgeMembers, Vn as MenuDescriptor, Vt as AtomicResult, W as FieldsMap, Wn as PaginatorKind, Wt as AtomicUpdateInput, X as IncludedRelations, Xn as RelatedQueryDescriptor, Xt as MediaTypeParams, Y as IncludePath, Yn as RawOutputMedia, Yt as LocalIdentifier, Z as IncludedResource, Zn as RelatedQueryOperation, Zt as ResourceIdentifier, _ as serializeQuery, _n as PageKeys, _t as RelationSortQuery, a as Validator, an as MaterialiseContext, at as ReadableRelationName, b as HeadersInit, bn as PageOf, bt as ResourceHandle, c as resolveValidator, cn as RelationView, ct as RelatedQuery, d as JsonApiContext, dn as materialise, dt as RelationCollection, en as DocumentEnvelope, er as ResourceDescriptor, et as ListPageParams, f as JsonApiRequest, fn as relatedPaginator, ft as RelationFilterQuery, g as executeRaw, gn as Page, gt as RelationReadQuery, h as execute, hn as ExactPageParams, ht as RelationPaginator, i as ValidationOption, in as LinkObject, ir as isPolymorphic, it as ReadResult, j as BinaryResponseType, jn as ApiDescriptor, jt as WriteOptions, k as AtomicResultOf, kn as ActionOutput, kt as UpdateInput, l as validateDocument, ln as ResourceEnvelope, lt as RelatedQueryEntry, m as ReadQuery, mn as CANONICAL_PAGE_KEYS, mt as RelationPageParams, n as SchemaMap, nn as EdgeEnvelope, nr as SortFamilyDescriptor, nt as MemberName, o as WireResource, on as NavigateOptions, ot as RelatedIncludedResource, p as RawResponseType, pn as relatedPaginatorKind, pt as RelationName, q as HydratedMember, qn as PivotDescriptor, qt as ATOMIC_MEDIA_TYPE, r as ValidationConfig, rn as Link, rr as StrategyDescriptor, rt as PivotInput, s as assertJsonApiDocument, sn as RelationArrayEnvelope, st as RelatedIncludedType, t as ResolvedValidator, tn as Edge, tr as ResourceExamples, tt as LooseRelatedQueryEntry, u as Document, un as ResourceLinks, ut as RelatedQueryParam, v as ClientOptions, vn as PageLinks, vt as RelationshipAccessor, w as TransportRequest, wn as TypedPage, wt as SortToken, x as createClient, xn as PageParams, xt as ResourceObjectView, y as HANDLE_RESERVED, yn as PageMeta, yt as ResourceAccessors, z as DefaultAttributes, zn as InputMediaKind, zt as AtomicRecorder } from "./validate-sTJePeDg.mjs";
2
2
 
3
3
  //#region src/errors.d.ts
4
4
  /**
@@ -253,5 +253,5 @@ declare function withRemappedRelationshipPaths(error: JsonApiError, rel: string,
253
253
  */
254
254
  declare function withRemappedAtomicPaths(error: JsonApiError, descriptor: ApiDescriptor, typeForOp: (opIndex: number) => string | undefined): JsonApiError;
255
255
  //#endregion
256
- export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, ActionCallOptions, ActionDescriptor, ActionInput, ActionLocation, ActionLocationDescriptor, ActionOutput, ActionScope, ActionsAccessor, ApiDescriptor, ApiExamples, ArrayEnvelope, AtomicCreateHandle, AtomicCreateInput, AtomicDeleteHandle, AtomicDescriptor, AtomicHandle, AtomicRecorder, AtomicRef, AtomicResult, AtomicResultOf, AtomicResults, AtomicUpdateHandle, AtomicUpdateInput, BinaryBody, BinaryResponseType, CANONICAL_PAGE_KEYS, Cardinality, Client, ClientIdPolicy, ClientOptions, CodedErrorObject, Collection, CountToken, CountableDescriptor, CreateInput, DefaultActionTypes, DefaultAttributes, DefaultWriteAttributes, Document, DocumentEnvelope, Edge, EdgeEnvelope, EdgeMembers, ErrorCodeGuard, ErrorCodeOf, ErrorFinder, ExactPageParams, FieldSelectionMap, FieldsMap, FilterFamilyDescriptor, FilterKey, FilterQuery, FilterSpec, HANDLE_RESERVED, HeadersInit, HydratedMember, IdentifierMember, IncludePath, IncludedRelations, IncludedResource, IncludedType, InputMedia, InputMediaKind, JSON_API_MEDIA_TYPE, JsonApiContext, JsonApiError, JsonApiErrorObject, JsonApiRequest, JsonApiTransport, Link, LinkObject, LinkageRef, ListPageParams, LocalIdentifier, MaterialiseContext, MediaExamples, MediaTypeParams, MemberName, MenuDescriptor, NavigateOptions, OperationExamples, Page, PageKeys, PageLinks, PageMeta, PageOf, PageParams, PageParamsOf, PaginatorDescriptor, PaginatorKind, PaginatorRole, PaginatorStrategy, PivotDescriptor, PivotInput, RawMediaKind, RawOutputMedia, RawResponseType, ReadQuery, ReadResult, ReadableRelationName, RelatedIncludedResource, RelatedIncludedType, RelationDescriptor, RelationMutations, RelationName, RelationPageParams, RelationPaginator, RelationReadQuery, RelationView, RelationshipAccessor, RelationshipDocument, ResolvedPaginator, ResolvedValidator, ResourceAccessors, ResourceDescriptor, ResourceEnvelope, ResourceExamples, ResourceHandle, ResourceIdentifier, ResourceLinks, ResourceObjectView, SchemaMap, SingleReadQuery, SortFamilyDescriptor, SortQuery, SortToken, StrategyDescriptor, StructuralGuardError, ToDocumentOptions, TransportRawBody, TransportRequest, TransportResponse, TypeAccessor, TypeName, TypedPage, TypedReadQuery, UpdateInput, ValidationConfig, ValidationOption, Validator, WireResource, WithLinks, WriteDocument, WriteOptions, 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 };
256
+ export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, ActionCallOptions, ActionDescriptor, ActionInput, ActionLocation, ActionLocationDescriptor, ActionOutput, ActionScope, ActionsAccessor, ApiDescriptor, ApiExamples, ArrayEnvelope, AtomicCreateHandle, AtomicCreateInput, AtomicDeleteHandle, AtomicDescriptor, AtomicHandle, AtomicRecorder, AtomicRef, AtomicResult, AtomicResultOf, AtomicResults, AtomicUpdateHandle, AtomicUpdateInput, BinaryBody, BinaryResponseType, CANONICAL_PAGE_KEYS, Cardinality, Client, ClientIdPolicy, ClientOptions, CodedErrorObject, Collection, CountAccessor, CountToken, CountableDescriptor, CountedRelationName, CreateInput, DefaultActionTypes, DefaultAttributes, DefaultWriteAttributes, Document, DocumentEnvelope, Edge, EdgeEnvelope, EdgeMembers, ErrorCodeGuard, ErrorCodeOf, ErrorFinder, ExactPageParams, FieldSelectionMap, FieldsMap, FilterFamilyDescriptor, FilterKey, FilterQuery, FilterSpec, HANDLE_RESERVED, HeadersInit, HydratedMember, IdentifierMember, IncludePath, IncludedRelations, IncludedResource, IncludedType, InputMedia, InputMediaKind, JSON_API_MEDIA_TYPE, JsonApiContext, JsonApiError, JsonApiErrorObject, JsonApiRequest, JsonApiTransport, Link, LinkObject, LinkageRef, ListPageParams, LocalIdentifier, LooseRelatedQueryEntry, MaterialiseContext, MediaExamples, MediaTypeParams, MemberName, MenuDescriptor, NavigateOptions, OperationExamples, Page, PageKeys, PageLinks, PageMeta, PageOf, PageParams, PageParamsOf, PaginatorDescriptor, PaginatorKind, PaginatorRole, PaginatorStrategy, PivotDescriptor, PivotInput, RawMediaKind, RawOutputMedia, RawResponseType, ReadQuery, ReadResult, ReadableRelationName, RelatedIncludedResource, RelatedIncludedType, RelatedQuery, RelatedQueryDescriptor, RelatedQueryEntry, RelatedQueryOperation, RelatedQueryParam, RelationArrayEnvelope, RelationCollection, RelationDescriptor, RelationFilterQuery, RelationMutations, RelationName, RelationPageParams, RelationPaginator, RelationReadQuery, RelationSortQuery, RelationView, RelationshipAccessor, RelationshipDocument, ResolvedPaginator, ResolvedValidator, ResourceAccessors, ResourceDescriptor, ResourceEnvelope, ResourceExamples, ResourceHandle, ResourceIdentifier, ResourceLinks, ResourceObjectView, SchemaMap, SingleReadQuery, SortFamilyDescriptor, SortQuery, SortToken, StrategyDescriptor, StructuralGuardError, ToDocumentOptions, TransportRawBody, TransportRequest, TransportResponse, TypeAccessor, TypeName, TypedPage, TypedReadQuery, TypedRelationReadQuery, UpdateInput, ValidationConfig, ValidationOption, Validator, WireResource, WithLinks, WriteDocument, WriteOptions, 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 };
257
257
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -237,6 +237,11 @@ const defineGetter = (target, key, get) => {
237
237
  configurable: true
238
238
  });
239
239
  };
240
+ /** A relationship object's `meta.total` when it is a finite number, else `undefined`. */
241
+ const relationTotal = (rel) => {
242
+ const total = rel?.meta?.["total"];
243
+ return typeof total === "number" && Number.isFinite(total) ? total : void 0;
244
+ };
240
245
  /**
241
246
  * Materialise a JSON:API document into a hydrated graph (ADR 0002):
242
247
  *
@@ -341,7 +346,7 @@ function resolveMember(member, env, index, nodes, ctx, relationEdge) {
341
346
  if (included) return buildEdgeView(buildNode(included, env, index, nodes, ctx), member, relationEdge);
342
347
  return buildIdentifierView(member, relationEdge);
343
348
  }
344
- /** Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$rel). */
349
+ /** Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$rel/$count). */
345
350
  function attachResourceEnvelope(node, raw, env, rels) {
346
351
  defineGetter(node, "$meta", () => raw.meta);
347
352
  defineGetter(node, "$links", () => raw.links);
@@ -357,6 +362,7 @@ function attachResourceEnvelope(node, raw, env, rels) {
357
362
  if (rel.meta !== void 0) view.meta = rel.meta;
358
363
  return view;
359
364
  });
365
+ define(node, "$count", (name) => Object.hasOwn(rels, name) ? relationTotal(rels[name]) : void 0);
360
366
  }
361
367
  /**
362
368
  * A per-edge VIEW over a node: a distinct wrapper per membership that reads through to the
@@ -375,7 +381,8 @@ function buildEdgeView(node, member, relationEdge) {
375
381
  "$self",
376
382
  "$document",
377
383
  "$raw",
378
- "$rel"
384
+ "$rel",
385
+ "$count"
379
386
  ]) delegate(view, node, k);
380
387
  attachEdgeEnvelope(view, member, false, relationEdge);
381
388
  return view;
@@ -449,6 +456,7 @@ function augmentRelationArray(members, rel, paginator, ctx) {
449
456
  const links = rel.links;
450
457
  defineGetter(arr, "$links", () => links);
451
458
  defineGetter(arr, "$meta", () => rel.meta);
459
+ defineGetter(arr, "$count", () => relationTotal(rel));
452
460
  attachPage(arr, paginator, pageMeta(rel.meta), links, ctx, false);
453
461
  return arr;
454
462
  }
@@ -601,16 +609,21 @@ const appendFilterValue = (parts, key, value, list = false) => {
601
609
  * Serialise a read query to a query string (no leading `?`). Bracketed keys
602
610
  * (`filter[title]`, `page[number]`, `fields[albums]`) are kept literal; only values
603
611
  * 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
612
+ * goes out as `filter[<key>][]` once per member, and `isRelatedListFilter` does the same for a
613
+ * `relatedQuery` entry's filters by include path. Empty/undefined entries are skipped; key order is deterministic
605
614
  * (family order, then insertion order within a family) so URLs are stable for caching.
606
615
  */
607
- function serializeQuery(query, isListFilter) {
616
+ function serializeQuery(query, isListFilter, isRelatedListFilter) {
608
617
  const parts = [];
609
618
  if (query.filter) for (const [key, value] of Object.entries(query.filter)) appendFilterValue(parts, `filter[${key}]`, value, isListFilter?.(key) ?? false);
610
619
  if (query.sort !== void 0) append(parts, "sort", Array.isArray(query.sort) ? query.sort.join(",") : query.sort);
611
620
  if (query.include) append(parts, "include", query.include.join(","));
612
621
  if (query.fields) for (const [type, names] of Object.entries(query.fields)) parts.push(`fields[${type}]=${encodeURIComponent(names.join(","))}`);
613
622
  if (query.withCount && query.withCount.length > 0) append(parts, "withCount", query.withCount.join(","));
623
+ for (const [path, entry] of Object.entries(query.relatedQuery ?? {})) {
624
+ for (const [key, value] of Object.entries(entry?.filter ?? {})) appendFilterValue(parts, `relatedQuery[${path}][filter][${key}]`, value, isRelatedListFilter?.(path, key) ?? false);
625
+ if (entry?.sort !== void 0) append(parts, `relatedQuery[${path}][sort]`, typeof entry.sort === "string" ? entry.sort : entry.sort.join(","));
626
+ }
614
627
  if (query.page) for (const [key, value] of Object.entries(query.page)) append(parts, `page[${key}]`, Array.isArray(value) ? value.join(",") : value);
615
628
  return parts.join("&");
616
629
  }
@@ -647,7 +660,7 @@ async function send(ctx, req, responseType) {
647
660
  sendHeaders = link.sameOrigin;
648
661
  } else url = isAbsolute(req.path) ? req.path : ctx.baseUrl + req.path;
649
662
  if (req.query) {
650
- const qs = serializeQuery(req.query, req.listFilter);
663
+ const qs = serializeQuery(req.query, req.listFilter, req.relatedListFilter);
651
664
  if (qs) url += (url.includes("?") ? "&" : "?") + qs;
652
665
  }
653
666
  const negotiated = mediaType({
@@ -1192,6 +1205,7 @@ async function run(ctx, type, operation, vars, query, linkage = false, relationF
1192
1205
  req.query = params;
1193
1206
  const listFilter = listFilterMatcher(filterSpec(ctx, type, operation, vars["rel"]));
1194
1207
  if (listFilter !== void 0) req.listFilter = listFilter;
1208
+ if (params.relatedQuery !== void 0) req.relatedListFilter = relatedListFilter(ctx, type);
1195
1209
  if (signal !== void 0) req.signal = signal;
1196
1210
  negotiateProfiles(ctx, type, params, req, relationForCount);
1197
1211
  }
@@ -1203,24 +1217,63 @@ async function run(ctx, type, operation, vars, query, linkage = false, relationF
1203
1217
  return doc === void 0 ? void 0 : materialise(doc, ctx.materialise, linkage, primaryType, paginatorOverride);
1204
1218
  }
1205
1219
  /**
1206
- * The filter vocabulary a read's `filter` is matched against: the type's for its collection read,
1207
- * and the related type's for a related or relationship read of a relation with one related type.
1220
+ * The filter vocabulary a read's `filter` is matched against: the type's for its collection read.
1221
+ * A related or relationship read takes the relation's own when its descriptor declares one, else
1222
+ * the related type's when the relation has one related type.
1208
1223
  */
1209
1224
  function filterSpec(ctx, type, operation, rel) {
1210
1225
  if (operation === "fetchMany") return ctx.descriptor[type];
1211
- const types = rel === void 0 ? void 0 : ctx.descriptor[type]?.relations[rel]?.types;
1226
+ const relation = rel === void 0 ? void 0 : ctx.descriptor[type]?.relations[rel];
1227
+ if (relation?.filterable !== void 0 || relation?.filterFamilies !== void 0) return relation;
1228
+ const types = relation?.types;
1212
1229
  return types?.length === 1 ? ctx.descriptor[types[0]] : void 0;
1213
1230
  }
1214
1231
  /**
1232
+ * Whether a `relatedQuery` entry's filter key takes a list, matched against the vocabulary of the
1233
+ * relation its include path ends on, as that relation's related read matches it. A path through a
1234
+ * polymorphic relation continues from the first member type declaring the next relation.
1235
+ */
1236
+ function relatedListFilter(ctx, type) {
1237
+ const matchers = /* @__PURE__ */ new Map();
1238
+ return (path, key) => {
1239
+ if (!matchers.has(path)) matchers.set(path, listFilterMatcher(relatedQuerySpec(ctx, type, path)));
1240
+ return matchers.get(path)?.(key) ?? false;
1241
+ };
1242
+ }
1243
+ /** The filter vocabulary of the relation an include path from `type` ends on. */
1244
+ function relatedQuerySpec(ctx, type, path) {
1245
+ const names = path.split(".");
1246
+ let owners = [type];
1247
+ for (const [index, name] of names.entries()) {
1248
+ const owner = owners.find((t) => ctx.descriptor[t]?.relations[name] !== void 0);
1249
+ if (owner === void 0) return;
1250
+ if (index === names.length - 1) return filterSpec(ctx, owner, "fetchRelated", name);
1251
+ owners = ctx.descriptor[owner].relations[name].types;
1252
+ }
1253
+ }
1254
+ /** Whether a `relatedQuery` carries a filter or sort for any path, so it reaches the wire. */
1255
+ function sendsRelatedQuery(relatedQuery) {
1256
+ return Object.values(relatedQuery ?? {}).some((entry) => Object.keys(entry?.filter ?? {}).length > 0 || entry?.sort !== void 0 && entry.sort.length > 0);
1257
+ }
1258
+ /**
1215
1259
  * Add any profiles a query's parameters require to the request's negotiated `profiles`. A
1216
1260
  * `withCount` read needs the type's Countable profile in `Accept` — else the server rejects it
1217
1261
  * (400) under strict query-param validation. The profile URI is read from the descriptor's
1218
- * `countable` block (never hardcoded); absent when the type advertises no Countable profile.
1262
+ * `countable` block (never hardcoded); absent when the type advertises no Countable profile. A
1263
+ * `relatedQuery` on a collection or single read likewise adds the type's Relationship Queries
1264
+ * profile, after any Countable one.
1219
1265
  */
1220
1266
  function negotiateProfiles(ctx, type, query, req, relationForCount) {
1221
- if (query.withCount === void 0 || query.withCount.length === 0) return;
1222
- const profile = relationForCount !== void 0 ? ctx.descriptor[type]?.relations[relationForCount]?.countable?.profile : ctx.descriptor[type]?.countable?.profile;
1223
- if (profile !== void 0) req.profiles = [...req.profiles ?? [], profile];
1267
+ const profiles = [];
1268
+ if (query.withCount !== void 0 && query.withCount.length > 0) {
1269
+ const profile = relationForCount !== void 0 ? ctx.descriptor[type]?.relations[relationForCount]?.countable?.profile : ctx.descriptor[type]?.countable?.profile;
1270
+ if (profile !== void 0) profiles.push(profile);
1271
+ }
1272
+ if (relationForCount === void 0 && sendsRelatedQuery(query.relatedQuery)) {
1273
+ const profile = ctx.descriptor[type]?.relatedQuery?.profile;
1274
+ if (profile !== void 0 && !profiles.includes(profile)) profiles.push(profile);
1275
+ }
1276
+ if (profiles.length > 0) req.profiles = [...req.profiles ?? [], ...profiles];
1224
1277
  }
1225
1278
  /** Project a write's opts to the read-query families the response honours (`include`/`fields`). */
1226
1279
  function writeQuery(opts) {