@haddowg/json-api-client 1.31.0 → 1.32.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
@@ -595,7 +595,7 @@ function materialiseDocument(doc, ctx, linkage, primaryType, paginatorOverride)
595
595
  if (doc.jsonapi !== void 0) env.jsonapi = doc.jsonapi;
596
596
  if (doc.meta !== void 0) env.meta = doc.meta;
597
597
  if (doc.links !== void 0) env.links = doc.links;
598
- const index = buildIndex(doc.included);
598
+ const index = buildIndex(doc.included, linkage ? void 0 : doc.data);
599
599
  const nodes = /* @__PURE__ */ new Map();
600
600
  const build = (raw) => buildNode(raw, env, index, nodes, ctx);
601
601
  const data = doc.data;
@@ -610,11 +610,18 @@ function materialiseDocument(doc, ctx, linkage, primaryType, paginatorOverride)
610
610
  return build(raw);
611
611
  }
612
612
  }
613
- /** Index `included` by `type:id` so relationship linkage can be hydrated. */
614
- function buildIndex(included) {
613
+ /**
614
+ * Index `included` and the primary resources by `type:id` so relationship linkage can be hydrated.
615
+ * A server never repeats a primary resource in `included`, so a member that links back to one
616
+ * (`tracks.album` on an album) is found only among the primary data.
617
+ */
618
+ function buildIndex(included, primary) {
615
619
  const index = /* @__PURE__ */ new Map();
616
- if (!included) return index;
617
- for (const raw of included) if (isObject$2(raw) && typeof raw["type"] === "string" && typeof raw["id"] === "string") index.set(key(raw["type"], raw["id"]), raw);
620
+ const add = (raw) => {
621
+ if (isObject$2(raw) && typeof raw["type"] === "string" && typeof raw["id"] === "string") index.set(key(raw["type"], raw["id"]), raw);
622
+ };
623
+ for (const raw of included ?? []) add(raw);
624
+ for (const raw of Array.isArray(primary) ? primary : [primary]) add(raw);
618
625
  return index;
619
626
  }
620
627
  const key = (type, id) => `${type}:${id}`;
@@ -632,6 +639,8 @@ function buildNode(raw, env, index, nodes, ctx) {
632
639
  id: raw.id
633
640
  };
634
641
  nodes.set(id, node);
642
+ const cycleViews = [];
643
+ UNFINISHED.set(node, cycleViews);
635
644
  if (raw.attributes) for (const [k, v] of Object.entries(raw.attributes)) node[k] = v;
636
645
  const rels = raw.relationships ?? {};
637
646
  const resType = ctx.descriptor[raw.type];
@@ -641,8 +650,78 @@ function buildNode(raw, env, index, nodes, ctx) {
641
650
  node[name] = hydrateRelation(rel, relDesc?.cardinality, resolvePaginator(relatedPaginator(relDesc, ctx)), env, index, nodes, ctx);
642
651
  }
643
652
  attachResourceEnvelope(node, raw, env, rels, nestedFieldset(ctx.fields?.[raw.type]));
653
+ UNFINISHED.delete(node);
654
+ for (const view of cycleViews) readLateRelations(view, node);
644
655
  return node;
645
656
  }
657
+ /** Nodes still being built, each with the per-edge views a relation cycle copied of it so far. */
658
+ const UNFINISHED = /* @__PURE__ */ new WeakMap();
659
+ /** A back-reference's relations that read through to its node; a property, read on every walk. */
660
+ const LATE = Symbol("late relations");
661
+ /** Nodes some back-reference reads relations through to. */
662
+ const READ_THROUGH = /* @__PURE__ */ new WeakSet();
663
+ /**
664
+ * A relation cycle copied `view` of `node` before the node's later relations were set. Each one it
665
+ * missed reads the node's slot as linkage: the view sits past the end of its include path, and a
666
+ * hydrated value would close the cycle. Non-enumerable, so a spread, `JSON.stringify` and a cache
667
+ * walk meet no cycle.
668
+ */
669
+ function readLateRelations(view, node) {
670
+ const late = /* @__PURE__ */ new Set();
671
+ for (const name of Object.keys(node)) if (!Object.hasOwn(view, name)) {
672
+ late.add(name);
673
+ defineGetter(view, name, () => linkageOf(node[name]));
674
+ }
675
+ if (late.size > 0) {
676
+ Object.defineProperty(view, LATE, { value: late });
677
+ READ_THROUGH.add(node);
678
+ }
679
+ }
680
+ /** Each slot value's linkage, so a back-reference reads the same value until its node's changes. */
681
+ const LINKAGE = /* @__PURE__ */ new WeakMap();
682
+ /** A relation slot's value as linkage: identifier views, in an array keeping the slot's envelope. */
683
+ function linkageOf(slot) {
684
+ if (typeof slot !== "object" || slot === null) return slot;
685
+ if (LINKAGE.has(slot)) return LINKAGE.get(slot);
686
+ const value = Array.isArray(slot) ? withSlotEnvelope(slot, slot.map(identifierOf)) : identifierOf(slot);
687
+ LINKAGE.set(slot, value);
688
+ return value;
689
+ }
690
+ function identifierOf(member) {
691
+ if (!isObject$2(member) || typeof member["type"] !== "string" || typeof member["id"] !== "string") return member;
692
+ const meta = member.$edge?.meta;
693
+ return buildIdentifierView({
694
+ type: member["type"],
695
+ id: member["id"],
696
+ ...meta !== void 0 ? { meta } : {}
697
+ });
698
+ }
699
+ /** `members` carrying `slot`'s non-index members (`$page`, `$links`, `$next()` and the rest). */
700
+ function withSlotEnvelope(slot, members) {
701
+ for (const name of Reflect.ownKeys(slot)) if (name !== "length" && !(typeof name === "string" && /^\d+$/.test(name))) Object.defineProperty(members, name, Object.getOwnPropertyDescriptor(slot, name));
702
+ return members;
703
+ }
704
+ /**
705
+ * The relations of `view` that read through to its node as linkage (a back-reference a relation
706
+ * cycle built before the node's later relations were set), or `undefined`. A cache layer leaves
707
+ * these slots alone: they follow the node.
708
+ * @internal
709
+ */
710
+ function lateRelationsOf(view) {
711
+ return view[LATE];
712
+ }
713
+ /**
714
+ * Tell the client a cache layer wrote relation `name` of the cached copy `copy`: a node that
715
+ * back-references read the relation through to takes the value too, so they read it.
716
+ * @internal
717
+ */
718
+ function relationWritten(copy, name, value) {
719
+ let at = SOURCES.get(copy);
720
+ while (at !== void 0) {
721
+ if (READ_THROUGH.has(at)) at[name] = value;
722
+ at = SOURCES.get(at);
723
+ }
724
+ }
646
725
  /**
647
726
  * Resolve one relationship's value: an included member hydrates to a per-edge view, a
648
727
  * linked-but-not-included member stays an identifier, an empty to-one is `null`, and a
@@ -703,8 +782,10 @@ function attachResourceEnvelope(node, raw, env, rels, selection) {
703
782
  */
704
783
  function buildEdgeView(node, member, relationEdge, pick) {
705
784
  const view = {};
706
- if (pick === void 0) Object.assign(view, node);
707
- else for (const [k, v] of Object.entries(node)) if (k === "type" || k === "id" || pick(k)) view[k] = v;
785
+ if (pick === void 0) {
786
+ Object.assign(view, node);
787
+ UNFINISHED.get(node)?.push(view);
788
+ } else for (const [k, v] of Object.entries(node)) if (k === "type" || k === "id" || pick(k)) view[k] = v;
708
789
  SOURCES.set(view, node);
709
790
  for (const k of [
710
791
  "$meta",
@@ -714,8 +795,10 @@ function buildEdgeView(node, member, relationEdge, pick) {
714
795
  "$raw",
715
796
  "$nestedFieldset"
716
797
  ]) delegate(view, node, k);
717
- const rel = node.$rel;
718
- define(view, "$rel", typeof rel === "function" ? rel.bind(node) : () => void 0);
798
+ define(view, "$rel", (name) => {
799
+ const rel = node.$rel;
800
+ return typeof rel === "function" ? rel.call(node, name) : void 0;
801
+ });
719
802
  attachOverlayAccessors(view);
720
803
  attachEdgeEnvelope(view, member, false, relationEdge);
721
804
  return view;
@@ -2259,6 +2342,91 @@ async function loadAll(first, options = {}) {
2259
2342
  return all;
2260
2343
  }
2261
2344
  //#endregion
2262
- export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, CANONICAL_PAGE_KEYS, HANDLE_RESERVED, InputValidationError, JSON_API_MEDIA_TYPE, JsonApiError, PollTimeoutError, StructuralGuardError, assertJsonApiDocument, createClient, edgeViewOf, execute, executeRaw, executeResponse, fetchTransport, fieldErrors, findError, hasErrorCode, identifierViewOf, inputFailure, isAccepted, isActionLocation, isMaterialised, isPolymorphic, listFilterMatcher, loadAll, materialise, mediaType, nestedFieldset, nextPageParams, nextRequestStamp, parseRetryAfter, prevPageParams, readActionLocation, relatedPaginator, relatedPaginatorKind, remapPointer, remapRelationshipPointer, requestStampOf, resolvePaginator, resolveValidator, runAtomic, serializeQuery, setMaterialisedOverlay, sparseSchema, sparseSchemas, toDocument, toRelationshipDocument, validateDocument, withInputCheck, withRemappedAtomicPaths, withRemappedDocumentMetaPaths, withRemappedPaths, withRemappedRelationshipPaths, withTopLevelMeta };
2345
+ //#region src/mock.ts
2346
+ /** The members a linkage member carries beside its identity, which never become attributes. */
2347
+ const MEMBER_KEYS = /* @__PURE__ */ new Set([
2348
+ "type",
2349
+ "id",
2350
+ "meta",
2351
+ "$pivot"
2352
+ ]);
2353
+ /**
2354
+ * Build a materialised resource from its plain data, as a read returns it: the relations the data
2355
+ * nests hydrate, the identifiers stay identifiers, and each member's `$pivot` lands on its linkage
2356
+ * `meta.pivot`, so `$pivot`, `$edge`, `$rel` and `$count` all work. For tests and stories; the
2357
+ * generated client binds it to its descriptor and types it.
2358
+ */
2359
+ function mockResource(descriptor, data) {
2360
+ return materialise(mockDocument(descriptor, data), mockContext(descriptor));
2361
+ }
2362
+ /** {@link mockResource} for a collection of type `type`, as a list read returns it. */
2363
+ function mockCollection(descriptor, type, data) {
2364
+ return materialise(mockDocument(descriptor, data), mockContext(descriptor), false, type);
2365
+ }
2366
+ function mockContext(descriptor) {
2367
+ return {
2368
+ descriptor,
2369
+ navigate: () => Promise.reject(/* @__PURE__ */ new Error("A mock resource has no server to follow its links to."))
2370
+ };
2371
+ }
2372
+ /** The JSON:API document plain data stands for: the primary data, and every nested resource in `included`. */
2373
+ function mockDocument(descriptor, data) {
2374
+ const primary = /* @__PURE__ */ new Set();
2375
+ const included = /* @__PURE__ */ new Map();
2376
+ const toResource = (value) => {
2377
+ const relations = descriptor[value.type]?.relations ?? {};
2378
+ const attributes = {};
2379
+ const relationships = {};
2380
+ for (const [key, member] of Object.entries(value)) {
2381
+ if (key === "type" || key === "id") continue;
2382
+ if (key in relations) {
2383
+ if (member !== void 0) relationships[key] = { data: linkageOf(member) };
2384
+ } else if (key !== "meta" && key !== "$pivot") attributes[key] = member;
2385
+ }
2386
+ return {
2387
+ type: value.type,
2388
+ id: value.id,
2389
+ ...Object.keys(attributes).length > 0 ? { attributes } : {},
2390
+ ...Object.keys(relationships).length > 0 ? { relationships } : {},
2391
+ ...value["meta"] !== void 0 ? { meta: value["meta"] } : {}
2392
+ };
2393
+ };
2394
+ const linkageOf = (value) => {
2395
+ if (value === null) return null;
2396
+ if (Array.isArray(value)) return value.map((member) => identifierOf(member));
2397
+ return identifierOf(value);
2398
+ };
2399
+ const identifierOf = (member) => {
2400
+ const id = `${member.type}:${member.id}`;
2401
+ if (isFullResource(member) && !primary.has(id) && !included.has(id)) {
2402
+ included.set(id, {});
2403
+ included.set(id, toResource(member));
2404
+ }
2405
+ const pivot = member.$pivot;
2406
+ const meta = member["meta"];
2407
+ const linkageMeta = pivot === void 0 ? meta : {
2408
+ ...meta,
2409
+ pivot
2410
+ };
2411
+ return {
2412
+ type: member.type,
2413
+ id: member.id,
2414
+ ...linkageMeta !== void 0 ? { meta: linkageMeta } : {}
2415
+ };
2416
+ };
2417
+ const list = Array.isArray(data) ? data : [data];
2418
+ for (const value of list) primary.add(`${value.type}:${value.id}`);
2419
+ const resources = list.map(toResource);
2420
+ return {
2421
+ data: Array.isArray(data) ? resources : resources[0],
2422
+ ...included.size > 0 ? { included: [...included.values()] } : {}
2423
+ };
2424
+ }
2425
+ /** Whether a relation member carries more than its identity, so it stands for an included resource. */
2426
+ function isFullResource(member) {
2427
+ return Object.keys(member).some((key) => !MEMBER_KEYS.has(key));
2428
+ }
2429
+ //#endregion
2430
+ export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, CANONICAL_PAGE_KEYS, HANDLE_RESERVED, InputValidationError, JSON_API_MEDIA_TYPE, JsonApiError, PollTimeoutError, StructuralGuardError, assertJsonApiDocument, createClient, edgeViewOf, execute, executeRaw, executeResponse, fetchTransport, fieldErrors, findError, hasErrorCode, identifierViewOf, inputFailure, isAccepted, isActionLocation, isMaterialised, isPolymorphic, lateRelationsOf, listFilterMatcher, loadAll, materialise, mediaType, mockCollection, mockDocument, mockResource, nestedFieldset, nextPageParams, nextRequestStamp, parseRetryAfter, prevPageParams, readActionLocation, relatedPaginator, relatedPaginatorKind, relationWritten, remapPointer, remapRelationshipPointer, requestStampOf, resolvePaginator, resolveValidator, runAtomic, serializeQuery, setMaterialisedOverlay, sparseSchema, sparseSchemas, toDocument, toRelationshipDocument, validateDocument, withInputCheck, withRemappedAtomicPaths, withRemappedDocumentMetaPaths, withRemappedPaths, withRemappedRelationshipPaths, withTopLevelMeta };
2263
2431
 
2264
2432
  //# sourceMappingURL=index.mjs.map