@haddowg/json-api-client 1.33.0 → 1.33.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["isPlainObject","isObject","isObject"],"sources":["../src/request-stamp.ts","../src/types.ts","../src/request.ts","../src/accepted.ts","../src/pagination.ts","../src/materialise.ts","../src/input-validation.ts","../src/input-path.ts","../src/serialize-write.ts","../src/atomic.ts","../src/descriptor.ts","../src/filters.ts","../src/location.ts","../src/transport.ts","../src/client.ts","../src/field-errors.ts","../src/load-all.ts","../src/mock.ts"],"sourcesContent":["/**\n * Request stamps: when the request behind a result started, relative to every other request made in\n * this process.\n *\n * The client takes a stamp as each request starts and records it on the top-level value it\n * materialises from the response: a read's resource, collection or linkage (`$next()`/`$prev()`\n * pages included), a write's returned resource, and an atomic batch's results. A cache can then\n * tell which of two results carrying the same resource is the newer, whatever order their\n * responses arrived in.\n *\n * The stamp is a per-process counter rather than `Date.now()`: two requests started in the same\n * millisecond still get distinct, ordered stamps, and a clock change can't reorder them. It means\n * nothing outside the process that issued it, so a value that crossed one (through JSON on a server\n * render, or storage) carries none. Stamps live in a `WeakMap` keyed by the result, so the result\n * keeps its shape and nothing is added to it.\n *\n * @internal\n */\n\n/** The last stamp handed out; `0` is older than any request (no request is ever stamped `0`). */\nlet clock = 0\n\n/**\n * A new stamp, later than every stamp handed out before it. The client takes one as each request\n * starts; anything ordering its own events against the client's requests takes them here too.\n * @internal\n */\nexport function nextRequestStamp(): number {\n clock += 1\n return clock\n}\n\nconst stamps = new WeakMap<object, number>()\n\n/**\n * Record `stamp` as the start of the request `value` was materialised from, when it is an object.\n * Returns `value`.\n * @internal\n */\nexport function stampRequest<T>(value: T, stamp: number): T {\n if (typeof value === 'object' && value !== null) {\n stamps.set(value, stamp)\n }\n return value\n}\n\nconst documentStamps = new WeakMap<object, number>()\n\n/**\n * Record `stamp` on the response document it was parsed from, so whatever is built from the\n * document can be stamped without the caller carrying the number.\n * @internal\n */\nexport function stampDocument(doc: object | undefined, stamp: number): void {\n if (doc !== undefined) {\n documentStamps.set(doc, stamp)\n }\n}\n\n/**\n * Stamp `value` with the request stamp of `doc`, when `doc` carries one. Returns `value`.\n * @internal\n */\nexport function stampFromDocument<T>(doc: object | undefined, value: T): T {\n const stamp = doc === undefined ? undefined : documentStamps.get(doc)\n return stamp === undefined ? value : stampRequest(value, stamp)\n}\n\n/**\n * The stamp of the request `value` was materialised from: a top-level result the client returned.\n * `undefined` for anything else, such as a plain copy of a result, a nested resource, or data the\n * client never returned.\n * @internal\n */\nexport function requestStampOf(value: unknown): number | undefined {\n return typeof value === 'object' && value !== null ? stamps.get(value) : undefined\n}\n","/** The JSON:API media type. */\nexport const JSON_API_MEDIA_TYPE = 'application/vnd.api+json'\n\n/** The Atomic Operations extension URI. */\nexport const ATOMIC_EXT = 'https://jsonapi.org/ext/atomic'\n\n/**\n * The media-type parameters a request opts into: extension URIs (`ext`) and/or profile URIs\n * (`profile`). Each is rendered as a space-joined, quoted media-type parameter per RFC 6839 /\n * the JSON:API spec (`ext=\"<uri> <uri>\"`, `profile=\"<uri> <uri>\"`).\n */\nexport interface MediaTypeParams {\n ext?: readonly string[] | undefined\n profiles?: readonly string[] | undefined\n}\n\n/**\n * Compose the JSON:API media type with any opted-in `ext`/`profile` parameters. Each parameter\n * is a space-joined, double-quoted URI list, in the canonical order `ext` then `profile` so the\n * output is deterministic (stable for caching/assertions). Empty/absent lists are omitted; with\n * neither, the bare {@link JSON_API_MEDIA_TYPE} is returned (no behaviour change for a plain\n * request). Used for both `Accept` and (when a body is present) `Content-Type`.\n */\nexport function mediaType(params: MediaTypeParams = {}): string {\n let out = JSON_API_MEDIA_TYPE\n if (params.ext !== undefined && params.ext.length > 0) {\n out += `; ext=\"${params.ext.join(' ')}\"`\n }\n if (params.profiles !== undefined && params.profiles.length > 0) {\n out += `; profile=\"${params.profiles.join(' ')}\"`\n }\n return out\n}\n\n/**\n * The media type for an Atomic Operations request/response: the JSON:API media type carrying\n * the atomic `ext` parameter. Sent as both `Content-Type` and `Accept` on a `client.atomic`\n * batch (per the JSON:API atomic extension).\n */\nexport const ATOMIC_MEDIA_TYPE = mediaType({ ext: [ATOMIC_EXT] })\n\n/** A resource identifier: the shape a non-included but linked relation takes. */\nexport interface ResourceIdentifier<TType extends string = string> {\n type: TType\n id: string\n meta?: Record<string, unknown>\n}\n\n/** A local id reference used inside an atomic transaction (`{ type, lid }`). */\nexport interface LocalIdentifier<TType extends string = string> {\n type: TType\n lid: string\n}\n","import type { HeadersInit } from './client'\nimport { JsonApiError, type JsonApiErrorObject } from './errors'\nimport type {\n JsonApiTransport,\n TransportRawBody,\n TransportRequest,\n TransportResponse,\n} from './transport'\nimport { nextRequestStamp, stampDocument } from './request-stamp'\nimport { mediaType } from './types'\n\n/**\n * A read query, in the flat shape the fluent surface accepts. Serialised to the\n * JSON:API bracketed query-parameter families by {@link serializeQuery}.\n */\nexport interface ReadQuery {\n filter?: Record<string, unknown>\n sort?: string | string[]\n include?: string[]\n fields?: Record<string, string[]>\n /** Relationship-count tokens (the Countable profile) — serialised comma-joined onto `withCount`. */\n withCount?: readonly string[]\n /**\n * A `filter` and `sort` per relation (the Relationship Queries profile), serialised as\n * `relatedQuery[<relation>][filter][<key>]` and `relatedQuery[<relation>][sort]`.\n */\n relatedQuery?: Readonly<\n Record<\n string,\n { filter?: Readonly<Record<string, unknown>>; sort?: string | readonly string[] } | undefined\n >\n >\n page?: Record<string, unknown>\n /** Cancels the read when signalled. Never serialised; passed to the transport. */\n signal?: AbortSignal\n}\n\n/** A loose JSON:API document — enough structure for the runtime to materialise. */\nexport interface Document {\n data?: unknown\n included?: unknown[]\n links?: Record<string, unknown>\n meta?: Record<string, unknown>\n jsonapi?: Record<string, unknown>\n}\n\n/** The ambient context a request executes in (carried by the client). */\nexport interface JsonApiContext {\n baseUrl: string\n transport: JsonApiTransport\n headers?: () => HeadersInit | Promise<HeadersInit>\n /** Follow server links to another origin, without {@link headers}. Off by default. */\n allowCrossOriginLinks?: boolean\n}\n\n/** A single read/write request, before serialisation. */\nexport interface JsonApiRequest {\n method: string\n /**\n * A path appended to `baseUrl` (a filled path template such as `/albums/1`), or an absolute\n * `http(s)://` URL. With {@link link} set, a link from the server instead.\n */\n path: string\n /**\n * `path` is a link the server sent (a `links` member such as `next`, or a `Location` header).\n * It resolves against `baseUrl` per RFC 3986, so a root-relative `/api/v5/albums?page[number]=2`\n * keeps the base's origin but not its path, where a path template is appended to the base.\n */\n link?: boolean\n query?: ReadQuery\n /**\n * The filter keys of {@link query} that take a list, sent as `filter[<key>][]` once per member.\n * The client sets it from the descriptor; without it an array filter value is comma-joined.\n */\n listFilter?: (key: string) => boolean\n /**\n * The filter keys of a {@link ReadQuery.relatedQuery} entry that take a list, by the entry's\n * relation. The client sets it from that relation's related-read vocabulary.\n */\n relatedListFilter?: (relation: string, key: string) => boolean\n body?: unknown\n /**\n * Override the request `Content-Type`, which defaults to the negotiated JSON:API media type on\n * every `POST` and on any other request with a body. Set for a custom action's non-JSON:API\n * input. When set it wins over {@link ext}/{@link profiles} for `Content-Type`; `null` sends\n * none, so the transport can write a multipart body's boundary itself.\n */\n contentType?: string | null\n /**\n * Override the request `Accept` header (defaults to the negotiated JSON:API media type). Set\n * for a `raw`-input action that still expects a document response; when set it wins over\n * {@link ext}/{@link profiles} for `Accept`.\n */\n accept?: string\n /**\n * Extension URIs to negotiate (the media-type `ext` parameter), e.g. the atomic ext. Composed\n * into both `Accept` and (when a body is present) `Content-Type` via the JSON:API media type,\n * unless {@link accept}/{@link contentType} override the respective header.\n */\n ext?: readonly string[]\n /**\n * Profile URIs to negotiate (the media-type `profile` parameter), e.g. the Countable profile a\n * `withCount` read requires. Composed into both `Accept` and (when a body is present)\n * `Content-Type`, unless {@link accept}/{@link contentType} override the respective header.\n */\n profiles?: readonly string[]\n /**\n * Send the body verbatim instead of JSON-stringifying it: a string, or a binary, `FormData` or\n * `URLSearchParams` body. Used for a custom action's non-JSON:API input; any other value still\n * falls back to `JSON.stringify`.\n */\n raw?: boolean\n /** Passed through to the transport so the caller can cancel the request. */\n signal?: AbortSignal\n}\n\nconst isAbsolute = (path: string): boolean => /^https?:\\/\\//i.test(path)\n\n// Stands in for the origin when `baseUrl` is relative and there's no page to resolve it against.\nconst RELATIVE_ORIGIN = 'http://relative.invalid'\n\n/** A server link resolved for following, and whether it stays on the base URL's origin. */\ninterface ResolvedLink {\n url: string\n sameOrigin: boolean\n}\n\n/**\n * Resolve a server link against `baseUrl` per RFC 3986 and check where it lands. A link on the\n * base's origin is followed; a relative base (e.g. `/api`) takes the page's origin in a browser and\n * otherwise only accepts a link that keeps the host. Anything that isn't plain http(s) is refused.\n */\nfunction resolveLink(link: string, baseUrl: string): ResolvedLink {\n // The URL parser drops tabs and newlines and trims control characters, so check what it sees.\n let normalised = link.replace(/[\\t\\n\\r]/g, '')\n let start = 0\n while (start < normalised.length && normalised.charCodeAt(start) <= 0x20) start++\n normalised = normalised.slice(start)\n const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalised)?.[1]?.toLowerCase()\n if (scheme !== undefined && scheme !== 'http' && scheme !== 'https') {\n throw new Error(`Refusing to follow link \"${link}\": only http(s) links are followed`)\n }\n\n const relativeBase = !isAbsolute(baseUrl)\n const page = (globalThis as { location?: { href?: unknown } }).location?.href\n const base = new URL(\n baseUrl,\n relativeBase ? (typeof page === 'string' ? page : RELATIVE_ORIGIN) : undefined,\n )\n const resolved = new URL(link, base)\n // `https:host` names a scheme without `//`, which the parser may read as a path or a host.\n const sameOrigin =\n resolved.origin === base.origin && (scheme === undefined || /^https?:\\/\\//i.test(normalised))\n\n if (!sameOrigin) {\n return { url: resolved.href, sameOrigin }\n }\n return {\n url: relativeBase ? resolved.pathname + resolved.search + resolved.hash : resolved.href,\n sameOrigin,\n }\n}\n\nconst append = (parts: string[], key: string, value: unknown): void => {\n if (value === undefined || value === null || value === '') {\n return\n }\n parts.push(`${key}=${encodeURIComponent(String(value))}`)\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Append a filter value under its (already-bracketed) key. A plain object is a STRUCTURED filter\n * value — a `Range`/`DateRange` deepObject (`{ min, max }`) — and recurses into nested bracketed\n * keys (`filter[k][min]=`), matching the server's deepObject wire shape; an array goes out once per\n * member as `filter[k][]=` for a filter that takes a list, so a member may hold a comma, and joins\n * with `,` otherwise; a scalar is appended directly. Without the object branch a `{ min, max }` value would reach the\n * wire as `filter[k]=[object Object]` and be silently ignored by the server.\n */\nconst appendFilterValue = (parts: string[], key: string, value: unknown, list = false): void => {\n if (isPlainObject(value)) {\n for (const [subKey, subValue] of Object.entries(value)) {\n appendFilterValue(parts, `${key}[${subKey}]`, subValue)\n }\n return\n }\n if (list && Array.isArray(value)) {\n for (const member of value) {\n append(parts, `${key}[]`, member)\n }\n return\n }\n append(parts, key, Array.isArray(value) ? value.join(',') : value)\n}\n\n/**\n * Serialise a read query to a query string (no leading `?`). Bracketed keys\n * (`filter[title]`, `page[number]`, `fields[albums]`) are kept literal; only values\n * are percent-encoded. `isListFilter` names the filter keys that take a list, whose array value\n * goes out as `filter[<key>][]` once per member, and `isRelatedListFilter` does the same for a\n * `relatedQuery` entry's filters by relation. Empty/undefined entries are skipped; key order is deterministic\n * (family order, then insertion order within a family) so URLs are stable for caching.\n */\nexport function serializeQuery(\n query: ReadQuery,\n isListFilter?: (key: string) => boolean,\n isRelatedListFilter?: (relation: string, key: string) => boolean,\n): string {\n const parts: string[] = []\n\n if (query.filter) {\n for (const [key, value] of Object.entries(query.filter)) {\n appendFilterValue(parts, `filter[${key}]`, value, isListFilter?.(key) ?? false)\n }\n }\n\n if (query.sort !== undefined) {\n append(parts, 'sort', Array.isArray(query.sort) ? query.sort.join(',') : query.sort)\n }\n\n if (query.include) {\n append(parts, 'include', query.include.join(','))\n }\n\n if (query.fields) {\n for (const [type, names] of Object.entries(query.fields)) {\n // An explicitly-empty fieldset (`fields[type]=`) is meaningful in JSON:API — it selects NO\n // members of that type (id-only), which is exactly what the return type narrows to. Emit the\n // empty param verbatim (the generic empty-skip would drop it, leaving the type over-narrowed\n // vs. the full resource the server would otherwise return).\n parts.push(`fields[${type}]=${encodeURIComponent(names.join(','))}`)\n }\n }\n\n if (query.withCount && query.withCount.length > 0) {\n append(parts, 'withCount', query.withCount.join(','))\n }\n\n for (const [relation, entry] of Object.entries(query.relatedQuery ?? {})) {\n for (const [key, value] of Object.entries(entry?.filter ?? {})) {\n appendFilterValue(\n parts,\n `relatedQuery[${relation}][filter][${key}]`,\n value,\n isRelatedListFilter?.(relation, key) ?? false,\n )\n }\n if (entry?.sort !== undefined) {\n append(\n parts,\n `relatedQuery[${relation}][sort]`,\n typeof entry.sort === 'string' ? entry.sort : entry.sort.join(','),\n )\n }\n }\n\n if (query.page) {\n for (const [key, value] of Object.entries(query.page)) {\n append(parts, `page[${key}]`, Array.isArray(value) ? value.join(',') : value)\n }\n }\n\n return parts.join('&')\n}\n\n/**\n * Execute a request: build the URL (a server link resolved against `baseUrl` and held to its\n * origin, an absolute path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request headers,\n * then drive the transport. A 2xx with a body parses to a {@link Document}; an empty /\n * 204 body resolves to `undefined`. A non-2xx throws a {@link JsonApiError} carrying the\n * parsed error objects (tolerating a non-JSON error body with an empty list).\n */\nexport async function execute(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n): Promise<Document | undefined> {\n const stamp = nextRequestStamp()\n const res = await send(ctx, req)\n const doc = parseDocument(res.body)\n stampDocument(doc, stamp)\n return doc\n}\n\n/** A response's status and headers beside its parsed {@link Document}. */\nexport interface ExecutedResponse {\n status: number\n headers: Record<string, string>\n document: Document | undefined\n /** The stamp taken as the request started; the document carries it too. */\n stamp: number\n}\n\n/**\n * Execute a request as {@link execute} does, keeping the response's status and headers. With\n * `seeOther`, a `303` the transport didn't follow resolves with no document instead of throwing,\n * so the caller can read its `Location`.\n */\nexport async function executeResponse(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n seeOther = false,\n): Promise<ExecutedResponse> {\n const stamp = nextRequestStamp()\n const res = await send(ctx, req, undefined, seeOther)\n const document = res.status === 303 ? undefined : parseDocument(res.body)\n stampDocument(document, stamp)\n return { status: res.status, headers: res.headers, document, stamp }\n}\n\n/** How {@link executeRaw} reads a successful response body. */\nexport type RawResponseType = 'text' | 'blob' | 'arraybuffer'\n\n/**\n * Execute a request whose successful response is not JSON:API, such as a custom action's CSV\n * export or image, and return its body as text or binary. Everything else matches\n * {@link execute}: the same URL, headers and negotiation, and a non-2xx still throws a\n * {@link JsonApiError} parsed from the JSON:API error document. A `204` or empty text body\n * resolves to `undefined`.\n */\nexport async function executeRaw(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n as: 'blob' | 'arraybuffer',\n): Promise<Blob | ArrayBuffer | undefined>\nexport async function executeRaw(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n as: 'text',\n): Promise<string | undefined>\nexport async function executeRaw(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n as: RawResponseType,\n): Promise<string | Blob | ArrayBuffer | undefined> {\n const res = await send(ctx, req, as === 'text' ? undefined : as)\n if (as === 'text') {\n return res.body === '' ? undefined : res.body\n }\n if (res.status === 204) {\n return undefined\n }\n if (res.binary === undefined) {\n throw new Error(\n '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.',\n )\n }\n return res.binary\n}\n\n/**\n * Build the URL (a server link resolved against `baseUrl` and held to its origin, an absolute\n * path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request\n * headers, then drive the transport. A non-2xx throws a {@link JsonApiError} carrying the parsed\n * error objects (tolerating a non-JSON error body with an empty list).\n */\nasync function send(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n responseType?: 'blob' | 'arraybuffer',\n seeOther = false,\n): Promise<TransportResponse> {\n let url: string\n let sendHeaders = true\n if (req.link) {\n const link = resolveLink(req.path, ctx.baseUrl)\n if (!link.sameOrigin && ctx.allowCrossOriginLinks !== true) {\n throw new Error(\n `Refusing to follow link \"${req.path}\": it leaves the base URL's origin (set allowCrossOriginLinks to follow it without the configured headers)`,\n )\n }\n url = link.url\n sendHeaders = link.sameOrigin\n } else {\n url = isAbsolute(req.path) ? req.path : ctx.baseUrl + req.path\n }\n if (req.query) {\n const qs = serializeQuery(req.query, req.listFilter, req.relatedListFilter)\n if (qs) {\n url += (url.includes('?') ? '&' : '?') + qs\n }\n }\n\n // Compose the negotiated media type (`application/vnd.api+json` + any opted-in ext/profile\n // parameters) once; a bare request yields the plain JSON:API media type. An explicit\n // `accept`/`contentType` override wins over the negotiated value for its header.\n const negotiated = mediaType({ ext: req.ext, profiles: req.profiles })\n const headers: Record<string, string> = { Accept: req.accept ?? negotiated }\n\n const transportReq: TransportRequest = { method: req.method, url, headers }\n if (req.signal !== undefined) {\n transportReq.signal = req.signal\n }\n if (responseType !== undefined) {\n transportReq.responseType = responseType\n }\n // A JSON:API server answers 415 to a POST without the JSON:API Content-Type, even with no body.\n if (req.body !== undefined || req.method.toUpperCase() === 'POST') {\n const contentType = req.contentType === undefined ? negotiated : req.contentType\n if (contentType !== null) {\n headers['Content-Type'] = contentType\n }\n }\n if (typeof req.body === 'string' && req.raw) {\n transportReq.body = req.body\n } else if (req.raw && isRawBody(req.body)) {\n transportReq.rawBody = req.body\n } else if (req.body !== undefined) {\n transportReq.body = JSON.stringify(req.body)\n }\n\n if (ctx.headers && sendHeaders) {\n mergeHeaders(headers, await ctx.headers())\n }\n\n const res = await ctx.transport(transportReq)\n\n if ((res.status >= 200 && res.status < 300) || (seeOther && res.status === 303)) {\n return res\n }\n\n throw new JsonApiError(res.status, parseErrors(res.body))\n}\n\n/** Whether a raw body goes to the transport as is rather than through `JSON.stringify`. */\nfunction isRawBody(body: unknown): body is TransportRawBody {\n return (\n (typeof Blob !== 'undefined' && body instanceof Blob) ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) ||\n (typeof FormData !== 'undefined' && body instanceof FormData) ||\n (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams)\n )\n}\n\n/**\n * Merge a `HeadersInit` (object / tuple array / `Headers`) into the outgoing map,\n * preserving the caller's casing (unlike the WHATWG `Headers`, which lowercases). The\n * caller's headers override the runtime defaults, so per-request `Accept` etc. can win.\n */\nfunction mergeHeaders(into: Record<string, string>, extra: HeadersInit): void {\n if (extra instanceof Headers) {\n extra.forEach((value, key) => {\n into[key] = value\n })\n } else if (Array.isArray(extra)) {\n for (const [key, value] of extra) {\n if (key !== undefined && value !== undefined) {\n into[key] = String(value)\n }\n }\n } else {\n for (const [key, value] of Object.entries(extra)) {\n into[key] = String(value)\n }\n }\n}\n\nfunction parseDocument(body: string): Document | undefined {\n if (body === '') {\n return undefined\n }\n return JSON.parse(body) as Document\n}\n\nfunction parseErrors(body: string): JsonApiErrorObject[] {\n if (body === '') {\n return []\n }\n try {\n const doc = JSON.parse(body) as { errors?: JsonApiErrorObject[] }\n return Array.isArray(doc.errors) ? doc.errors : []\n } catch {\n return []\n }\n}\n","import {\n type Document,\n executeResponse,\n type ExecutedResponse,\n type JsonApiContext,\n} from './request'\n\n/** Options for waiting on an accepted write: `wait` on the call, or {@link Accepted.$poll}. */\nexport interface PollOptions {\n /**\n * How long to keep polling, in milliseconds, before rejecting with a {@link PollTimeoutError}.\n * Defaults to five minutes.\n */\n timeout?: number\n /** Stops polling when signalled. The call rejects with the signal's reason, as a request does. */\n signal?: AbortSignal\n}\n\n/**\n * A write the server accepted for later (`202 Accepted`). `Job` is the job it answered with,\n * `Result` what the write resolves to once the job is done, and `Meta` the job document's\n * top-level `meta`.\n */\nexport interface Accepted<Job, Result = unknown, Meta = Record<string, unknown> | undefined> {\n /**\n * The job, materialised as its type's resource, or the document's top-level `meta` when the\n * server answered with a meta-only document.\n */\n readonly job: Job\n /** The `202` document's top-level `meta`, typed with the members the operation declares. */\n readonly meta: Meta\n /** The job URL, from `Content-Location`, which {@link $poll} reads until the job is done. */\n readonly contentLocation: string\n /**\n * How long the server asks the client to wait before polling, in seconds, from `Retry-After`. An\n * HTTP date is counted from when the response arrived. Absent when the server sent none.\n */\n readonly retryAfter: number | undefined\n /** Poll the job URL until the job is done, and resolve to what the write returns. */\n $poll(options?: PollOptions): Promise<Result>\n}\n\n/** Thrown when a job is still pending when the poll's timeout runs out. */\nexport class PollTimeoutError extends Error {\n readonly contentLocation: string\n readonly timeout: number\n\n constructor(contentLocation: string, timeout: number) {\n super(`The job at ${contentLocation} was still pending after ${timeout}ms`)\n this.name = 'PollTimeoutError'\n this.contentLocation = contentLocation\n this.timeout = timeout\n }\n}\n\nconst ACCEPTED = Symbol.for('@haddowg/json-api-client/accepted')\n\n/** Whether a write's result is an {@link Accepted} job rather than its normal result. */\nexport function isAccepted(value: unknown): value is Accepted<unknown, unknown> {\n return typeof value === 'object' && value !== null && ACCEPTED in value\n}\n\nconst DEFAULT_TIMEOUT = 5 * 60 * 1000\nconst DEFAULT_INTERVAL = 1000\n\n/** How the client reads and finishes one accepted write. */\nexport interface AcceptedTarget {\n readonly request: JsonApiContext\n readonly jobType: string\n /** Shape the job's materialised document (or `meta`) for {@link Accepted.job}. */\n readonly job: (doc: Document | undefined) => unknown\n /** Shape the finished response into what the write returns. */\n readonly complete: (doc: Document | undefined) => unknown\n}\n\n/** A response header by name, whatever case the transport wrote it in. */\nfunction header(headers: Record<string, string>, name: string): string | undefined {\n const wanted = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === wanted) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * A `Retry-After` value in seconds: delta-seconds as sent, an HTTP date as the seconds left until\n * it, rounded up and never negative. `undefined` when absent or unreadable.\n */\nexport function parseRetryAfter(value: string | undefined, now = Date.now()): number | undefined {\n const trimmed = value?.trim()\n if (trimmed === undefined || trimmed === '') {\n return undefined\n }\n if (/^\\d+$/.test(trimmed)) {\n return Number(trimmed)\n }\n const at = Date.parse(trimmed)\n return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - now) / 1000))\n}\n\n/** Whether a document is a meta-only one: no primary `data` member. */\nconst isMetaOnly = (doc: Document | undefined): boolean => doc === undefined || !('data' in doc)\n\n/** The `type` of a document's single primary resource, if it has one. */\nfunction primaryType(doc: Document | undefined): unknown {\n const data = doc?.data\n return typeof data === 'object' && data !== null && !Array.isArray(data)\n ? (data as Record<string, unknown>)['type']\n : undefined\n}\n\n/** Build the {@link Accepted} for a `202` response. */\nexport function toAccepted(\n target: AcceptedTarget,\n res: ExecutedResponse,\n): Accepted<unknown, unknown, unknown> {\n const contentLocation = header(res.headers, 'Content-Location')\n if (contentLocation === undefined) {\n throw new Error('The server answered 202 Accepted without a Content-Location to poll.')\n }\n const metaJob = isMetaOnly(res.document)\n const retryAfter = parseRetryAfter(header(res.headers, 'Retry-After'))\n const value = {\n job: target.job(res.document),\n contentLocation,\n retryAfter,\n }\n Object.defineProperty(value, ACCEPTED, { value: true, enumerable: false })\n Object.defineProperty(value, 'meta', { value: res.document?.meta, enumerable: false })\n Object.defineProperty(value, '$poll', {\n value: (options?: PollOptions) => poll(target, contentLocation, metaJob, retryAfter, options),\n enumerable: false,\n })\n return value as Accepted<unknown, unknown, unknown>\n}\n\n/**\n * Poll the job URL. A `2xx` still holding the job (its type, or a meta-only document for a\n * meta-only job) is pending: wait for its `Retry-After`, else the `202`'s, else a second. A `303`\n * the transport didn't follow is done, and its `Location` is fetched; any other `2xx` is the\n * redirect already followed. A non-2xx throws the usual {@link JsonApiError}.\n */\nasync function poll(\n target: AcceptedTarget,\n contentLocation: string,\n metaJob: boolean,\n acceptedRetryAfter: number | undefined,\n options: PollOptions = {},\n): Promise<unknown> {\n const timeout = options.timeout ?? DEFAULT_TIMEOUT\n const signal = options.signal\n const deadline = Date.now() + timeout\n const get = (path: string, seeOther: boolean) =>\n executeResponse(\n target.request,\n { method: 'GET', path, link: true, ...(signal !== undefined ? { signal } : {}) },\n seeOther,\n )\n const holdsJob = (doc: Document | undefined): boolean =>\n doc !== undefined && (primaryType(doc) === target.jobType || (metaJob && isMetaOnly(doc)))\n\n let delay = (acceptedRetryAfter ?? DEFAULT_INTERVAL / 1000) * 1000\n for (;;) {\n const remaining = deadline - Date.now()\n if (remaining <= 0) {\n throw new PollTimeoutError(contentLocation, timeout)\n }\n // A Retry-After past the deadline still gets one last poll at the deadline.\n await sleep(Math.min(delay, remaining), signal)\n const res = await get(contentLocation, true)\n if (res.status === 303) {\n const location = header(res.headers, 'Location')\n if (location === undefined) {\n throw new Error(`The job at ${contentLocation} answered 303 without a Location.`)\n }\n return target.complete((await get(location, false)).document)\n }\n if (!holdsJob(res.document)) {\n return target.complete(res.document)\n }\n const retryAfter = parseRetryAfter(header(res.headers, 'Retry-After')) ?? acceptedRetryAfter\n delay = (retryAfter ?? DEFAULT_INTERVAL / 1000) * 1000\n }\n}\n\n/** Resolve after `ms`, or reject with the signal's reason when it aborts first. */\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason)\n return\n }\n const onAbort = () => {\n clearTimeout(timer)\n reject(signal!.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n","/**\n * Pagination: resolving which strategy answers a read (runtime) and typing a read's `page`\n * parameter and `$page` from the descriptor (compile time). Both follow the paginator the\n * server advertises: a bare kind (canonical wire keys), a strategy with renamed keys, or a\n * MultiPaginator menu the client picks from by `kind`.\n */\nimport type {\n MenuDescriptor,\n PaginatorDescriptor,\n PaginatorKind,\n PaginatorRole,\n PaginatorStrategy,\n StrategyDescriptor,\n} from './descriptor'\n\n/** The wire key for each role when the server keeps the default names. */\nexport const CANONICAL_PAGE_KEYS = {\n page: { number: 'number', size: 'size' },\n offset: { offset: 'offset', limit: 'limit' },\n cursor: { after: 'after', before: 'before', size: 'size' },\n fixed: { number: 'number' },\n none: {},\n} as const satisfies Record<PaginatorKind, Partial<Record<PaginatorRole, string>>>\n\n/** Role -> wire key for the strategy that answered. */\nexport type PageKeys = Readonly<Partial<Record<PaginatorRole, string>>>\n\n/** The strategy that answers one read, with its wire keys and, for a menu pick, the arm's `kind`. */\nexport interface ResolvedPaginator {\n kind: PaginatorKind\n keys: PageKeys\n /** The menu arm the request picked with `page[kind]`. Absent when it picked none (the default). */\n arm?: string\n}\n\n/**\n * Resolve the strategy that answers a read from the endpoint's paginator and the `page` the\n * request sends. A menu answers with the arm named by `page.kind`, else its `default`.\n */\nexport function resolvePaginator(\n paginator: PaginatorDescriptor | undefined,\n page?: Readonly<Record<string, unknown>>,\n): ResolvedPaginator {\n if (paginator === undefined) {\n return { kind: 'none', keys: {} }\n }\n if (typeof paginator === 'string') {\n return { kind: paginator, keys: CANONICAL_PAGE_KEYS[paginator] }\n }\n if (paginator.strategy !== 'multi') {\n return { kind: paginator.strategy, keys: paginator.keys }\n }\n const picked = page?.['kind']\n const arm =\n typeof picked === 'string' && Object.hasOwn(paginator.arms, picked) ? picked : undefined\n const resolved = resolvePaginator(paginator.arms[arm ?? paginator.default])\n return arm === undefined ? resolved : { ...resolved, arm }\n}\n\n/** Navigation links by relation (`first`/`prev`/`next`/`last`), when present. */\nexport interface PageLinks {\n first?: string\n prev?: string\n next?: string\n last?: string\n}\n\n/** Normalised pagination state on a collection, as the runtime builds it; count-free-safe. */\nexport interface Page {\n kind: PaginatorKind\n /** Role -> wire key for the strategy that answered. */\n keys: PageKeys\n /** The menu arm the request picked with `page[kind]`, when it picked one. */\n arm?: string\n /** The raw `meta.page` block, when present (shape varies by kind). */\n meta?: Record<string, unknown>\n links: PageLinks\n}\n\n/**\n * The `meta.page` block each built-in strategy renders. `total`/`lastPage` (and `to` on an empty\n * page) are absent when the server does not count.\n */\nexport type PageMeta<K extends PaginatorKind> = K extends 'page'\n ? {\n currentPage: number\n perPage: number\n from: number\n to?: number\n total?: number\n lastPage?: number\n }\n : K extends 'fixed'\n ? { currentPage: number; total?: number; lastPage?: number }\n : K extends 'offset'\n ? { offset: number; limit: number; from: number; to?: number; total?: number }\n : K extends 'cursor'\n ? { perPage: number; from?: string; to?: string; hasMore: boolean }\n : Record<string, unknown>\n\n/** `$page` typed by the strategy `K` that answers, its wire keys and the picked menu arm. */\nexport type TypedPage<\n K extends PaginatorKind,\n Keys extends PageKeys,\n Arm extends string | undefined = undefined,\n> = {\n kind: K\n keys: Keys\n meta?: PageMeta<K>\n links: PageLinks\n} & (Arm extends string ? { arm: Arm } : { arm?: never })\n\n/** A non-menu paginator entry as `{ strategy, keys }` (a bare kind takes the canonical keys). */\ntype StrategyOf<P> = P extends PaginatorKind\n ? { strategy: P; keys: (typeof CANONICAL_PAGE_KEYS)[P] }\n : P extends StrategyDescriptor\n ? P\n : never\n\n/** Cursors are opaque strings; every other role is a count. */\ntype RoleValue<R> = R extends 'after' | 'before' ? string : number\n\n/** The page members one strategy accepts, keyed by their wire names. */\ntype StrategyParams<S> = S extends { keys: infer K }\n ? { -readonly [R in keyof K as K[R] extends string ? K[R] : never]?: RoleValue<R> }\n : never\n\n/** True when `P` is the loose `PaginatorDescriptor` union rather than a generated literal. */\ntype IsLoose<P> = [PaginatorKind] extends [P] ? true : false\n\ntype ArmName<M extends MenuDescriptor> = Extract<keyof M['arms'], string>\n\ntype ArmParams<M extends MenuDescriptor, A> =\n A extends ArmName<M> ? { kind: A } & StrategyParams<StrategyOf<M['arms'][A]>> : never\n\ntype KeysOfUnion<U> = U extends unknown ? keyof U : never\n\n/**\n * The default arm's members without `kind`. Members only another arm reads are `never`: the\n * server would select that arm by them, while the response is typed as the default.\n */\ntype DefaultArmParams<M extends MenuDescriptor> = StrategyParams<\n StrategyOf<M['arms'][M['default']]>\n> & { kind?: undefined } & {\n [X in Exclude<\n KeysOfUnion<StrategyParams<StrategyOf<M['arms'][ArmName<M>]>>>,\n keyof StrategyParams<StrategyOf<M['arms'][M['default']]>>\n >]?: never\n}\n\n/**\n * The `page` parameter an endpoint with paginator `P` accepts: its strategy's members under\n * their wire keys (numbers, cursors as strings). A menu takes one arm tagged by `kind`, or the\n * default arm's members untagged. `never` for an unpaginated endpoint; a loose record when the\n * descriptor is not a generated literal.\n */\nexport type PageParams<P> =\n IsLoose<P> extends true\n ? Readonly<Record<string, unknown>>\n : P extends 'none'\n ? never\n : P extends MenuDescriptor\n ? ArmParams<P, ArmName<P>> | DefaultArmParams<P>\n : StrategyParams<StrategyOf<P>>\n\n/** The member of page parameter union `P` that argument `Q` selects by its `kind`, if any. */\ntype SelectedArm<Q, P> = Q extends { kind: infer K }\n ? Extract<P, { kind: K }>\n : Extract<P, { kind?: undefined }>\n\n/**\n * A page argument `Q` with any member outside the arm it selects turned into `never`, so a typo,\n * or another arm's member, is an error.\n */\nexport type ExactPageParams<Q, P> = Q & {\n [K in Exclude<\n keyof Q,\n KeysOfUnion<[SelectedArm<Q, P>] extends [never] ? P : SelectedArm<Q, P>>\n >]: never\n}\n\ntype StrategyPage<S, Arm extends string | undefined = undefined> = S extends {\n strategy: infer K extends PaginatorStrategy\n keys: infer Keys extends PageKeys\n}\n ? TypedPage<K, Keys, Arm>\n : Page\n\ntype MenuPage<M extends MenuDescriptor, Q> = [Q] extends [never]\n ? StrategyPage<StrategyOf<M['arms'][M['default']]>>\n : Q extends { kind: infer A extends ArmName<M> }\n ? StrategyPage<StrategyOf<M['arms'][A]>, A>\n : StrategyPage<StrategyOf<M['arms'][M['default']]>>\n\n/**\n * The `$page` a read on an endpoint with paginator `P` carries, given the `page` argument `Q`\n * it sent: the picked menu arm's strategy, the default's when it picked none, else the\n * endpoint's own strategy.\n */\nexport type PageOf<P, Q = undefined> =\n IsLoose<P> extends true\n ? Page\n : P extends MenuDescriptor\n ? MenuPage<P, Q>\n : P extends 'none'\n ? TypedPage<'none', Record<never, never>>\n : StrategyPage<StrategyOf<P>>\n\n/**\n * The `page` argument that reads another page from the strategy that answered `P` (a `$page`):\n * its members under their wire keys, tagged with the menu arm it picked. A loose record for an\n * untyped `Page`.\n */\nexport type PageParamsOf<P extends Page> = PaginatorKind extends P['kind']\n ? Readonly<Record<string, string | number>>\n : StrategyParams<{ keys: P['keys'] }> &\n (P extends { arm: infer A extends string } ? { kind: A } : unknown)\n\n/**\n * The `page` params for the page after `list`, read from its `next` link, or `undefined` on the\n * last page (or before anything has loaded). Works the same for every strategy, because the\n * server's link already carries the right parameters: counts come back as numbers, cursors as\n * strings, under the wire keys the strategy uses, with the menu arm's `kind` when the link names\n * one. Feed the result back as the `page` of the next read:\n *\n * ```ts\n * const next = nextPageParams(albums)\n * if (next) albums = await client.albums.list({ page: next })\n * ```\n */\nexport function nextPageParams<P extends Page>(\n list: { readonly $page: P } | undefined,\n): PageParamsOf<P> | undefined {\n return pageParams(list?.$page, list?.$page.links.next)\n}\n\n/** The `page` params for the page before `list`, from its `prev` link. See {@link nextPageParams}. */\nexport function prevPageParams<P extends Page>(\n list: { readonly $page: P } | undefined,\n): PageParamsOf<P> | undefined {\n return pageParams(list?.$page, list?.$page.links.prev)\n}\n\nconst CURSOR_ROLES: readonly string[] = ['after', 'before']\n\nfunction pageParams<P extends Page>(\n page: P | undefined,\n link: string | undefined,\n): PageParamsOf<P> | undefined {\n if (page === undefined || link === undefined) {\n return undefined\n }\n const keys = Object.entries(page.keys) as [PaginatorRole, string][]\n const query = link.includes('?') ? link.slice(link.indexOf('?') + 1).split('#')[0] : ''\n const params: Record<string, string | number> = {}\n // `forEach` rather than `for…of`: iterating `URLSearchParams` needs the DOM iterable lib, which\n // the client's ES2022 consumers (generated clients type-checked without DOM) don't have.\n new URLSearchParams(query).forEach((value, name) => {\n const member = /^page\\[([^\\]]+)\\]$/.exec(name)?.[1]\n if (member === undefined) {\n return\n }\n const role = keys.find(([, key]) => key === member)?.[0]\n const count = Number(value)\n params[member] =\n role !== undefined && !CURSOR_ROLES.includes(role) && value !== '' && Number.isFinite(count)\n ? count\n : value\n })\n return params as PageParamsOf<P>\n}\n","import type {\n ApiDescriptor,\n PaginatorDescriptor,\n PaginatorKind,\n RelationDescriptor,\n} from './descriptor'\nimport { type Page, type ResolvedPaginator, resolvePaginator } from './pagination'\nimport { type NestedFieldset, nestedFieldset } from './nested-fieldset'\nimport type { Document } from './request'\nimport { stampFromDocument } from './request-stamp'\nimport type { ResourceIdentifier } from './types'\nimport { assertJsonApiDocument, type ResolvedValidator, validateDocument } from './validate'\n\n/** A trimmed, by-reference top-level envelope shared by every resource from one response. */\nexport interface DocumentEnvelope {\n jsonapi?: Record<string, unknown>\n meta?: Record<string, unknown>\n links?: Record<string, unknown>\n}\n\n/** A JSON:API link object. */\nexport interface LinkObject {\n href: string\n rel?: string\n describedby?: string | LinkObject\n title?: string\n type?: string\n hreflang?: string | string[]\n meta?: Record<string, unknown>\n}\n\n/**\n * A link as the wire carries it. A server renders the links it builds as link objects unless it\n * opts out to bare strings, and an author-supplied link keeps whichever shape it was given.\n */\nexport type Link = string | LinkObject\n\n/** Resource-level links (`self` is the common one; the wire may carry more). */\nexport interface ResourceLinks {\n self?: Link\n [key: string]: unknown\n}\n\n/**\n * The relationship-instance envelope for a materialised related value (its `$edge`). `Meta`\n * types `meta` when the relation declares its identifier meta members.\n */\nexport interface Edge<Meta extends Record<string, unknown> = Record<string, unknown>> {\n links?: Record<string, unknown>\n meta?: Meta\n}\n\n/**\n * A member a cache layer (an optimistic draft in `@haddowg/json-api-query`) predicted for a\n * relation but couldn't show yet, because no copy of it fits the slot: its identifier, and the\n * member the write supplied when it supplied more than an identifier (a row the user picked, or a\n * new resource's create input), so a placeholder can show what is known of it.\n */\nexport interface PendingMember<TType extends string = string> extends ResourceIdentifier<TType> {\n /** The member the write supplied, when it carried more than its identifier. */\n readonly member?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Where an optimistic create was placed in a list: first (`'start'`), last (`'end'`), or before\n * the member at an index of the list (of the page, in an infinite query's pages).\n */\nexport type PendingPlacement = 'start' | 'end' | number\n\n/**\n * A create a cache layer placed in a list but couldn't show as a member, because the row it can\n * build from the create's input doesn't hold everything the list's members promise (an attribute\n * only the server sets, or an included resource that isn't cached). `input` is what the write sent\n * (`I` types it where the create input's type is known), `id` the id the row carries (the one sent,\n * or a temporary id swapped for the server's once the write succeeds), and `at` where in the list\n * it belongs.\n */\nexport interface PendingCreate<\n I = Readonly<Record<string, unknown>>,\n TType extends string = string,\n> {\n readonly type: TType\n readonly id: string\n readonly at: PendingPlacement\n readonly input: I\n}\n\n/** The uniform shape `$rel(name)` returns. */\nexport interface RelationView {\n data?: unknown\n links?: Record<string, unknown>\n meta?: Record<string, unknown>\n}\n\n/** Non-enumerable envelope accessors shared by every materialised resource. */\nexport interface ResourceEnvelope {\n readonly $meta: Record<string, unknown> | undefined\n readonly $links: ResourceLinks | undefined\n /** The `self` link's href, whether the wire carried a bare URL or a link object. */\n readonly $self: string | undefined\n readonly $document: DocumentEnvelope\n readonly $raw: RawResource\n /**\n * The keys the request's sparse fieldset selected of each attribute it narrowed, under the Nested\n * Fieldsets profile. An attribute named here holds only those of its keys the resource has.\n */\n readonly $nestedFieldset: NestedFieldset\n $rel(name: string): RelationView | undefined\n /**\n * A relationship's count, from its `meta.total` (a `withCount` read): a finite number, else\n * `undefined`. Read from the raw relationship, so it works when the relation carries no data.\n */\n $count(name: string): number | undefined\n /**\n * `'pending'` while a cache layer holds an unconfirmed optimistic change to this resource (an\n * attribute it predicted, or a change to one of its relations), else `undefined`.\n */\n readonly $optimistic: 'pending' | undefined\n /**\n * The members a cache layer predicted for relation `name` but couldn't show yet, because no copy\n * of them fits the slot, each carrying the member the write supplied when it supplied one. Empty\n * when there are none.\n */\n $pending(name: string): readonly PendingMember[]\n}\n\n/** Edge-local accessors carried by a materialised related VALUE (per-edge view). */\nexport interface EdgeEnvelope {\n readonly $edge: Edge | undefined\n readonly $pivot: Record<string, unknown> | undefined\n /** `'pending'` while a cache layer holds an unconfirmed optimistic change to this member. */\n readonly $optimistic: 'pending' | undefined\n}\n\n/** Relationship-level accessors carried by an augmented to-many array. */\nexport interface ArrayEnvelope {\n readonly $page: Page\n readonly $links: Record<string, unknown> | undefined\n readonly $meta: Record<string, unknown> | undefined\n $next(options?: NavigateOptions): Promise<unknown>\n $prev(options?: NavigateOptions): Promise<unknown>\n}\n\n/** The accessor a to-many relationship array carries beside its {@link ArrayEnvelope}. */\nexport interface RelationArrayEnvelope {\n /** The relationship's count, from its `meta.total`: a finite number, else `undefined`. */\n readonly $count: number | undefined\n}\n\n/** Per-call options for `$next()`/`$prev()`. */\nexport interface NavigateOptions {\n /** Cancels the page fetch when signalled. */\n signal?: AbortSignal\n}\n\n/** The runtime context materialise reads its descriptor + navigation seam from. */\nexport interface MaterialiseContext {\n descriptor: ApiDescriptor\n /**\n * Re-fetch + re-materialise a link (wired in Build 4); returns the materialised value.\n * `linkage` propagates the originating surface so a paginated relationship-endpoint\n * array re-materialises as identifiers (not resources) on `$next()`/`$prev()`. `paginator`\n * carries the strategy that answered the current page, so the re-materialised page reports the\n * same `$page` (a divergent per-relation paginator, a picked menu arm, or an EMPTY next page\n * that carries no member to sniff).\n */\n navigate: (\n url: string,\n linkage?: boolean,\n paginator?: ResolvedPaginator,\n signal?: AbortSignal,\n ) => Promise<unknown>\n /**\n * The opt-in per-resource validator, resolved from `ClientOptions.validate`. When\n * present, every wire resource in `data`/`included` is validated against its per-type schema\n * before the document is materialised. Absent => no per-field validation (the default).\n */\n validate?: ResolvedValidator | undefined\n /**\n * The sparse fieldsets the request sent, by type, which tell an attribute narrowed to some of\n * its keys from one rendered whole (see {@link ResourceEnvelope.$nestedFieldset}).\n */\n fields?: Readonly<Record<string, readonly string[]>> | undefined\n}\n\n/** A raw JSON:API resource object (or bare identifier) off the wire. */\ninterface RawResource {\n type: string\n id: string\n meta?: Record<string, unknown>\n links?: ResourceLinks\n attributes?: Record<string, unknown>\n relationships?: Record<string, RawRelationship>\n}\n\ninterface RawRelationship {\n data?: unknown\n links?: Record<string, unknown>\n meta?: Record<string, unknown>\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nconst define = (target: object, key: string, value: unknown): void => {\n Object.defineProperty(target, key, { value, enumerable: false, configurable: true })\n}\n\nconst defineGetter = (target: object, key: string, get: (this: object) => unknown): void => {\n Object.defineProperty(target, key, { get, enumerable: false, configurable: true })\n}\n\n// ── The cache-layer overlay ─────────────────────────────────────────────────────────────────\n\n/**\n * What a cache layer (such as `@haddowg/json-api-query`'s optimistic drafts) reports about the\n * materialised values it holds, consulted by `$optimistic`, `$pending()` and `$count`. Each call\n * gets the value the accessor was read on followed by the values it reads through to (a per-edge\n * view, then the node it views), so a layer that recorded any of them answers for all.\n *\n * @internal\n */\nexport interface MaterialisedOverlay {\n /** `'pending'` when the layer holds an unconfirmed change to any of `targets`. */\n optimistic(targets: readonly object[]): 'pending' | undefined\n /** The members of relation `name` the layer predicted for `targets` but couldn't show. */\n pending(targets: readonly object[], name: string): readonly PendingMember[]\n /**\n * The creates the layer placed in the collection `targets` (an augmented array, then what it\n * reads through to) but couldn't show as members. Absent: none.\n */\n creates?(targets: readonly object[]): readonly PendingCreate[]\n /**\n * The total the collection `targets` reports, given the `raw` total its response carried\n * (`$page.meta.total`, and a top-level collection's `$meta.total`). Absent: the raw total.\n */\n total?(targets: readonly object[], raw: number): number\n /**\n * The count `targets` report for relation `name`, given the `raw` count the response carried.\n * `name` is `undefined` when the target is the to-many array itself (its own `$count`).\n */\n count(\n targets: readonly object[],\n name: string | undefined,\n raw: number | undefined,\n ): number | undefined\n}\n\nlet overlay: MaterialisedOverlay | undefined\n\n/**\n * Install the cache layer's {@link MaterialisedOverlay}, or remove it with `undefined`. One layer is\n * installed at a time; without one, `$optimistic` is `undefined`, `$pending()` is empty and `$count`\n * is the response's count.\n *\n * @internal\n */\nexport function setMaterialisedOverlay(next: MaterialisedOverlay | undefined): void {\n overlay = next\n}\n\nconst NO_IDENTIFIERS: readonly PendingMember[] = Object.freeze([])\n\nconst NO_CREATES: readonly PendingCreate[] = Object.freeze([])\n\n/** The value each per-edge view reads through to. */\nconst SOURCES = new WeakMap<object, object>()\n\n/** The raw (response) count of each node's relations, by node. */\nconst RAW_COUNTS = new WeakMap<object, (name: string) => number | undefined>()\n\n/** `target` followed by the values it reads through to, nearest first. */\nfunction chainOf(target: object): object[] {\n const chain: object[] = []\n let at: object | undefined = target\n while (at !== undefined && !chain.includes(at)) {\n chain.push(at)\n at = SOURCES.get(at)\n }\n return chain\n}\n\n/** The raw count of relation `name` the first value in `chain` with one carries. */\nfunction rawCount(chain: readonly object[], name: string): number | undefined {\n for (const value of chain) {\n const count = RAW_COUNTS.get(value)\n if (count !== undefined) {\n return count(name)\n }\n }\n return undefined\n}\n\n/** {@link rawCount} for the chain starting at `target`, without building the chain. */\nfunction rawCountOf(target: object, name: string): number | undefined {\n let at: object | undefined = target\n while (at !== undefined) {\n const count = RAW_COUNTS.get(at)\n if (count !== undefined) {\n return count(name)\n }\n at = SOURCES.get(at)\n }\n return undefined\n}\n\n/** Define the overlay-backed accessors (`$optimistic`, `$pending`, `$count`) of a resource value. */\nfunction attachOverlayAccessors(target: object): void {\n defineGetter(target, '$optimistic', () => overlay?.optimistic(chainOf(target)))\n define(\n target,\n '$pending',\n (name: string): readonly PendingMember[] =>\n overlay?.pending(chainOf(target), name) ?? NO_IDENTIFIERS,\n )\n define(target, '$count', (name: string): number | undefined => {\n if (overlay === undefined) {\n return rawCountOf(target, name)\n }\n const chain = chainOf(target)\n return overlay.count(chain, name, rawCount(chain, name))\n })\n}\n\n/** A relationship object's `meta.total` when it is a finite number, else `undefined`. */\nconst relationTotal = (rel: RawRelationship | undefined): number | undefined => {\n const total = rel?.meta?.['total']\n return typeof total === 'number' && Number.isFinite(total) ? total : undefined\n}\n\n/**\n * Materialise a JSON:API document into a hydrated graph (ADR 0002):\n *\n * - single resource -> a flattened resource object (own enumerable type/id/attributes/\n * relations + non-enumerable `$`-accessors);\n * - collection / related collection -> an augmented array of resource objects;\n * - relationship linkage -> an augmented array of identifier views (to-many) or a single\n * identifier / null (to-one).\n *\n * Included resources hydrate into nested per-edge views (reads through to the shared\n * node for attributes, owns its own `$edge`/`$pivot`); linked-but-not-included relations\n * stay as identifiers; links-only relations are `undefined`. The envelope rides\n * non-enumerable `$`-accessors so `{...res}` / `JSON.stringify(res)` are clean.\n *\n * `linkage` discriminates a relationship-endpoint response (primary `data` is pure\n * resource-identifier linkage) from a resource/collection response (primary `data` is a\n * full resource) — a structural guess can't tell them apart for an attribute-less,\n * relation-less resource, so the caller passes the surface it issued.\n *\n * `paginatorOverride` sets the top-level array's `$page` for a related/relationship read, where the\n * paginator is the RELATION's (which may diverge from the related type's collection — D6a), for a\n * menu read that picked an arm, and where an empty page carries no member to sniff a type from. A\n * bare kind is read with its canonical wire keys. `primaryType` is preferred for a\n * top-level collection read (statically-known); both override the sniff-from-`data[0]` fallback.\n */\nexport function materialise(\n doc: Document,\n ctx: MaterialiseContext,\n linkage = false,\n primaryType?: string,\n paginatorOverride?: ResolvedPaginator | PaginatorKind,\n): unknown {\n const value = materialiseDocument(doc, ctx, linkage, primaryType, paginatorOverride)\n if (typeof value === 'object' && value !== null) {\n MATERIALISED.add(value)\n }\n return stampFromDocument(doc, value)\n}\n\nconst MATERIALISED = new WeakSet<object>()\n\n/**\n * Whether `value` is a top-level result `materialise` built: a resource, a collection or a linkage\n * value, including the pages `$next()` and `$prev()` re-materialise. A plain copy of one, such as\n * data that went through `JSON.stringify` on a server and back, has lost its `$`-accessors and\n * answers `false`, which is how a hydrated cache entry is told from a fresh read.\n */\nexport function isMaterialised(value: unknown): value is object {\n return typeof value === 'object' && value !== null && MATERIALISED.has(value)\n}\n\nfunction materialiseDocument(\n doc: Document,\n ctx: MaterialiseContext,\n linkage: boolean,\n primaryType: string | undefined,\n paginatorOverride: ResolvedPaginator | PaginatorKind | undefined,\n): unknown {\n // Always-on light structural guards: prove the envelope invariant the runtime relies on (a\n // JSON:API document; each data/included member carries type+id). Then, only when configured,\n // run the opt-in per-field validation over each wire resource by its type.\n assertJsonApiDocument(doc)\n if (ctx.validate !== undefined) {\n validateDocument(doc, ctx.validate, ctx.fields)\n }\n\n const env: DocumentEnvelope = {}\n if (doc.jsonapi !== undefined) env.jsonapi = doc.jsonapi\n if (doc.meta !== undefined) env.meta = doc.meta\n if (doc.links !== undefined) env.links = doc.links\n\n const index = buildIndex(doc.included, linkage ? undefined : doc.data)\n // One node per type:id, shared by reference for attribute reads.\n const nodes = new Map<string, object>()\n const build = (raw: RawResource): object => buildNode(raw, env, index, nodes, ctx)\n\n const data = doc.data\n\n if (data === null) {\n return null\n }\n\n if (Array.isArray(data)) {\n const raws = data as RawResource[]\n const members = linkage\n ? raws.map((raw) => buildIdentifierView(raw))\n : raws.map((raw) => buildEdgeView(build(raw), raw))\n return augmentArray(members, doc, ctx, linkage, primaryType, paginatorOverride)\n }\n\n if (isObject(data)) {\n const raw = data as unknown as RawResource\n if (linkage) {\n return buildIdentifierView(raw)\n }\n return build(raw)\n }\n\n // No primary data (e.g. a meta-only document); expose nothing materialisable.\n return undefined\n}\n\n/**\n * Index `included` and the primary resources by `type:id` so relationship linkage can be hydrated.\n * A server never repeats a primary resource in `included`, so a member that links back to one\n * (`tracks.album` on an album) is found only among the primary data.\n */\nfunction buildIndex(included: unknown[] | undefined, primary: unknown): Map<string, RawResource> {\n const index = new Map<string, RawResource>()\n const add = (raw: unknown): void => {\n if (isObject(raw) && typeof raw['type'] === 'string' && typeof raw['id'] === 'string') {\n index.set(key(raw['type'], raw['id']), raw as unknown as RawResource)\n }\n }\n for (const raw of included ?? []) add(raw)\n for (const raw of Array.isArray(primary) ? primary : [primary]) add(raw)\n return index\n}\n\nconst key = (type: string, id: string): string => `${type}:${id}`\n\n/**\n * Build (or reuse) the shared NODE for a resource: flattened type/id/attributes + hydrated\n * relations as own enumerable props, plus the resource-level `$`-accessors. The node is\n * memoised by `type:id` so attribute reads share one object; per-edge data never lands here.\n */\nfunction buildNode(\n raw: RawResource,\n env: DocumentEnvelope,\n index: Map<string, RawResource>,\n nodes: Map<string, object>,\n ctx: MaterialiseContext,\n): object {\n const id = key(raw.type, raw.id)\n const existing = nodes.get(id)\n if (existing) return existing\n\n const node: Record<string, unknown> = { type: raw.type, id: raw.id }\n // Seed the cache before recursing so a relation cycle resolves to this same node.\n nodes.set(id, node)\n const cycleViews: Record<string, unknown>[] = []\n UNFINISHED.set(node, cycleViews)\n\n if (raw.attributes) {\n for (const [k, v] of Object.entries(raw.attributes)) {\n node[k] = v\n }\n }\n\n const rels = raw.relationships ?? {}\n const resType = ctx.descriptor[raw.type]\n for (const [name, rel] of Object.entries(rels)) {\n if (!('data' in rel)) {\n // Links-only relation: no value to carry an edge -> undefined (reachable via $rel).\n continue\n }\n const relDesc = resType?.relations[name]\n node[name] = hydrateRelation(\n rel,\n relDesc?.cardinality,\n resolvePaginator(relatedPaginator(relDesc, ctx)),\n env,\n index,\n nodes,\n ctx,\n )\n }\n\n attachResourceEnvelope(node, raw, env, rels, nestedFieldset(ctx.fields?.[raw.type]))\n UNFINISHED.delete(node)\n for (const view of cycleViews) {\n readLateRelations(view, node)\n }\n return node\n}\n\n/** Nodes still being built, each with the per-edge views a relation cycle copied of it so far. */\nconst UNFINISHED = new WeakMap<object, Record<string, unknown>[]>()\n\n/** A back-reference's relations that read through to its node; a property, read on every walk. */\nconst LATE: unique symbol = Symbol('late relations')\n\n/** Nodes some back-reference reads relations through to. */\nconst READ_THROUGH = new WeakSet<object>()\n\n/**\n * A relation cycle copied `view` of `node` before the node's later relations were set. Each one it\n * missed reads the node's slot as linkage: the view sits past the end of its include path, and a\n * hydrated value would close the cycle. Non-enumerable, so a spread, `JSON.stringify` and a cache\n * walk meet no cycle.\n */\nfunction readLateRelations(view: Record<string, unknown>, node: Record<string, unknown>): void {\n const late = new Set<string>()\n for (const name of Object.keys(node)) {\n if (!Object.hasOwn(view, name)) {\n late.add(name)\n defineGetter(view, name, () => linkageOf(node[name]))\n }\n }\n if (late.size > 0) {\n Object.defineProperty(view, LATE, { value: late })\n READ_THROUGH.add(node)\n }\n}\n\n/** Each slot value's linkage, so a back-reference reads the same value until its node's changes. */\nconst LINKAGE = new WeakMap<object, unknown>()\n\n/** A relation slot's value as linkage: identifier views, in an array keeping the slot's envelope. */\nfunction linkageOf(slot: unknown): unknown {\n if (typeof slot !== 'object' || slot === null) {\n return slot\n }\n if (LINKAGE.has(slot)) {\n return LINKAGE.get(slot)\n }\n const value = Array.isArray(slot)\n ? withSlotEnvelope(slot, slot.map(identifierOf))\n : identifierOf(slot)\n LINKAGE.set(slot, value)\n return value\n}\n\nfunction identifierOf(member: unknown): unknown {\n if (!isObject(member) || typeof member['type'] !== 'string' || typeof member['id'] !== 'string') {\n return member\n }\n const meta = (member as { $edge?: Edge }).$edge?.meta\n return buildIdentifierView({\n type: member['type'],\n id: member['id'],\n ...(meta !== undefined ? { meta } : {}),\n } as RawResource)\n}\n\n/** `members` carrying `slot`'s non-index members (`$page`, `$links`, `$next()` and the rest). */\nfunction withSlotEnvelope(slot: readonly unknown[], members: unknown[]): unknown[] {\n for (const name of Reflect.ownKeys(slot)) {\n if (name !== 'length' && !(typeof name === 'string' && /^\\d+$/.test(name))) {\n Object.defineProperty(members, name, Object.getOwnPropertyDescriptor(slot, name)!)\n }\n }\n return members\n}\n\n/**\n * The relations of `view` that read through to its node as linkage (a back-reference a relation\n * cycle built before the node's later relations were set), or `undefined`. A cache layer leaves\n * these slots alone: they follow the node.\n * @internal\n */\nexport function lateRelationsOf(view: object): ReadonlySet<string> | undefined {\n return (view as { [LATE]?: ReadonlySet<string> })[LATE]\n}\n\n/**\n * Tell the client a cache layer wrote relation `name` of the cached copy `copy`: a node that\n * back-references read the relation through to takes the value too, so they read it.\n * @internal\n */\nexport function relationWritten(copy: object, name: string, value: unknown): void {\n let at: object | undefined = SOURCES.get(copy)\n while (at !== undefined) {\n if (READ_THROUGH.has(at)) {\n ;(at as Record<string, unknown>)[name] = value\n }\n at = SOURCES.get(at)\n }\n}\n\n/**\n * Resolve one relationship's value: an included member hydrates to a per-edge view, a\n * linked-but-not-included member stays an identifier, an empty to-one is `null`, and a\n * to-many is always an augmented array (of views and/or identifiers).\n *\n * `related` is the relation's paginator (from the descriptor), threaded so a to-many array\n * reports the same `$page` it would on its dedicated endpoint without a `page` argument.\n */\nfunction hydrateRelation(\n rel: RawRelationship,\n cardinality: 'one' | 'many' | undefined,\n related: ResolvedPaginator,\n env: DocumentEnvelope,\n index: Map<string, RawResource>,\n nodes: Map<string, object>,\n ctx: MaterialiseContext,\n): unknown {\n const data = rel.data\n\n if (Array.isArray(data)) {\n const raws = data as RawResource[]\n const members = raws.map((member) => resolveMember(member, env, index, nodes, ctx))\n const hydrated = raws.some((member) => index.has(key(member.type, member.id)))\n return augmentRelationArray(members, rel, related, ctx, hydrated)\n }\n\n // A declared to-many with no array yet (count-free / lazy) still reads as an array.\n if (data === undefined && cardinality === 'many') {\n return augmentRelationArray([], rel, related, ctx, false)\n }\n\n if (data === null || data === undefined) {\n return data === null ? null : undefined\n }\n\n if (isObject(data)) {\n // A to-one's edge envelope carries the relationship object's self/related links/meta\n // ($edge = { links:{self,related}, meta }; docs/materialisation.md) so there's no need to go via\n // the parent's $rel for to-ones.\n return resolveMember(data as unknown as RawResource, env, index, nodes, ctx, {\n links: rel.links,\n meta: rel.meta,\n })\n }\n\n return undefined\n}\n\n/** The relationship-object envelope threaded onto a to-one member's `$edge`. */\ninterface RelationEdge {\n links: Record<string, unknown> | undefined\n meta: Record<string, unknown> | undefined\n}\n\n/** A single linkage member -> a hydrated per-edge view if included, else an identifier view. */\nfunction resolveMember(\n member: RawResource,\n env: DocumentEnvelope,\n index: Map<string, RawResource>,\n nodes: Map<string, object>,\n ctx: MaterialiseContext,\n relationEdge?: RelationEdge,\n): object {\n const included = index.get(key(member.type, member.id))\n if (included) {\n return buildEdgeView(buildNode(included, env, index, nodes, ctx), member, relationEdge)\n }\n return buildIdentifierView(member, relationEdge)\n}\n\n/**\n * Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$nestedFieldset/$rel,\n * and the overlay-backed $count/$optimistic/$pending).\n */\nfunction attachResourceEnvelope(\n node: object,\n raw: RawResource,\n env: DocumentEnvelope,\n rels: Record<string, RawRelationship>,\n selection: NestedFieldset,\n): void {\n defineGetter(node, '$meta', () => raw.meta)\n defineGetter(node, '$links', () => raw.links)\n defineGetter(node, '$self', () => linkHref(raw.links?.self))\n defineGetter(node, '$document', () => env)\n defineGetter(node, '$raw', () => raw)\n defineGetter(node, '$nestedFieldset', () => selection)\n define(node, '$rel', (name: string): RelationView | undefined => {\n const rel = rels[name]\n if (!rel) return undefined\n const view: RelationView = {}\n if ('data' in rel) view.data = rel.data\n if (rel.links !== undefined) view.links = rel.links\n if (rel.meta !== undefined) view.meta = rel.meta\n return view\n })\n RAW_COUNTS.set(node, (name: string): number | undefined =>\n Object.hasOwn(rels, name) ? relationTotal(rels[name]) : undefined,\n )\n attachOverlayAccessors(node)\n}\n\n/**\n * A per-edge VIEW over a node: a distinct wrapper per membership that reads through to the\n * shared node for attributes (and the resource-level `$`-accessors) but owns its own\n * edge-local `$edge`/`$pivot`. Identity is by `type:id`, never reference.\n *\n * `relationEdge` (set for a to-one) carries the relationship object's self/related links and\n * meta, which ride the value's `$edge` (docs/materialisation.md).\n */\nfunction buildEdgeView(\n node: object,\n member: RawResource,\n relationEdge?: RelationEdge,\n pick?: (key: string) => boolean,\n): object {\n const view: Record<string, unknown> = {}\n // Copy the node's own enumerable props (type/id/attributes/relations) into this per-edge view.\n // INVARIANT (normalize.ts, ADR 0003): every cache patch must walk and patch ALL cached views\n // of a resource, not just the canonical node — `patchAll`/`walkResources`/`patchNode` do exactly\n // that, so these copied props stay consistent across writes. A future node-only write path would\n // leave edge views stale, so it must preserve this walk-every-view invariant.\n if (pick === undefined) {\n Object.assign(view, node)\n UNFINISHED.get(node)?.push(view)\n } else {\n for (const [k, v] of Object.entries(node)) {\n if (k === 'type' || k === 'id' || pick(k)) {\n view[k] = v\n }\n }\n }\n SOURCES.set(view, node)\n // Delegate the node's non-enumerable `$`-accessors so they read through to the node.\n for (const k of ['$meta', '$links', '$self', '$document', '$raw', '$nestedFieldset'] as const) {\n delegate(view, node, k)\n }\n // Looked up at the call: a relation cycle copies a node before its `$rel` is defined.\n define(view, '$rel', (name: string): RelationView | undefined => {\n const rel = (node as { $rel?: (name: string) => RelationView | undefined }).$rel\n return typeof rel === 'function' ? rel.call(node, name) : undefined\n })\n // Its own overlay accessors, which ask about this view and then the node it reads through to.\n attachOverlayAccessors(view)\n // A full-resource member's own `links` is its self-link (already on `$links`/`$self`), so a\n // to-many member's `$edge` is meta-only; a to-one additionally carries the relationship\n // object's self/related links via `relationEdge`.\n attachEdgeEnvelope(view, member, false, relationEdge)\n return view\n}\n\n/** The linkage member a per-edge or identifier view is built for: its identity and its meta. */\nexport interface EdgeMember {\n type: string\n id: string\n meta?: Record<string, unknown>\n}\n\n/**\n * A per-edge view over `node` for the membership `member` describes, as `materialise` builds one\n * for an included member: it copies `node`'s own enumerable members (those `pick` keeps, when\n * given; `type` and `id` always), reads its resource-level `$`-accessors through to `node`, and\n * owns its `$edge`/`$pivot` from `member.meta`. `node` may be any resource value, a materialised\n * one or a plain object; accessors it lacks read as `undefined`.\n *\n * For a cache layer placing a member in a slot (`@haddowg/json-api-query`'s optimistic drafts).\n *\n * @internal\n */\nexport function edgeViewOf(\n node: object,\n member: EdgeMember,\n pick?: (key: string) => boolean,\n): object {\n return buildEdgeView(node, member as RawResource, undefined, pick)\n}\n\n/**\n * An identifier view for `member`, as `materialise` builds one for a linked member that isn't\n * included: `{ type, id, meta? }` with its `$edge`/`$pivot`.\n *\n * @internal\n */\nexport function identifierViewOf(member: EdgeMember): object {\n return buildIdentifierView(member as RawResource)\n}\n\n/** An identifier VIEW for a linked-but-not-included member: a clean `{type,id,meta?}` + edge. */\nfunction buildIdentifierView(member: RawResource, relationEdge?: RelationEdge): object {\n const view: Record<string, unknown> = { type: member.type, id: member.id }\n if (member.meta !== undefined) view.meta = member.meta\n defineGetter(view, '$optimistic', () => overlay?.optimistic([view]))\n // A bare linkage member has no resource of its own, so any `links` it carries are edge links.\n attachEdgeEnvelope(view, member, true, relationEdge)\n return view\n}\n\n/**\n * Attach `$edge` (the member's identifier-level edge meta/links) and `$pivot` sugar over it.\n * For a to-one, the relationship object's self/related links + meta (`relationEdge`) merge in,\n * with member-level meta winning on key collision.\n */\nfunction attachEdgeEnvelope(\n view: object,\n member: RawResource,\n includeLinks: boolean,\n relationEdge?: RelationEdge,\n): void {\n defineGetter(view, '$edge', () => {\n const memberLinks = includeLinks ? member.links : undefined\n const links = memberLinks ?? relationEdge?.links\n const meta = mergeMeta(relationEdge?.meta, member.meta)\n if (links === undefined && meta === undefined) return undefined\n const edge: Edge = {}\n if (links !== undefined) edge.links = links\n if (meta !== undefined) edge.meta = meta\n return edge\n })\n defineGetter(view, '$pivot', () => {\n const pivot = member.meta?.['pivot']\n return isObject(pivot) ? pivot : undefined\n })\n}\n\n/** Merge a relationship-object meta with member-level meta (member wins on key collision). */\nfunction mergeMeta(\n base: Record<string, unknown> | undefined,\n override: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (base === undefined) return override\n if (override === undefined) return base\n return { ...base, ...override }\n}\n\n/** Mirror a non-enumerable accessor from `source` onto `target`, reading through live. */\nfunction delegate(target: object, source: object, k: string): void {\n const value = (source as Record<string, unknown>)[k]\n if (typeof value === 'function') {\n define(target, k, (value as (...a: unknown[]) => unknown).bind(source))\n } else {\n defineGetter(target, k, () => (source as Record<string, unknown>)[k])\n }\n}\n\n/**\n * A top-level / related collection array: `$page` from `doc`, links/meta from the document.\n * `linkage` propagates to `$next()`/`$prev()` so a relationship-endpoint page re-materialises\n * as identifiers, not resources.\n */\nfunction augmentArray(\n members: object[],\n doc: Document,\n ctx: MaterialiseContext,\n linkage: boolean,\n primaryType?: string,\n paginatorOverride?: ResolvedPaginator | PaginatorKind,\n): object[] {\n const arr = [...members]\n const links = doc.links\n defineGetter(arr, '$links', () => links)\n // Read through `this`, as `$page` and `$pending` are, so a copy of the array carrying these\n // accessors (a cache layer's edited membership) asks the overlay about itself.\n defineGetter(arr, '$meta', function (this: object) {\n return withTotal(doc.meta, this)\n })\n const paginator =\n paginatorOverride === undefined\n ? resolvePaginator(primaryPaginator(doc, ctx, primaryType))\n : typeof paginatorOverride === 'string'\n ? resolvePaginator(paginatorOverride)\n : paginatorOverride\n attachPage(arr, paginator, pageMeta(doc.meta), links, ctx, linkage)\n return arr\n}\n\n/**\n * A to-many relationship array: `$page`/links/meta come from the relationship object.\n * `paginator` is the relation's (so an in-document compound-include to-many reports the same\n * discriminant it would when fetched at its own relationship/related endpoint — \"one model,\n * three surfaces\").\n *\n * A rendered to-many holds only its first page, and its page links usually address the\n * relationship endpoint, which answers with identifiers. So `$next()`/`$prev()` keep the shape the\n * array has: an included (`hydrated`) array reads the same page from the related endpoint, which\n * answers with the resources, and an array of identifiers reads the page as linkage.\n */\nfunction augmentRelationArray(\n members: object[],\n rel: RawRelationship,\n paginator: ResolvedPaginator,\n ctx: MaterialiseContext,\n hydrated: boolean,\n): object[] {\n const arr = [...members]\n const links = rel.links\n defineGetter(arr, '$links', () => links)\n defineGetter(arr, '$meta', () => rel.meta)\n // Read through `this`, so a copy of the array carrying this accessor (a cache layer's edited\n // membership) asks the overlay about itself.\n defineGetter(arr, '$count', function (this: object) {\n const raw = relationTotal(rel)\n return overlay === undefined ? raw : overlay.count([this], undefined, raw)\n })\n attachPage(\n arr,\n paginator,\n pageMeta(rel.meta),\n links,\n ctx,\n !hydrated,\n hydrated ? (link) => relatedPageLink(link, links) : undefined,\n )\n return arr\n}\n\n/**\n * A relationship page link moved to the related endpoint: a link addressing the relationship's\n * `self` path takes its `related` path and keeps its query, so it reads the same page as\n * resources. Any other link, such as one already addressing the related endpoint, is unchanged.\n */\nfunction relatedPageLink(link: string, links: Record<string, unknown> | undefined): string {\n const self = linkHref(links?.['self'])\n const related = linkHref(links?.['related'])\n if (self === undefined || related === undefined) {\n return link\n }\n const at = link.indexOf('?')\n const path = at < 0 ? link : link.slice(0, at)\n const selfPath = self.split('?')[0]\n return path === selfPath ? `${related.split('?')[0]}${at < 0 ? '' : link.slice(at)}` : link\n}\n\n/** Attach `$page` + `$next()`/`$prev()` driven by link presence (count-free-safe). */\nfunction attachPage(\n arr: object[],\n paginator: ResolvedPaginator,\n meta: Record<string, unknown> | undefined,\n links: Record<string, unknown> | undefined,\n ctx: MaterialiseContext,\n linkage: boolean,\n follow: (link: string) => string = (link) => link,\n): void {\n const page: Page = { kind: paginator.kind, keys: paginator.keys, links: pageLinks(links) }\n if (paginator.arm !== undefined) page.arm = paginator.arm\n if (meta !== undefined) page.meta = meta\n // Through `this`, so a copy of the array (a cache layer's edited membership) reports its own\n // total and pending creates.\n defineGetter(arr, '$page', function (this: object) {\n return pageWithTotal(page, this)\n })\n define(arr, '$pending', function (this: object): readonly PendingCreate[] {\n return overlay?.creates?.([this]) ?? NO_CREATES\n })\n const go = (link: string | undefined, signal: AbortSignal | undefined) =>\n navigateLink(link === undefined ? undefined : follow(link), ctx, linkage, paginator, signal)\n define(arr, '$next', (options?: NavigateOptions) => go(page.links.next, options?.signal))\n define(arr, '$prev', (options?: NavigateOptions) => go(page.links.prev, options?.signal))\n}\n\nconst navigateLink = (\n link: string | undefined,\n ctx: MaterialiseContext,\n linkage: boolean,\n paginator: ResolvedPaginator,\n signal: AbortSignal | undefined,\n): Promise<unknown> => {\n if (link === undefined) {\n return Promise.resolve(undefined)\n }\n return signal === undefined\n ? ctx.navigate(link, linkage, paginator)\n : ctx.navigate(link, linkage, paginator, signal)\n}\n\n/** Extract the navigation links (a link may be a string or a `{href}` object). */\nfunction pageLinks(links: Record<string, unknown> | undefined): Page['links'] {\n const out: Page['links'] = {}\n if (!links) return out\n for (const k of ['first', 'prev', 'next', 'last'] as const) {\n const href = linkHref(links[k])\n if (href !== undefined) out[k] = href\n }\n return out\n}\n\nconst linkHref = (link: unknown): string | undefined => {\n if (typeof link === 'string') return link\n if (isObject(link) && typeof link['href'] === 'string') return link['href']\n return undefined\n}\n\n/** `meta` with its `total` moved as the overlay reports for `target`, when both say so. */\nfunction withTotal(\n meta: Record<string, unknown> | undefined,\n target: object,\n): Record<string, unknown> | undefined {\n const raw = meta?.['total']\n if (overlay?.total === undefined || typeof raw !== 'number' || !Number.isFinite(raw)) {\n return meta\n }\n const total = overlay.total([target], raw)\n return total === raw ? meta : cachedCopy(meta!, total, () => ({ ...meta, total }))\n}\n\n/** `page` with its `meta.total` moved as the overlay reports for `target`. */\nfunction pageWithTotal(page: Page, target: object): Page {\n const meta = page.meta === undefined ? undefined : withTotal(page.meta, target)\n if (meta === undefined || meta === page.meta) {\n return page\n }\n return cachedCopy(page, meta['total'] as number, () => ({ ...page, meta }))\n}\n\n/** The copies made of each value per total, so an unchanged total reads back the same object. */\nconst COPIES = new WeakMap<object, Map<number, object>>()\n\nfunction cachedCopy<V extends object>(value: V, total: number, make: () => V): V {\n const copies = COPIES.get(value) ?? new Map<number, object>()\n COPIES.set(value, copies)\n let copy = copies.get(total)\n if (copy === undefined) {\n copy = make()\n copies.set(total, copy)\n }\n return copy as V\n}\n\nconst pageMeta = (meta: Record<string, unknown> | undefined): Record<string, unknown> | undefined =>\n isObject(meta?.['page']) ? (meta['page'] as Record<string, unknown>) : undefined\n\n/**\n * The document's paginator (from the primary type's descriptor). Prefers the statically-known\n * `primaryType` (passed by the descriptor binding at the call site) so an EMPTY page still reports\n * the collection's real kind; falls back to sniffing the first member's type (for a re-materialised\n * `$next()` page or a related read, where the primary type isn't threaded).\n */\nfunction primaryPaginator(\n doc: Document,\n ctx: MaterialiseContext,\n primaryType?: string,\n): PaginatorDescriptor | undefined {\n const first = Array.isArray(doc.data) ? doc.data[0] : doc.data\n const type =\n primaryType ??\n (isObject(first) && typeof first['type'] === 'string' ? first['type'] : undefined)\n return type !== undefined ? ctx.descriptor[type]?.paginator : undefined\n}\n\n/**\n * A to-many relation's paginator. The relation's OWN related/relationship endpoint may\n * paginate differently than the related type's top-level collection (D6a), so prefer the\n * per-relation `paginator` (carried in the descriptor only when it diverges); otherwise fall back\n * to the related type's own paginator (the relationship and related endpoints both paginate that\n * type), so the discriminant is identical across the three surfaces. A polymorphic relation\n * resolves off its first declared related type (its members span types, matching the relationship\n * endpoint's first-member resolution).\n */\nexport function relatedPaginator(\n relation: RelationDescriptor | undefined,\n ctx: MaterialiseContext,\n): PaginatorDescriptor | undefined {\n if (relation?.paginator !== undefined) return relation.paginator\n const relatedType = relation?.types[0]\n return relatedType === undefined ? undefined : ctx.descriptor[relatedType]?.paginator\n}\n\n/** The kind a relation's related read answers with when it sends no `page`. See {@link relatedPaginator}. */\nexport function relatedPaginatorKind(\n relation: RelationDescriptor | undefined,\n ctx: MaterialiseContext,\n): PaginatorKind {\n return resolvePaginator(relatedPaginator(relation, ctx)).kind\n}\n","/**\n * The parts of the Standard Schema interface (standardschema.dev) the client calls. Zod, Valibot\n * and ArkType schemas implement it.\n */\nexport interface StandardSchema<Input = unknown> {\n readonly '~standard': {\n readonly version: 1\n readonly vendor: string\n readonly validate: (value: unknown) => StandardSchemaResult | Promise<StandardSchemaResult>\n readonly types?: { readonly input: Input } | undefined\n }\n}\n\n/** What a Standard Schema's `validate` returns. */\nexport type StandardSchemaResult =\n | { readonly value: unknown; readonly issues?: undefined }\n | { readonly issues: readonly StandardSchemaIssue[] }\n\n/** One problem a Standard Schema found. */\nexport interface StandardSchemaIssue {\n readonly message: string\n readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[] | undefined\n}\n\n/**\n * The schemas `createClient({ validateInput })` checks a write's input against before sending it,\n * by wire type: `{ albums: { create: albumsCreateSchema, update: albumsUpdateSchema } }`. A type or\n * a write with no schema is sent unchecked. `json-api-codegen --zod` generates this map.\n */\nexport type InputSchemas = Readonly<\n Record<string, { readonly create?: StandardSchema; readonly update?: StandardSchema }>\n>\n\n/**\n * Thrown by a create or update whose input fails the schema `validateInput` holds for it, before\n * any request is sent. `fieldErrors(error)` takes it as it takes a server's 422.\n */\nexport class InputValidationError extends Error {\n readonly type: string\n readonly operation: 'create' | 'update'\n readonly issues: readonly StandardSchemaIssue[]\n /** The failing operation's index in an atomic batch. */\n readonly opIndex?: number\n\n constructor(\n type: string,\n operation: 'create' | 'update',\n issues: readonly StandardSchemaIssue[],\n opIndex?: number,\n ) {\n const first = issues[0]?.message\n super(\n `The ${type} ${operation} input${opIndex === undefined ? '' : ` of atomic operation ${opIndex}`} is invalid` +\n (first === undefined ? '' : `: ${first}`) +\n (issues.length > 1 ? ` (and ${issues.length - 1} more)` : ''),\n )\n this.name = 'InputValidationError'\n this.type = type\n this.operation = operation\n this.issues = issues\n if (opIndex !== undefined) {\n this.opIndex = opIndex\n }\n }\n}\n\n/** One write's input, as `validateInput` checks it. */\nexport interface InputCheck {\n readonly type: string\n readonly operation: 'create' | 'update'\n readonly input: unknown\n readonly opIndex?: number\n}\n\n/**\n * The {@link InputValidationError} `check`'s input fails its schema in `schemas` with, or\n * `undefined` when it passes or has no schema. A Promise only for a schema that validates\n * asynchronously.\n */\nexport function inputFailure(\n schemas: InputSchemas | undefined,\n check: InputCheck,\n): InputValidationError | undefined | Promise<InputValidationError | undefined> {\n const schema = schemas?.[check.type]?.[check.operation]\n if (schema === undefined) {\n return undefined\n }\n const failure = (result: StandardSchemaResult) =>\n result.issues === undefined\n ? undefined\n : new InputValidationError(check.type, check.operation, result.issues, check.opIndex)\n const result = schema['~standard'].validate(check.input)\n return result instanceof Promise ? result.then(failure) : failure(result)\n}\n\n/**\n * Run `write` once `check`'s input passes its schema, else reject with the\n * {@link InputValidationError}. A write with no schema, or a schema that validates synchronously,\n * starts in this tick.\n */\nexport function withInputCheck<T>(\n schemas: InputSchemas | undefined,\n check: InputCheck,\n write: () => Promise<T>,\n): Promise<T> {\n const proceed = (failure: InputValidationError | undefined): Promise<T> =>\n failure === undefined ? write() : Promise.reject(failure)\n const failure = inputFailure(schemas, check)\n return failure instanceof Promise ? failure.then(proceed) : proceed(failure)\n}\n","/**\n * The flat input-path key format: `.` between names, `[n]` for a to-many member's index, as in\n * `orderedTracks[0].$pivot.position`. `byPath()` and `fieldErrors()` key errors by it.\n */\nexport function joinInputPath(segments: readonly (string | number)[]): string {\n return segments\n .map((segment, i) =>\n typeof segment === 'number' ? `[${segment}]` : i === 0 ? segment : `.${segment}`,\n )\n .join('')\n}\n\n/** The segments of a flat input-path key: `a[0].b` is `['a', 0, 'b']`. */\nexport function splitInputPath(key: string): (string | number)[] {\n return Array.from(key.matchAll(/([^.[\\]]+)|\\[(\\d+)\\]/g), ([, name, index]) =>\n index === undefined ? name! : Number(index),\n )\n}\n","/**\n * The write serialisation layer (docs/writes.md and docs/errors.md).\n * Two descriptor-aware inverses of the wire shape:\n *\n * - {@link toDocument} builds the JSON:API write document from the caller's FLAT input\n * (the client owns the envelope), routing each key to `attributes` or `relationships`\n * by the descriptor and coercing relationship linkage by cardinality;\n * - {@link remapPointer} / {@link withRemappedPaths} invert a write error's\n * `source.pointer` back to that flat path so {@link JsonApiError.byPath} groups by the\n * shape the caller actually supplied (form/validation UX).\n */\nimport type { ApiDescriptor } from './descriptor'\nimport { JsonApiError, type JsonApiErrorObject } from './errors'\nimport { joinInputPath } from './input-path'\n\n/** Per-edge writable pivot data, supplied on a to-many member as the `$pivot` key. */\nconst PIVOT_KEY = '$pivot'\n\n/** The resource object's own `meta`, supplied in a write input as the `$meta` key. */\nconst META_KEY = '$meta'\n\n/**\n * The key an error on the request document's top-level `meta`, sent as a write's `meta` option, is\n * grouped under: `$meta` names the resource object's, so the document's is `$documentMeta`.\n */\nconst DOCUMENT_META_KEY = '$documentMeta'\n\n/** The flat path of a pointer into the request document's top-level `meta`, else `undefined`. */\nfunction documentMetaPath(segments: readonly string[]): string | undefined {\n return segments[0] === 'meta' ? pointerPath([DOCUMENT_META_KEY, ...segments.slice(1)]) : undefined\n}\n\n/** Pointer segments as a flat input path, a numeric segment indexing an array: `tags[0]`. */\nfunction pointerPath(segments: readonly string[]): string {\n return joinInputPath(segments.map((s) => (/^\\d+$/.test(s) ? Number(s) : s)))\n}\n\n/** The reserved input keys never routed to attributes/relationships. */\nconst RESERVED_INPUT: ReadonlySet<string> = new Set(['type', 'id'])\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/**\n * A JSON:API resource identifier in a write document: `{ type, id }` or — inside an atomic\n * batch — `{ type, lid }` (a reference to a resource created earlier in the same transaction).\n * May carry writable pivot meta on a to-many member.\n */\ninterface WriteIdentifier {\n type: string\n id?: string\n lid?: string\n meta?: { pivot: Record<string, unknown> } & Record<string, unknown>\n}\n\n/** A relationship document: `{ data: <linkage> }`. */\nexport interface RelationshipDocument {\n data: WriteIdentifier | WriteIdentifier[] | null\n}\n\n/** The JSON:API write document {@link toDocument} produces. */\nexport interface WriteDocument {\n data: {\n type: string\n id?: string\n attributes?: Record<string, unknown>\n relationships?: Record<string, RelationshipDocument>\n meta?: Record<string, unknown>\n }\n /** The document's top-level `meta`, which a write takes in its options. */\n meta?: Readonly<Record<string, unknown>>\n}\n\n/** Options for {@link toDocument}. */\nexport interface ToDocumentOptions {\n /**\n * The resource id, supplied for an UPDATE (it comes from the handle, not the input). When\n * present it is always written as `data.id`. Omit for a CREATE — then `input.id` is written\n * only per the type's `clientId` policy.\n */\n id?: string\n}\n\n/**\n * Build a JSON:API write document from FLAT input. Each input key is routed via the\n * descriptor: a declared relation -> `data.relationships[name] = { data: <linkage> }`;\n * anything else -> `data.attributes[name]`. Relationship linkage is coerced by cardinality:\n *\n * - to-one accepts an identifier `{type,id}`, a materialised resource object (its `{type,id}`\n * are extracted), or `null` (-> `data: null`, clearing the relationship);\n * - to-many accepts an array of those; a member may carry a `$pivot` object, rendered as the\n * member identifier's `meta.pivot` (writable pivot fields).\n *\n * `data.type` is always the accessor `type`. `data.id` is written from `opts.id` (an update),\n * else from `input.id` only when the type's `clientId` policy allows it (omitted when\n * `forbidden`, passed through when `optional`/`required`). A `$meta` object is the resource\n * object's `meta`.\n */\nexport function toDocument(\n descriptor: ApiDescriptor,\n type: string,\n input: Record<string, unknown>,\n opts?: ToDocumentOptions,\n): WriteDocument {\n const resource = descriptor[type]\n const relations = resource?.relations ?? {}\n\n const data: WriteDocument['data'] = { type }\n\n const id = resolveId(input, opts, resource?.clientId)\n if (id !== undefined) {\n data.id = id\n }\n\n const attributes: Record<string, unknown> = {}\n const relationships: Record<string, RelationshipDocument> = {}\n\n for (const [keyName, value] of Object.entries(input)) {\n if (RESERVED_INPUT.has(keyName)) {\n continue\n }\n if (keyName === META_KEY) {\n if (isObject(value)) {\n data.meta = value\n }\n continue\n }\n const relation = relations[keyName]\n if (relation !== undefined) {\n relationships[keyName] = { data: coerceLinkage(value, relation.cardinality) }\n } else {\n attributes[keyName] = value\n }\n }\n\n if (Object.keys(attributes).length > 0) {\n data.attributes = attributes\n }\n if (Object.keys(relationships).length > 0) {\n data.relationships = relationships\n }\n\n return { data }\n}\n\n/**\n * A write document with the top-level `meta` a call's options carry, or the document as it is\n * when they carry none.\n */\nexport function withTopLevelMeta<Doc extends object>(\n doc: Doc,\n meta: Readonly<Record<string, unknown>> | undefined,\n): Doc & { meta?: Readonly<Record<string, unknown>> } {\n return meta === undefined ? doc : { ...doc, meta }\n}\n\n/**\n * Build a relationship-mutation document `{ data: <linkage> }` for the\n * `/{type}/{id}/relationships/{rel}` endpoints, coercing the caller's refs by cardinality:\n *\n * - to-one accepts an identifier `{type,id}`, a materialised resource object, or `null`\n * (-> `data: null`, clearing the relationship);\n * - to-many accepts an array of those; a member may carry `$pivot`, rendered as the member\n * identifier's `meta.pivot`.\n *\n * The same {@link coerceLinkage} the whole-resource writer uses, so a relationship written\n * standalone and one embedded in a resource serialise identically.\n */\nexport function toRelationshipDocument(\n refs: unknown,\n cardinality: 'one' | 'many',\n): RelationshipDocument {\n return { data: coerceLinkage(refs, cardinality) }\n}\n\n/** Resolve the document id: an update's handle id always wins; a create honours the policy. */\nfunction resolveId(\n input: Record<string, unknown>,\n opts: ToDocumentOptions | undefined,\n clientId: ApiDescriptor[string]['clientId'] | undefined,\n): string | undefined {\n if (opts?.id !== undefined) {\n return opts.id\n }\n if (clientId === 'forbidden') {\n return undefined\n }\n const candidate = input['id']\n return typeof candidate === 'string' ? candidate : undefined\n}\n\n/** Coerce one relationship value to linkage by cardinality (array for to-many, identifier/null for to-one). */\nfunction coerceLinkage(\n value: unknown,\n cardinality: 'one' | 'many',\n): WriteIdentifier | WriteIdentifier[] | null {\n if (cardinality === 'many') {\n const members = Array.isArray(value) ? value : value == null ? [] : [value]\n return members.map((member) => toIdentifier(member))\n }\n if (value === null || value === undefined) {\n return null\n }\n return toIdentifier(value)\n}\n\n/**\n * Extract a resource identifier from a linkage input value: an identifier `{type,id}`, a\n * materialised resource object (the same `{type,id}` enumerable props), or — inside an atomic\n * batch — a local identifier `{type,lid}` referencing a just-created resource (the handle a\n * `tx.create` returns). A `$pivot` key is lifted onto `meta.pivot` (writable pivot fields).\n * Throws on a value carrying no `type`, or neither an `id` nor a `lid`.\n */\nfunction toIdentifier(value: unknown): WriteIdentifier {\n if (!isObject(value)) {\n throw new TypeError(\n `Relationship linkage must be an identifier or resource object; received ${describe(value)}`,\n )\n }\n const { type, id, lid } = value\n if (typeof type !== 'string') {\n throw new TypeError('Relationship linkage requires a `type`')\n }\n // An `id` identifies an existing resource; a `lid` references one created earlier in the\n // same atomic transaction. Exactly one is needed.\n const identifier: WriteIdentifier =\n typeof id === 'string'\n ? { type, id }\n : typeof lid === 'string'\n ? { type, lid }\n : (() => {\n throw new TypeError('Relationship linkage requires an `id` or a `lid`')\n })()\n\n const pivot = value[PIVOT_KEY]\n if (isObject(pivot)) {\n identifier.meta = { pivot }\n }\n return identifier\n}\n\nconst describe = (value: unknown): string =>\n value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value\n\n/**\n * Invert a write error's `source.pointer` to the caller's FLAT input path, descriptor-aware:\n *\n * - `/data/attributes/title` -> `title`\n * - `/data/relationships/artist/data` -> `artist`\n * - `/data/id` -> `id` (client-id create conflict)\n * - `/data/attributes/releaseInfo/label` -> `releaseInfo.label` (nested map)\n * - `/data/relationships/orderedTracks/data/0/meta/pivot/position` -> `orderedTracks[0].$pivot.position`\n * - `/data/meta/source` -> `$meta.source`\n * - `/meta/idempotencyKey` -> `$documentMeta.idempotencyKey`\n *\n * Pivot values nest under a member's `meta.pivot` (symmetric with reads — see\n * `JsonPointerBuilder::forLinkageMeta`), so a `meta/pivot/<field>` tail on\n * a member of a pivot-bearing to-many is surfaced as `.$pivot.<field>`.\n *\n * A query-side pointer is left untouched (those are already user-facing — see\n * {@link withRemappedPaths}). An unrecognised / non-write pointer is returned verbatim.\n * `/data/type` and a bare `/data` are passed through (the client owns those; the caller\n * never supplies them).\n */\nexport function remapPointer(descriptor: ApiDescriptor, type: string, pointer: string): string {\n const segments = pointer.split('/').filter((s) => s !== '')\n if (segments[0] !== 'data') {\n return documentMetaPath(segments) ?? pointer\n }\n if (segments[1] === 'meta') {\n return pointerPath([META_KEY, ...segments.slice(2)])\n }\n\n if (segments[1] === 'attributes') {\n return pointerPath(segments.slice(2))\n }\n if (segments[1] === 'id') {\n return 'id'\n }\n if (segments[1] === 'relationships') {\n return remapRelationship(descriptor[type]?.relations ?? {}, segments.slice(2))\n }\n\n return pointer\n}\n\n/**\n * Remap a relationship pointer's tail (everything after `relationships/`, or — for a\n * relationship-endpoint document — the relation name spliced ahead of the `data` tail). The\n * leading segment is the relation name; a `data` segment is dropped; a numeric index becomes\n * `[n]`; a `meta/pivot/<field>` tail on a pivot-bearing relation becomes `.$pivot.<field>`. The\n * `relations` map tells us whether the relation carries pivot (so a member's `meta.pivot`\n * fields are the pivot data the bundle validates).\n */\nfunction remapRelationship(\n relations: Readonly<Record<string, { pivot?: boolean }>>,\n rest: readonly string[],\n): string {\n const name = rest[0]\n if (name === undefined) {\n return 'data/relationships'\n }\n const hasPivot = relations[name]?.pivot === true\n\n const path: (string | number)[] = [name]\n for (let i = 1; i < rest.length; i++) {\n const seg = rest[i]!\n if (seg === 'data') {\n continue\n }\n if (/^\\d+$/.test(seg)) {\n path.push(Number(seg))\n } else if (seg === 'meta' && hasPivot && rest[i + 1] === 'pivot') {\n // Pivot values nest under `meta.pivot` — collapse the\n // `meta/pivot` pair to `$pivot`; the offending field follows.\n path.push('$pivot')\n i++\n } else {\n path.push(seg)\n }\n }\n\n return joinInputPath(path)\n}\n\n/**\n * Invert a relationship-MUTATION error's `source.pointer` to the caller's flat path, for the\n * `/{type}/{id}/relationships/{rel}` endpoints. Two pointer shapes reach here:\n *\n * - the LINKAGE document shape (validation on the linkage members), rooted at `data` — the\n * relation name is supplied by the route, not the wire:\n * - `/data` -> `<rel>` (to-one clear/set)\n * - `/data/meta/pivot/position` -> `<rel>.$pivot.position` (to-one pivot, rare)\n * - `/data/0/meta/pivot/position` -> `<rel>[0].$pivot.position`\n * - the RESOURCE-document shape that core's relationship prohibitions emit unchanged\n * (`FullReplacementProhibited`/`RemovalProhibited`/`AdditionProhibited`/\n * `RelationshipTypeInappropriate` all point at `/data/relationships/<name>`) — short-circuited\n * to the relation name (drop the `relationships/<name>` prefix) rather than treating\n * `relationships` as a linkage sub-segment.\n *\n * A pointer into the top-level `meta` becomes `$documentMeta.<member>`, and any other non-`data`\n * pointer is returned verbatim.\n */\nexport function remapRelationshipPointer(rel: string, hasPivot: boolean, pointer: string): string {\n const segments = pointer.split('/').filter((s) => s !== '')\n if (segments[0] !== 'data') {\n return documentMetaPath(segments) ?? pointer\n }\n // A resource-document relationship pointer (`/data/relationships/<name>...`): the route's\n // relation name owns the path; drop the `relationships/<name>` prefix (segments[2] is the\n // wire name, == the route `rel`) and remap the remaining tail under the route relation.\n const tail = segments[1] === 'relationships' ? segments.slice(3) : segments.slice(1)\n return remapRelationship({ [rel]: { pivot: hasPivot } }, [rel, ...tail])\n}\n\n/**\n * Return a {@link JsonApiError} with each error object's `path` populated by remapping its\n * `source.pointer` (descriptor-aware) — so {@link JsonApiError.byPath} groups by the flat input\n * shape. Errors with no write pointer (e.g. a `source.parameter` query-side error, or no\n * source) are passed through unchanged. The original error is not mutated.\n */\nexport function withRemappedPaths(\n error: JsonApiError,\n descriptor: ApiDescriptor,\n type: string,\n): JsonApiError {\n return mapErrors(error, (pointer) => ({ path: remapPointer(descriptor, type, pointer) }))\n}\n\n/**\n * The relationship-mutation twin of {@link withRemappedPaths}: remap each error's pointer\n * keyed by the relation name from the route. Handles both the linkage-document shape (rooted\n * at `data`) and the resource-document shape core's prohibition exceptions emit\n * (`/data/relationships/<rel>`). `hasPivot` lets a member-level `meta` field surface as\n * `$pivot`. The original error is not mutated.\n */\nexport function withRemappedRelationshipPaths(\n error: JsonApiError,\n rel: string,\n hasPivot: boolean,\n): JsonApiError {\n return mapErrors(error, (pointer) => ({ path: remapRelationshipPointer(rel, hasPivot, pointer) }))\n}\n\n/**\n * Give each error on the request document's top-level `meta` its `$documentMeta.<member>` path,\n * for a request whose other members the client didn't build, such as a bespoke action document or\n * a meta-only one. Every other error is passed through unchanged. The original error is not\n * mutated.\n */\nexport function withRemappedDocumentMetaPaths(error: JsonApiError): JsonApiError {\n const remapped: JsonApiErrorObject[] = error.errors.map((e) => {\n const path =\n e.source?.pointer === undefined\n ? undefined\n : documentMetaPath(e.source.pointer.split('/').filter((s) => s !== ''))\n return path === undefined ? e : { ...e, path }\n })\n return new JsonApiError(error.status, remapped, error.message)\n}\n\n/**\n * Invert an atomic-batch error's `source.pointer` to `(opIndex, flatPath)`: an atomic 422\n * points at `/atomic:operations/{n}/data/...`, so strip the `atomic:operations/{n}` prefix to\n * the op index, resolve that op's wire type (`typeForOp`), and delegate the remaining `/data`\n * tail to the same {@link remapPointer} a standalone write uses (so the flat path is identical\n * — `title`, `releaseInfo.label`, `artist`, …). A relationship op's tail is remapped under its\n * relation, as a standalone relationship write's is, when `relationForOp` names one. A pointer\n * without the atomic prefix is remapped\n * verbatim under the (whole-batch) document at op index `undefined`. The original error is not\n * mutated.\n */\nexport function withRemappedAtomicPaths(\n error: JsonApiError,\n descriptor: ApiDescriptor,\n typeForOp: (opIndex: number) => string | undefined,\n relationForOp?: (opIndex: number) => { rel: string; hasPivot: boolean } | undefined,\n): JsonApiError {\n return mapErrors(error, (pointer) => {\n const segments = pointer.split('/').filter((s) => s !== '')\n if (segments[0] !== 'atomic:operations' || segments[1] === undefined) {\n return { path: pointer }\n }\n const opIndex = Number(segments[1])\n if (!Number.isInteger(opIndex)) {\n return { path: pointer }\n }\n const type = typeForOp(opIndex)\n const relation = relationForOp?.(opIndex)\n const tail = `/${segments.slice(2).join('/')}`\n const path =\n relation !== undefined\n ? remapRelationshipPointer(relation.rel, relation.hasPivot, tail)\n : type === undefined\n ? tail\n : remapPointer(descriptor, type, tail)\n return { opIndex, path }\n })\n}\n\n/** What a per-error remap resolves to: the flat `path` and, for an atomic batch, the `opIndex`. */\ninterface RemapResult {\n path: string\n opIndex?: number\n}\n\n/** Shared error-mapper: clone each error with `path`/`opIndex` from its `source.pointer`, else pass through. */\nfunction mapErrors(error: JsonApiError, remap: (pointer: string) => RemapResult): JsonApiError {\n const remapped: JsonApiErrorObject[] = error.errors.map((e) => {\n const pointer = e.source?.pointer\n if (pointer === undefined) {\n return e\n }\n const { path, opIndex } = remap(pointer)\n return opIndex === undefined ? { ...e, path } : { ...e, path, opIndex }\n })\n return new JsonApiError(error.status, remapped, error.message)\n}\n","/**\n * The Atomic Operations transaction builder (docs/atomic-operations.md).\n * `client.atomic(tx => { … })` records a batch of operations and\n * posts them all-or-nothing to the server's `/operations` endpoint (the atomic ext media type),\n * returning the positional, materialised results.\n *\n * The `tx` recorder is NOT type-scoped (one builder spans every type), so each op carries its\n * own `type` discriminant:\n *\n * - `tx.create({ type, …flatFields })` -> an `add` op; returns a handle that DOUBLES AS a\n * `lid`-bearing relationship ref (`{ type, lid }`) so a just-created resource wires into a\n * later op without a server-assigned id;\n * - `tx.update({ type, id, …flatFields })` -> an `update` op (a `ref` to the existing resource);\n * - `tx.delete({ type, id })` -> a `remove` op;\n * - `tx.rel(ref, relationship)` reaches a relationship of the resource `ref` names, as the\n * standalone relationship accessor does: its `add`, `remove` and `replace` change the members of\n * a to-many, and its `set` a to-one's.\n *\n * Each create gets a deterministic `lid` from its op index (`atomic-<index>`), so the cross-op\n * reference is stable and human-readable. The flat->envelope serialisation reuses the same\n * {@link toDocument} the standalone writes use, so an atomic create body is identical to a\n * `POST /{type}` body (minus the swap of a server `id` for the generated `lid`).\n *\n * Content negotiation: the batch opts into the atomic extension via the request's `ext`\n * parameter ({@link ATOMIC_EXT}), so {@link execute} composes the atomic-ext media type\n * (`application/vnd.api+json; ext=\"…\"`) for both `Content-Type` and `Accept` — the generalised\n * media-type path the rest of the runtime shares.\n */\nimport type { ApiDescriptor, RequestMetaOperation } from './descriptor'\nimport { JsonApiError } from './errors'\nimport { materialise, type MaterialiseContext } from './materialise'\nimport { executeResponse, type JsonApiContext, type JsonApiRequest } from './request'\nimport { stampRequest } from './request-stamp'\nimport type {\n AtomicResultOf,\n CreateInput,\n MetaOption,\n MutationVerb,\n OptionsArg,\n RelationName,\n RelationRequestMetaOf,\n RelationshipMembers,\n RequestMetaOf,\n RequiresRequestMeta,\n TakesVerb,\n TypeName,\n UpdateInput,\n WritableRelationName,\n} from './result-types'\nimport { type InputCheck, type InputSchemas, inputFailure } from './input-validation'\nimport { toDocument, toRelationshipDocument, withRemappedAtomicPaths } from './serialize-write'\nimport type { LocalIdentifier, ResourceIdentifier } from './types'\nimport { ATOMIC_EXT } from './types'\n\n/**\n * A reference to a resource for an `update`/`remove` op: a bare identifier (or a materialised\n * resource — its `{type,id}` extracted), OR a `{ type, lid }` local identifier targeting a\n * resource CREATED EARLIER IN THE SAME BATCH (e.g. a `tx.create` handle), so an op can update\n * or remove a just-created resource that has no server id yet (per the JSON:API atomic ext,\n * `ref` may carry `lid` instead of `id`).\n */\nexport type AtomicRef =\n | ResourceIdentifier\n | { type: string; id: string }\n | LocalIdentifier\n | { type: string; lid: string }\n\n/**\n * Flat create input for type `T`: the `type` discriminant plus the type's flat create\n * attributes/relation slots (reusing {@link CreateInput}; relation slots may reference a prior\n * `tx.create` handle). `D`/`W` thread the descriptor + write-attribute map for precise fields;\n * the loose defaults keep a codegen-less caller compiling.\n */\nexport type AtomicCreateInput<D extends ApiDescriptor, W, T extends TypeName<D>> = {\n type: T\n} & CreateInput<D, W, T, 'atomicCreate'>\n\n/**\n * Flat update input for type `T`: the `type` discriminant + the target's identity (`id`, OR a\n * `lid` for a resource created earlier in the same batch) plus the type's flat update\n * attributes/relation slots (reusing {@link UpdateInput}).\n */\nexport type AtomicUpdateInput<D extends ApiDescriptor, W, T extends TypeName<D>> =\n | ({ type: T; id: string; lid?: never } & UpdateInput<D, W, T, 'atomicUpdate'>)\n | ({ type: T; lid: string; id?: never } & UpdateInput<D, W, T, 'atomicUpdate'>)\n\n/**\n * The options argument of an atomic operation of type `T`: the operation's `meta`, typed by the\n * type's `atomicRequestMeta` and required when a member is. A type declaring none takes any.\n */\nexport type AtomicOperationArgs<\n D extends ApiDescriptor,\n T extends TypeName<D>,\n Op extends RequestMetaOperation,\n> = OptionsArg<\n RequiresRequestMeta<RequestMetaOf<D, T, Op, true>>,\n MetaOption<RequestMetaOf<D, T, Op, true>>\n>\n\n/**\n * The options argument of an atomic operation with verb `V` on relation `R` of type `T`: its\n * `meta`, typed by the relation's `atomicRequestMeta` and required when a member is. A relation\n * declaring none takes any.\n */\nexport type AtomicRelationshipArgs<\n D extends ApiDescriptor,\n T extends TypeName<D>,\n R extends RelationName<D, T>,\n V extends MutationVerb,\n> = OptionsArg<\n RequiresRequestMeta<RelationRequestMetaOf<D, T, R, V, true>>,\n MetaOption<RelationRequestMetaOf<D, T, R, V, true>>\n>\n\n/**\n * The handle a {@link AtomicRecorder.create} returns. It is a `lid`-bearing relationship ref\n * (`{ type, lid }`) — pass it (or spread it) into a later op's relation slot to wire the\n * just-created resource without a server id. It also carries its op `kind` (`'create'`) and its\n * `opIndex` (its position in the batch, the created resource's positional result) so the typed\n * result tuple can map it back to the right positional result.\n */\nexport interface AtomicCreateHandle<T extends string = string> extends LocalIdentifier {\n readonly type: T\n readonly kind: 'create'\n readonly opIndex: number\n}\n\n/**\n * The handle a {@link AtomicRecorder.update} returns: its type discriminant `T`, its op `kind`\n * (`'update'`) and its `opIndex`. Returned (alongside the create handle) from the callback so its\n * positional result is typed as the materialised resource of `T`.\n */\nexport interface AtomicUpdateHandle<T extends string = string> {\n readonly type: T\n readonly kind: 'update'\n readonly opIndex: number\n}\n\n/**\n * The handle a {@link AtomicRecorder.delete} returns: its op `kind` (`'delete'`) and its\n * `opIndex`. A delete carries no data, so its positional result is `undefined`.\n */\nexport interface AtomicDeleteHandle {\n readonly kind: 'delete'\n readonly opIndex: number\n}\n\n/**\n * The handle a relationship operation returns (the `add`, `remove`, `replace` or `set` of\n * {@link AtomicRecorder.rel}): the target's type `T`, its `relationship` `R`, its op `kind`\n * (`'relationship'`) and its `opIndex`. Its positional result is the linkage the server answered\n * with.\n */\nexport interface AtomicRelationshipHandle<T extends string = string, R extends string = string> {\n readonly type: T\n readonly relationship: R\n readonly kind: 'relationship'\n readonly opIndex: number\n}\n\n/**\n * Any handle a recorder method returns — the element type of the callback's result tuple, used\n * as the inference constraint for the typed-tuple `atomic` form. The discriminant is left open\n * (`string`, NOT `TypeName<D>`) DELIBERATELY, so the type is descriptor-agnostic: a tighter\n * `TypeName<D>` constraint would flow the full type union into each element's contextual type\n * during array-literal inference, widening a `tx.create({ type: 'albums' })` handle's `T` back to\n * the whole union — losing the per-op narrowing. The recorder methods already guarantee each `T`\n * is a real `TypeName<D>`, so the open constraint is sound; `AtomicResultOf` re-infers the precise\n * `T` per element (guarded by `TypeName<D>` there).\n */\nexport type AtomicHandle =\n | AtomicCreateHandle<string>\n | AtomicUpdateHandle<string>\n | AtomicDeleteHandle\n | AtomicRelationshipHandle<string, string>\n\n/**\n * A relationship verb inside an atomic batch: present only when relation `R`'s cardinality matches\n * the verb's and the relation advertises it in its `mutations` flags, as the standalone accessor's\n * verbs are gated, and `never` otherwise.\n */\ntype AtomicRelationMutation<\n D extends ApiDescriptor,\n T extends TypeName<D>,\n R extends RelationName<D, T>,\n V extends MutationVerb,\n> =\n TakesVerb<D, T, R, V> extends true\n ? (\n members: RelationshipMembers<D, T, R, V>,\n ...opts: AtomicRelationshipArgs<D, T, R, V>\n ) => AtomicRelationshipHandle<T, R>\n : never\n\n/**\n * What {@link AtomicRecorder.rel} returns: relation `R` of a resource of type `T`, whose verbs\n * each record one relationship operation. A to-many takes `add`, `remove` and `replace` and a\n * to-one `set`, each only when the relation advertises it.\n */\nexport interface AtomicRelationshipRecorder<\n D extends ApiDescriptor,\n T extends TypeName<D>,\n R extends RelationName<D, T>,\n> {\n /** Add `members` to the to-many: an `add` op on its relationship. */\n add: AtomicRelationMutation<D, T, R, 'add'>\n /** Remove `members` from the to-many: a `remove` op on its relationship. */\n remove: AtomicRelationMutation<D, T, R, 'remove'>\n /** Replace every member of the to-many with `members`: an `update` op on its relationship. */\n replace: AtomicRelationMutation<D, T, R, 'replace'>\n /** Set the to-one to `member`, or clear it with `null`: an `update` op on its relationship. */\n set: AtomicRelationMutation<D, T, R, 'set'>\n}\n\n/** A single recorded atomic operation, in wire shape (`op` + `ref`/`data`, and its `meta`). */\ninterface AtomicOperation {\n op: 'add' | 'update' | 'remove'\n ref?: { type: string; id?: string; lid?: string; relationship?: string }\n data?: unknown\n meta?: Readonly<Record<string, unknown>>\n}\n\n/** The identity of an op's target resource: a server `id` or a same-batch `lid`. */\ntype AtomicIdentity = { id: string } | { lid: string }\n\n/**\n * The recorder handed to the `client.atomic` callback. Each method appends an op (preserving\n * order) and returns a handle carrying the op's discriminant `T`, `kind`, and `opIndex`. The\n * methods are generic over `T` (inferred from the input's `type`), so a create/update is typed\n * by the type's write-input ({@link CreateInput}/{@link UpdateInput}) and its handle resolves to\n * the materialised resource of `T`. `create` still returns a usable `{ type, lid }` ref so a\n * just-created resource wires into a later op without a server id.\n */\nexport interface AtomicRecorder<D extends ApiDescriptor, W> {\n create<T extends TypeName<D>>(\n input: AtomicCreateInput<D, W, T>,\n ...opts: AtomicOperationArgs<D, T, 'create'>\n ): AtomicCreateHandle<T>\n update<T extends TypeName<D>>(\n input: AtomicUpdateInput<D, W, T>,\n ...opts: AtomicOperationArgs<D, T, 'update'>\n ): AtomicUpdateHandle<T>\n delete<T extends TypeName<D>>(\n ref: AtomicRef & { type: T },\n ...opts: AtomicOperationArgs<D, T, 'delete'>\n ): AtomicDeleteHandle\n /**\n * Relation `relationship` of the resource `ref` names, by its server `id` or the `lid` of a\n * resource created earlier in the batch. Its verbs record operations on the relationship. Only\n * a relation that takes at least one verb is accepted.\n */\n rel<T extends TypeName<D>, R extends WritableRelationName<D, T>>(\n ref: AtomicRef & { type: T },\n relationship: R,\n ): AtomicRelationshipRecorder<D, T, R>\n}\n\n/** The wire `op` each relationship verb records: `replace` and `set` both update the relationship. */\nconst RELATIONSHIP_OPS = {\n add: 'add',\n remove: 'remove',\n replace: 'update',\n set: 'update',\n} as const satisfies Record<MutationVerb, AtomicOperation['op']>\n\n/** The options an atomic recorder method takes at runtime. */\ninterface AtomicOperationOptions {\n meta?: Readonly<Record<string, unknown>>\n}\n\n/** An operation with its `meta` added when the caller sent any. */\nconst withOperationMeta = (\n operation: AtomicOperation,\n opts: AtomicOperationOptions | undefined,\n): AtomicOperation => (opts?.meta === undefined ? operation : { ...operation, meta: opts.meta })\n\n/** One positional result of an atomic batch: the materialised `data` (a resource/`null`) plus any op `meta`. */\nexport interface AtomicResult<Data = unknown> {\n data: Data\n meta?: Record<string, unknown>\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/** The deterministic local id for the create at `opIndex` (stable + human-readable). */\nconst lidFor = (opIndex: number): string => `atomic-${opIndex}`\n\n/**\n * The typed result tuple for a callback that returns a tuple of handles `Ops`: each returned\n * handle maps (by {@link AtomicResultOf}) to its materialised positional result — a create/update\n * handle to the `AtomicResult` of its type, a delete handle to `undefined`. The mapping is\n * positional in the RETURNED order (sound regardless of subset/reorder, since the runtime resolves\n * each handle by its `opIndex`).\n */\nexport type AtomicResults<D extends ApiDescriptor, A, Ops extends readonly AtomicHandle[]> = {\n -readonly [K in keyof Ops]: AtomicResultOf<D, A, Ops[K]>\n}\n\n/**\n * Run an atomic transaction. Invokes `build` with a recorder, collecting the operations (always\n * via the recorder's side effect, preserving op order), then posts `{ \"atomic:operations\": [...] }`\n * to the atomic endpoint with the ext media type as both `Content-Type` and `Accept`. The server's\n * `{ \"atomic:results\": [...] }` is parsed positionally — each result's `data` materialised the same\n * as a read.\n *\n * The return shape depends on what `build` returns:\n *\n * - returns a tuple of handles -> a per-op POSITIONALLY-TYPED tuple: each returned handle is\n * resolved to its result BY ITS `opIndex` (`results[handle.opIndex]`), so the tuple is sound\n * regardless of the order/subset the callback returns the handles in (a delete handle resolves\n * to `undefined`);\n * - returns void/nothing -> the loose, ordered `AtomicResult[]` (backward-compatible).\n *\n * A thrown {@link JsonApiError} has each error's pointer remapped to `(opIndex, flatPath)` (the\n * failing op's type drives the flat-path inversion) before it propagates.\n */\nexport function runAtomic<D extends ApiDescriptor, A, W, const Ops>(\n request: JsonApiContext,\n materialiseCtx: MaterialiseContext,\n descriptor: D,\n path: string,\n build: (tx: AtomicRecorder<D, W>) => Ops,\n inputSchemas?: InputSchemas,\n): Promise<Ops extends readonly AtomicHandle[] ? AtomicResults<D, A, Ops> : AtomicResult[]>\nexport async function runAtomic(\n request: JsonApiContext,\n materialiseCtx: MaterialiseContext,\n descriptor: ApiDescriptor,\n path: string,\n // A recorder over a loose descriptor isn't assignable from one over the caller's, whose\n // required relations differ per type, so the implementation takes the callback untyped.\n build: (tx: never) => readonly AtomicHandle[] | void,\n inputSchemas?: InputSchemas,\n): Promise<AtomicResult[] | readonly (AtomicResult | undefined)[]> {\n const operations: AtomicOperation[] = []\n /** Each create and update input, checked against `inputSchemas` before the batch is sent. */\n const checks: InputCheck[] = []\n /** The wire type of each op, by index — drives the error-pointer remap. */\n const typeByOp: string[] = []\n /** The relation each relationship op writes, by index, which its pointers are remapped under. */\n const relationByOp = new Map<number, { rel: string; hasPivot: boolean }>()\n\n const relationship = (\n verb: MutationVerb,\n { type, identity }: { type: string; identity: AtomicIdentity },\n name: string,\n members: unknown,\n opts: AtomicOperationOptions | undefined,\n ): AtomicRelationshipHandle => {\n const opIndex = operations.length\n const { data } = toRelationshipDocument(members, verb === 'set' ? 'one' : 'many')\n operations.push(\n withOperationMeta(\n { op: RELATIONSHIP_OPS[verb], ref: { type, ...identity, relationship: name }, data },\n opts,\n ),\n )\n typeByOp.push(type)\n relationByOp.set(opIndex, {\n rel: name,\n hasPivot: descriptor[type]?.relations[name]?.pivot === true,\n })\n return { type, relationship: name, kind: 'relationship', opIndex }\n }\n\n const recorder: AtomicRecorder<ApiDescriptor, unknown> = {\n create(input, ...[opts]: [AtomicOperationOptions?]) {\n const opIndex = operations.length\n const lid = lidFor(opIndex)\n const data = atomicResourceData(descriptor, input, { lid })\n const { type: _type, ...fields } = input\n checks.push({ type: input.type, operation: 'create', input: fields, opIndex })\n operations.push(withOperationMeta({ op: 'add', data }, opts))\n typeByOp.push(input.type)\n return { type: input.type, lid, kind: 'create', opIndex }\n },\n update(input, ...[opts]: [AtomicOperationOptions?]) {\n const opIndex = operations.length\n const identity: AtomicIdentity =\n input.id !== undefined ? { id: input.id } : { lid: input.lid }\n const data = atomicResourceData(descriptor, input, identity)\n const { type: _type, lid: _lid, ...fields } = input as Record<string, unknown>\n // A singleton's update schema checks its id; any other type's checks the patch alone.\n const { id: _id, ...patch } = fields\n checks.push({\n type: input.type,\n operation: 'update',\n input: descriptor[input.type]?.singleton === true ? fields : patch,\n opIndex,\n })\n operations.push(\n withOperationMeta({ op: 'update', ref: { type: input.type, ...identity }, data }, opts),\n )\n typeByOp.push(input.type)\n return { type: input.type, kind: 'update', opIndex }\n },\n delete(ref, ...[opts]: [AtomicOperationOptions?]) {\n const opIndex = operations.length\n const { type, identity } = toRef(ref, 'atomic delete')\n operations.push(withOperationMeta({ op: 'remove', ref: { type, ...identity } }, opts))\n typeByOp.push(type)\n return { kind: 'delete', opIndex }\n },\n rel(ref, name) {\n const target = toRef(ref, 'atomic rel')\n if (typeof name !== 'string') {\n throw new TypeError('atomic rel requires a relationship name')\n }\n const verb =\n (v: MutationVerb) =>\n (members: unknown, ...[opts]: [AtomicOperationOptions?]) =>\n relationship(v, target, name, members, opts)\n // Over a loose descriptor no relation takes a verb, so the verbs join untyped.\n return {\n add: verb('add'),\n remove: verb('remove'),\n replace: verb('replace'),\n set: verb('set'),\n } as never\n },\n }\n\n // The callback always drives the recorder side effect (collecting ops in order); its RETURN\n // VALUE — when it's a tuple of handles — selects the typed positional result per handle.\n const returned = (\n build as (tx: AtomicRecorder<ApiDescriptor, unknown>) => readonly AtomicHandle[] | void\n )(recorder)\n\n // In batch order, so the first failing operation rejects the batch.\n for (const check of checks) {\n const failure = await inputFailure(inputSchemas, check)\n if (failure !== undefined) {\n throw failure\n }\n }\n\n const req: JsonApiRequest = {\n method: 'POST',\n path,\n body: { 'atomic:operations': operations },\n // Opt into the atomic extension; `execute` composes the ext media type for both\n // `Content-Type` and `Accept` (the shared media-type-negotiation path).\n ext: [ATOMIC_EXT],\n }\n\n let doc\n let stamp: number\n try {\n ;({ document: doc, stamp } = await executeResponse(request, req))\n } catch (error) {\n if (error instanceof JsonApiError) {\n throw withRemappedAtomicPaths(\n error,\n descriptor,\n (opIndex) => typeByOp[opIndex],\n (opIndex) => relationByOp.get(opIndex),\n )\n }\n throw error\n }\n\n const results = parseResults(\n doc as { ['atomic:results']?: unknown } | undefined,\n materialiseCtx,\n (opIndex) => relationByOp.has(opIndex),\n stamp,\n )\n\n // Loose form: the callback returned nothing, or not an all-handles array -> the ordered results\n // array (backward-compatible). The all-handles guard keeps the runtime in step with the type\n // predicate (`Ops extends readonly AtomicHandle[]`): a stray non-handle element resolves to the\n // loose AtomicResult[] the type promises rather than a row of undefined.\n const isHandleTuple =\n Array.isArray(returned) &&\n returned.every((h) => h !== null && typeof h === 'object' && 'opIndex' in h)\n if (!isHandleTuple) {\n return stampRequest(results, stamp)\n }\n // Typed-tuple form: resolve each RETURNED handle by its `opIndex` (a delete -> undefined), so\n // the tuple is sound regardless of the order/subset of handles returned. (A server returning no\n // `atomic:results` for an op yields undefined; the reference bundle always returns the created/\n // updated resource, so create/update results are typed present.)\n return stampRequest(\n returned.map((handle) => (handle.kind === 'delete' ? undefined : results[handle.opIndex])),\n stamp,\n )\n}\n\n/**\n * Build the resource `data` for an `add`/`update` op from flat input via {@link toDocument}\n * (so attributes/relationships route identically to a standalone write), then carry the op's\n * identity onto the resource: a server `id` (a create's server-assigned id is omitted; an\n * update by id keeps it) or a same-batch `lid` (a create's generated lid, or an update/remove\n * targeting an earlier op's resource).\n */\nfunction atomicResourceData(\n descriptor: ApiDescriptor,\n input: { type: string; [field: string]: unknown },\n identity: AtomicIdentity,\n): Record<string, unknown> {\n // Strip the identity keys before routing — `lid` is not an attribute, and `id` (when present\n // as a flat field) is carried via the identity, not the body. The identity is applied below.\n const { id: _id, lid: _lid, ...fields } = input as Record<string, unknown>\n const { data } = toDocument(\n descriptor,\n input.type,\n fields,\n 'id' in identity ? { id: identity.id } : undefined,\n )\n const out: Record<string, unknown> = { ...data }\n if ('lid' in identity) {\n // A lid-targeted op rides a local id, never a server id.\n delete out['id']\n out['lid'] = identity.lid\n }\n return out\n}\n\n/**\n * Coerce an op's target ref (an identifier, a materialised resource, or a same-batch `{type,lid}`\n * handle) to `{ type, identity }` — `identity` an `id` or a `lid`; throws if neither is present.\n * `what` names the operation in the error.\n */\nfunction toRef(ref: unknown, what: string): { type: string; identity: AtomicIdentity } {\n if (!isObject(ref)) {\n throw new TypeError(`${what} requires an identifier \\`{ type, id }\\` or \\`{ type, lid }\\``)\n }\n const { type, id, lid } = ref as { type?: unknown; id?: unknown; lid?: unknown }\n if (typeof type !== 'string') {\n throw new TypeError(`${what} requires a \\`type\\``)\n }\n if (typeof id === 'string') {\n return { type, identity: { id } }\n }\n if (typeof lid === 'string') {\n return { type, identity: { lid } }\n }\n throw new TypeError(`${what} requires an \\`id\\` or a \\`lid\\``)\n}\n\n/**\n * Parse `{ \"atomic:results\": [...] }` positionally, materialising each result's `data`: a\n * relationship op's as linkage, any other's as a resource, each stamped with the batch's request\n * start. An absent results array (an all-`204` batch) yields `[]`.\n */\nfunction parseResults(\n doc: { ['atomic:results']?: unknown } | undefined,\n ctx: MaterialiseContext,\n isLinkage: (opIndex: number) => boolean,\n stamp: number,\n): AtomicResult[] {\n const results = doc?.['atomic:results']\n if (!Array.isArray(results)) {\n return []\n }\n return results.map((result, opIndex) => {\n const entry = isObject(result) ? result : {}\n const data =\n entry['data'] === undefined\n ? undefined\n : stampRequest(materialise({ data: entry['data'] }, ctx, isLinkage(opIndex)), stamp)\n const out: AtomicResult = { data }\n if (isObject(entry['meta'])) {\n out.meta = entry['meta']\n }\n return out\n })\n}\n","/**\n * The generated runtime descriptor (ADR 0001). The codegen emits one of these per\n * server `as const satisfies ApiDescriptor`; the client's TYPES are derived from it\n * (one source of truth). It carries everything the generic runtime needs that types\n * alone can't: attribute-vs-relation, cardinality, related type(s), per-operation\n * path templates (uriType/prefix-aware), paginator kind, and the create client-id\n * policy.\n */\nexport type Cardinality = 'one' | 'many'\n\n/**\n * The mutation verbs a single relationship endpoint advertises (derived from the HTTP\n * methods it exposes). These are NOT uniform across relations — the bundle gates them\n * per relation (`cannotAdd`/`cannotRemove`/`cannotReplace`, per-relation endpoint\n * exposure) — so the descriptor carries the capability per relation and the fluent\n * surface gates `add`/`remove`/`replace`/`set` on it.\n *\n * For a to-many: `add` <- POST, `remove` <- DELETE, `replace` <- PATCH.\n * For a to-one: `set` <- PATCH. A flag is `true` iff the endpoint advertises the verb.\n */\nexport interface RelationMutations {\n add?: boolean\n remove?: boolean\n replace?: boolean\n set?: boolean\n}\n\n/**\n * The pivot fields one side of the wire carries on a member's `meta.pivot`, the declared\n * identifier meta members a response carries on a member's `meta`, or the members a document\n * declares in its top-level `meta`: field name to wire-format\n * hint (the vocabulary of {@link ResourceDescriptor.attributes}), the fields that are always\n * present, and the fields that may be `null`.\n */\nexport interface PivotDescriptor {\n fields: Readonly<Record<string, string>>\n /**\n * On a response, the fields every member renders; on a request, the fields every member must\n * send. Absent means every field.\n */\n required?: readonly string[]\n /** The fields whose value may be `null`. Absent means none. */\n nullable?: readonly string[]\n /**\n * The members the object takes beside {@link fields}, when the server opens it: each one's\n * wire-format hint (`unknown` for any value) and whether it may be `null`. `false` closes an\n * identifier meta object. Absent closes every other object, and leaves an identifier meta object\n * open, as a server that doesn't say leaves it.\n */\n additional?: AdditionalMembersDescriptor | false\n /**\n * The values a field may take when the server lists them, from its `enum` or `const`: the field\n * is typed as one of these literals, plus `null` when it is nullable, instead of by its hint. A\n * field hinted `array` lists the values of its items, and is typed as a list of them. Absent for\n * a field that takes any value of its hint, and absent altogether in a descriptor generated\n * without it.\n */\n values?: Readonly<Record<string, readonly MetaLiteral[]>>\n}\n\n/** A literal a meta member may take: one of the values its `enum` or `const` lists. */\nexport type MetaLiteral = string | number | boolean\n\n/**\n * The undeclared members an open meta object takes: their wire-format hint, the values they are\n * limited to when the server lists them, or their items are for a hint of `array`, and whether\n * `null`.\n */\nexport interface AdditionalMembersDescriptor {\n format: string\n nullable?: boolean\n values?: readonly MetaLiteral[]\n}\n\n/**\n * The members a document declares in its top-level `meta`, read from the per-operation document\n * component the server marks `x-document-meta`: each member's wire-format hint, the members every\n * such document carries, and the members that may be `null`. A collection's also lists the `page`\n * and `total` the server writes beside them, both optional. The document's `meta` is present\n * whenever a member is required.\n */\nexport type DocumentMetaDescriptor = PivotDescriptor\n\n/** An operation of a type whose document may declare its top-level `meta`. */\nexport type DocumentMetaOperation = 'fetchMany' | 'fetchOne' | 'create' | 'update' | 'delete'\n\n/** A write of a type whose request document may declare its top-level `meta`. */\nexport type RequestMetaOperation = 'create' | 'update' | 'delete'\n\n/**\n * The `meta` of a type's resource objects, read from the components the server marks\n * `x-resource-meta`: `read` what a response renders, `create` and `update` what a write's\n * `data.meta` takes. `atomicCreate` and `atomicUpdate` are the `data.meta` of an `add` or `update`\n * inside an atomic batch, present only when they differ from `create` and `update`.\n */\nexport interface ResourceMetaDescriptor {\n read?: PivotDescriptor\n create?: PivotDescriptor\n update?: PivotDescriptor\n atomicCreate?: PivotDescriptor\n atomicUpdate?: PivotDescriptor\n}\n\nexport interface RelationDescriptor {\n cardinality: Cardinality\n /** Related JSON:API type(s). */\n types: readonly string[]\n /**\n * `true` when the relation is polymorphic: its linkage is a union of identifier types, even a\n * union of one. Read this rather than counting {@link types}, so a\n * relation declared polymorphic over one type keeps its shape when a second type is added. A\n * descriptor without the flag, such as one generated from an older document or written by\n * hand, is polymorphic when it lists more than one type; see {@link isPolymorphic}.\n */\n polymorphic?: boolean\n /** Whether members carry pivot data (`meta.pivot`). */\n pivot?: boolean\n /**\n * The pivot fields carried on each member's `meta.pivot`, as a field-name → wire-format-hint\n * map, typed as always present and never `null` on both reads and writes.\n *\n * @deprecated Describe each side with {@link readPivot} and {@link writePivot}. Read only when\n * those are absent.\n */\n pivotFields?: Readonly<Record<string, string>>\n /** The `meta.pivot` a response renders on each member (`<Type><Rel>Pivot`). */\n readPivot?: PivotDescriptor\n /**\n * `true` when a response renders `meta.pivot` on every member of the relation's linkage, as its\n * response identifiers require `meta` and its `pivot`. A linkage member's `$pivot` and `$edge`\n * are then always present. Absent means a member may come without them. A request never has to\n * send a pivot.\n */\n pivotRendered?: boolean\n /**\n * The `meta.pivot` a request may send on each member (`<Type><Rel>WritePivot`): a create,\n * update or atomic body, or a relationship mutation.\n */\n writePivot?: PivotDescriptor\n /**\n * The members a response renders on each linkage member's `meta` beside any `pivot`\n * (`<Type><Rel>IdentifierMeta`), as the server's identifier meta resolver declares them. Read\n * only: no request carries them, and a related resource object does not render them.\n */\n identifierMeta?: PivotDescriptor\n /**\n * `true` for a relation create and update accept but no response renders. It stays settable\n * on write inputs and is left out of the read view, `fields` and the relationship reads.\n */\n writeOnly?: boolean\n /**\n * `true` when a create must send this relation, as the create request's\n * `relationships.required` lists it. A create input then requires it. Absent means optional,\n * as every relation is on an update.\n */\n requiredOnCreate?: boolean\n /**\n * The writes that refuse `null` for this to-one, as a required relation that is not nullable\n * does: `create`, `update` or both. A write input in one of them takes a reference, never\n * `null`. Absent means every write takes `null`, which clears the relation.\n */\n nonNullOn?: readonly ('create' | 'update')[]\n /**\n * The writes that refuse an empty linkage for this to-many, as a required relation's do, or\n * one bounded by `minItems` of 1 or more: `create`, `update` or both. A write input in one of\n * them takes a non-empty list. A create also takes one for a relation {@link requiredOnCreate}\n * marks. Absent means every write takes `[]`.\n */\n nonEmptyOn?: readonly ('create' | 'update')[]\n /**\n * The relation's segment in its related and relationship paths, when it differs from the\n * relation's name (`/articles/{id}/published-by` for `publisher`). Absent means the name.\n */\n uriField?: string\n /**\n * `false` when the related endpoint (`GET /{type}/{id}/{rel}`) is suppressed for this relation\n * (the bundle's `withoutRelatedEndpoint()`) — `.related()` is then a compile error /\n * runtime guard rather than a 404. Absent means exposed (the default).\n */\n related?: boolean\n /**\n * `false` when the relationship endpoint (`.../relationships/{rel}`) is suppressed for this\n * relation (the bundle's `withoutRelationshipEndpoint()`) — `.get()` (and every\n * mutation) is then gated off. Absent means exposed (the default).\n */\n relationship?: boolean\n /**\n * The per-relation mutation verbs the relationship endpoint advertises. An explicit `{}` means\n * the endpoint exposes no mutation verb (gates every verb OFF). Absent means the descriptor\n * carries no signal (a hand-written descriptor) — gating then falls back to cardinality alone.\n * A codegen descriptor always emits this (at least `{}`) so suppression never fails open.\n */\n mutations?: RelationMutations\n /**\n * The `withCount` count tokens + negotiation profile this relation's related/relationship reads\n * advertise: `_self_` on a to-many, and the relations of the related type it can count. Lets\n * `.related()`/`.get()` send\n * `withCount` and negotiate the right profile; absent when the relation advertises no Countable\n * profile.\n */\n countable?: CountableDescriptor\n /**\n * The paginator this relation's OWN related/relationship endpoints advertise\n * (`GET /{type}/{id}/{rel}` / `.../relationships/{rel}`), when it DIVERGES from the related\n * type's collection-level {@link ResourceDescriptor.paginator}. A related endpoint may paginate\n * differently than the related type's own collection (e.g. a cursor-paginated related to-many\n * whose target type is page-paginated at its top-level collection) — so the client resolves a\n * related/embedded to-many array's `$page.kind` from this per-relation value first, falling back\n * to the related type's collection paginator (D6a). Absent when the two agree (the common case).\n */\n paginator?: PaginatorDescriptor\n /**\n * The types the related endpoint's compound document can carry in `included`, read from the\n * document's typed `included`. Absent when nothing is includable there, or the document types\n * `included` only as `{type, id}`.\n */\n included?: readonly string[]\n /**\n * The sort tokens the relation's own related and relationship reads accept, when the descriptor\n * records them on the relation. The codegen does for a polymorphic relation, whose members\n * share no type to read them from, such as a `MorphToMany` sorting by its pivot fields, and for\n * a relation whose reads sort differently from its related type's collection read, such as by a\n * pivot field or a sort the relation declares. It records `[]` for a relation whose reads take no\n * sort, such as any to-one, and for a relation with no related or relationship read at all.\n * Narrows `sort` on `.get()`, `.related()` and `relatedQuery` as\n * {@link ResourceDescriptor.sortable} narrows a collection read, and `[]` with no\n * {@link sortFamilies} types `sort` as `never`. Absent, together with {@link sortFamilies}, means\n * not recorded: a monomorphic relation's reads then take its related type's collection sorts and\n * a polymorphic relation's take any sort.\n */\n sortable?: readonly string[]\n /** The sort families the relation's reads accept beside {@link sortable}. */\n sortFamilies?: readonly SortFamilyDescriptor[]\n /**\n * The filter keys the relation's own related and relationship reads accept, recorded as\n * {@link sortable} is, and also when the reads drop a filter default. The codegen records `[]`\n * for a relation whose reads take no filter, and for a relation with no read at all. Narrows\n * `filter` on `.get()`, `.related()` and `relatedQuery`, and `[]` with no {@link filterFamilies}\n * types `filter` as `never`. The client matches list filters against it. Absent, together with\n * {@link filterFamilies}, means not recorded: a monomorphic relation's reads then take its related\n * type's collection filters, list filters included, and a polymorphic relation's take any filter.\n */\n filterable?: readonly string[]\n /** The keys of {@link filterable} whose filter takes a list, sent as a collection read sends them. */\n listFilters?: readonly string[]\n /** The filter families the relation's reads accept beside {@link filterable}. */\n filterFamilies?: readonly FilterFamilyDescriptor[]\n /**\n * `true` when the related read takes `relatedQuery`, keyed by the relations of the related\n * type's {@link ResourceDescriptor.relatedQuery}. Only a monomorphic relation's can.\n */\n relatedQuery?: boolean\n /**\n * The top-level `meta` the relation's related read declares: the related type's collection\n * read's members for a to-many, its single read's for a to-one. Absent when it declares none.\n */\n documentMeta?: DocumentMetaDescriptor\n /**\n * The top-level `meta` each relationship write takes, keyed by its verb, read from the request\n * document the server marks `x-request-meta`. A verb that declares none has no entry, and the\n * map is absent when none does.\n */\n requestMeta?: Readonly<Partial<Record<keyof RelationMutations, DocumentMetaDescriptor>>>\n /**\n * The top-level `meta` each operation on the relation takes inside an atomic batch, keyed by its\n * verb like {@link requestMeta}, read from the atomic relationship operation kinds the type has\n * of its own for the relation. A verb that declares none has no entry, and the map is absent\n * when none does.\n */\n atomicRequestMeta?: Readonly<Partial<Record<keyof RelationMutations, DocumentMetaDescriptor>>>\n /**\n * The top-level `meta` of the meta-only `200` each relationship write answers with instead of\n * the linkage, keyed by its verb. A verb answering with the linkage has no entry, and the map is\n * absent when none answers meta-only.\n */\n mutationMeta?: Readonly<Partial<Record<keyof RelationMutations, DocumentMetaDescriptor>>>\n}\n\n/** A built-in pagination strategy. */\nexport type PaginatorStrategy = 'page' | 'offset' | 'cursor' | 'fixed'\n\n/** The strategy that answers a read, or `none` for an unpaginated endpoint. */\nexport type PaginatorKind = PaginatorStrategy | 'none'\n\n/**\n * A role a page parameter fills. `page`: number, size; `offset`: offset, limit; `cursor`: after,\n * before, size; `fixed`: number.\n */\nexport type PaginatorRole = 'number' | 'size' | 'offset' | 'limit' | 'after' | 'before'\n\n/** A strategy whose roles are filled by renamed wire keys, e.g. `{ number: 'p', size: 'size' }`. */\nexport interface StrategyDescriptor {\n strategy: PaginatorStrategy\n keys: Readonly<Partial<Record<PaginatorRole, string>>>\n}\n\n/**\n * A MultiPaginator menu: the client picks an arm by its `kind` (sent as `page[kind]`), and the\n * server answers with `default` when the request names none. Arm keys are the `kind` values.\n */\nexport interface MenuDescriptor {\n strategy: 'multi'\n default: string\n arms: Readonly<Record<string, PaginatorStrategy | StrategyDescriptor>>\n}\n\n/**\n * How an endpoint paginates. A bare kind uses the canonical wire keys (`page[number]`,\n * `page[size]`, ...); a {@link StrategyDescriptor} names renamed keys; a {@link MenuDescriptor}\n * offers several strategies.\n */\nexport type PaginatorDescriptor = PaginatorKind | StrategyDescriptor | MenuDescriptor\n\nexport type ClientIdPolicy = 'forbidden' | 'optional' | 'required'\n\n/** Where a custom action is invoked: collection-scoped (`/{type}/-actions/{name}`) or resource-scoped (`/{type}/{id}/-actions/{name}`). */\nexport type ActionScope = 'collection' | 'resource'\n\n/** The body a custom action accepts: a JSON:API document, no body, or a raw (non-JSON:API) payload. */\nexport type ActionInput = 'document' | 'none' | 'raw'\n\n/**\n * What a custom action returns: a JSON:API document (materialised into the resource view of its\n * {@link ActionDescriptor.outputType}), a meta-only document (its top-level `meta`), only the URL\n * of a location document (see {@link ActionDescriptor.location}), or nothing (a `204`).\n */\nexport type ActionOutput = 'document' | 'meta' | 'location' | 'none'\n\n/**\n * An action that answers with a URL, such as a short-lived download link (generator contract 17).\n * Asked for JSON:API, the server answers `200` with a location document whose `links.location`\n * carries the URL, and the client returns that URL without following it.\n */\nexport interface ActionLocationDescriptor {\n /** The media type the action declares the URL serves, such as `text/csv`. */\n mediaType: string\n}\n\n/**\n * How the client reads or sends a body that is not JSON:API: `binary` as a `Blob` or\n * `ArrayBuffer`, `text` as a `string`, `json` as parsed JSON typed from the media type's schema.\n */\nexport type RawMediaKind = 'binary' | 'text' | 'json'\n\n/**\n * How the client sends one of an action's request media types: a JSON:API `document` (the\n * action's usual document input), a `multipart` `FormData`, a `form` of URL-encoded fields, or a\n * {@link RawMediaKind}.\n */\nexport type InputMediaKind = RawMediaKind | 'document' | 'form' | 'multipart'\n\n/** A media type an action answers with besides JSON:API, and how its body is read. */\nexport interface RawOutputMedia {\n mediaType: string\n kind: RawMediaKind\n}\n\n/** A media type an action accepts as its request body, and how the client sends it. */\nexport interface InputMedia {\n mediaType: string\n kind: InputMediaKind\n}\n\n/**\n * A `202 Accepted` an operation declares: the server may accept the write for later and answer\n * with a job document to poll at its `Content-Location`. `jobType` is the job's JSON:API type, a\n * registered type when the descriptor has an entry for it.\n */\nexport interface AcceptedDescriptor {\n jobType: string\n /** The top-level `meta` the job document declares. Absent when it declares none. */\n meta?: DocumentMetaDescriptor\n}\n\n/**\n * A custom action declared on a type (`#[AsJsonApiAction]`). The runtime reaches it via\n * `client.<type>.actions.<name>(...)` (collection scope) or\n * `client.<type>.id(id).actions.<name>(...)` (resource scope); `input`/`output` drive how the body\n * is sent and the response shaped (see docs/writes.md).\n */\nexport interface ActionDescriptor {\n scope: ActionScope\n /** The action path template (e.g. `/albums/{id}/-actions/reissue`). */\n path: string\n /**\n * The HTTP method the action is invoked over, upper-case (e.g. `PATCH`). Absent means `POST`\n * (the default) — so an action declaring a single non-POST method (`#[AsJsonApiAction(methods:\n * ['PATCH'])]`) stays reachable rather than being silently dropped.\n */\n method?: string\n input: ActionInput\n output: ActionOutput\n /**\n * The JSON:API type of a `document`-input action's body — lets the client accept FLAT input\n * (like `create`) and build the envelope + remap `422` pointers, rather than the caller\n * hand-building `{ data: { type, attributes } }`. Absent for `none`/`raw` inputs, or a bespoke\n * command document whose type isn't a registered resource (then the raw envelope is passed\n * through).\n */\n inputType?: string\n /**\n * The JSON:API type of a `document`-output action's primary resource — the client materialises\n * the response into that type's resource view (matching the read path), so the typed result is\n * `result.title`, not `result.data.attributes.title`. Absent for `meta`/`none` outputs.\n */\n outputType?: string\n /** Whether a `document`-output action returns a single resource (`one`) or a collection (`many`). */\n outputCardinality?: Cardinality\n /**\n * `true` when the action takes `relatedQuery` for the resource it answers with, keyed by the\n * relations of its {@link outputType}'s {@link ResourceDescriptor.relatedQuery}.\n */\n relatedQuery?: boolean\n /**\n * The declared request media type for a `raw`-input action (e.g. `application/octet-stream`),\n * sent verbatim as the `Content-Type` so the server accepts the non-JSON:API body. Absent for\n * `document` (the JSON:API media type) and `none` (no body) inputs.\n */\n contentType?: string\n /**\n * The media types the action can answer with besides JSON:API (generator contract 10), in the\n * document's order. The caller picks one with the `accept` option; without it the client asks\n * for JSON:API when {@link output} is a document or meta, else for the first of these. Absent\n * when the action answers only in JSON:API.\n */\n rawOutput?: readonly RawOutputMedia[]\n /**\n * The media types the action's request body may use, in the document's order, when it lists\n * more than one. The caller picks one with the `contentType` option; without it the client\n * sends JSON:API when listed, else the first of these. Absent for a single media type, which\n * {@link input} and {@link contentType} already describe.\n */\n inputMedia?: readonly InputMedia[]\n /**\n * Whether the action leaves the server's state unchanged, as its operation's `x-safety`\n * declares (generator contract 15). Absent when the server doesn't say.\n */\n readOnly?: boolean\n /** Whether the action may destroy data, as its `x-safety` declares. Absent when not declared. */\n destructive?: boolean\n /**\n * Whether sending the action twice has the same effect as sending it once, as its `x-safety`\n * declares. Absent when the server doesn't say.\n */\n idempotent?: boolean\n /**\n * The OAuth scopes the action needs, read from its operation's `security` (generator contract\n * 16). Absent when it needs none.\n */\n scopes?: readonly string[]\n /**\n * Present when the action answers with a URL in a location document (generator contract 17).\n * With {@link output} `location` that is all it answers with; with `document` or `meta` it\n * answers with either, and the client tells them apart by the document's shape. Absent for an\n * action that answers with a bare `303`, which the transport follows as before.\n */\n location?: ActionLocationDescriptor\n /**\n * The keys a collection action accepts in `filter[...]`, the same filters its type's collection\n * read takes or a subset of them. The client sends them as the read does. Absent when the action\n * takes no filters.\n */\n filterable?: readonly string[]\n /** The keys of {@link filterable} that take a list, sent as the read sends them. */\n listFilters?: readonly string[]\n /** The filter families the action takes, as its type's collection read does. */\n filterFamilies?: readonly FilterFamilyDescriptor[]\n /**\n * Present when the action may answer `202 Accepted` with a job to poll. Absent when it always\n * answers synchronously.\n */\n accepted?: AcceptedDescriptor\n /**\n * The top-level `meta` each success status's document declares, keyed by status (`200`, `201`).\n * Every status answering with a JSON:API document is listed, `null` for one that declares\n * nothing. Absent when none declares any.\n */\n documentMeta?: Readonly<Record<string, DocumentMetaDescriptor | null>>\n /**\n * `true` for a `document` output whose `200` answers with a meta-only document while another\n * status answers with a resource, such as a `201` with the resource the action created. The\n * result is then that `200`'s `meta` or the resource. Absent otherwise.\n */\n metaResult?: boolean\n /**\n * The top-level `meta` the action's request document takes, read from the document the server\n * marks `x-request-meta`. An action with input `none` sends a meta-only document carrying it.\n * Absent when the action declares none.\n */\n requestMeta?: DocumentMetaDescriptor\n}\n\n/**\n * The `withCount` capability of a type's read endpoints (the Countable profile, core ADR\n * 0101). `tokens` are the count tokens a `withCount` query may carry (`_self_` counts the\n * collection itself; a relation name counts that relation per item); `profile` is the URI a\n * client must negotiate (in `Accept`) before the server honours `withCount` — else it is\n * rejected (400) under strict query-param validation. Absent when no read endpoint of the\n * type advertises `withCount`.\n */\nexport interface CountableDescriptor {\n tokens: readonly string[]\n profile: string\n}\n\n/** An operation answering with one resource that may take `withCount`. */\nexport type ResourceCountOperation = 'fetchOne' | 'create' | 'update'\n\n/**\n * An operation of a type that takes `relatedQuery` for the resources it answers with: the\n * collection read, the single-resource read, the create or the update.\n */\nexport type RelatedQueryOperation = 'fetchMany' | 'fetchOne' | 'create' | 'update'\n\n/**\n * The `relatedQuery` parameter for the resources of a type (the Relationship Queries profile): a\n * `filter` and `sort` per relation, applied to that relationship's members. `relations` names the\n * relations it addresses, `operations` names the type's own operations that take it, and\n * `profile` is the URI a client negotiates in `Accept` before the server honours it, read from the\n * parameter's `x-profile`. A related read or an action answering with resources of the type takes\n * the same parameter when its {@link RelationDescriptor.relatedQuery} or\n * {@link ActionDescriptor.relatedQuery} is `true`.\n */\nexport interface RelatedQueryDescriptor {\n operations: readonly RelatedQueryOperation[]\n profile: string\n /**\n * The relations an entry may be keyed by: the type's monomorphic relations a response renders.\n * Absent in a descriptor that doesn't record them, which then takes any such relation.\n */\n relations?: readonly string[]\n}\n\n/**\n * A family of sort keys matched by prefix: any key of the form `<prefix>.<suffix>`, ascending or\n * with a leading `-`, whose suffix matches `suffixPattern` (a regular expression source, unanchored\n * and without delimiters). The server accepts such keys although it can't list them.\n */\nexport interface SortFamilyDescriptor {\n prefix: string\n suffixPattern: string\n}\n\n/**\n * A family of filter keys matched by prefix: any `filter[<prefix>.<suffix>]` whose suffix matches\n * `suffixPattern` (a regular expression source, unanchored and without delimiters). `list` is\n * `true` when its filters take a list, sent as `filter[<prefix>.<suffix>][]` once per member.\n */\nexport interface FilterFamilyDescriptor {\n prefix: string\n suffixPattern: string\n list?: boolean\n}\n\nexport interface ResourceDescriptor {\n /** Attribute name -> wire format hint (drives optional value coercion). */\n attributes: Readonly<Record<string, string>>\n relations: Readonly<Record<string, RelationDescriptor>>\n /** Per-operation path templates, e.g. `{ fetchOne: '/albums/{id}' }`. */\n paths: Readonly<Record<string, string>>\n paginator: PaginatorDescriptor\n clientId: ClientIdPolicy\n /**\n * The attributes a read renders that a create can't supply (the server sets them: read-only on\n * create, or absent from the create document). Absent when every read attribute is creatable, or\n * for a type with no create.\n */\n serverOnly?: readonly string[]\n /** The attributes whose read value may be `null`. Absent when none may be. */\n nullable?: readonly string[]\n /**\n * `true` for a singleton type, which serves each caller one resource at a path with no `{id}`\n * (`/inbox`). Its {@link paths} are those of the single read, the update, and the related and\n * relationship reads, with no collection, create or delete. Absent for any other type.\n */\n singleton?: boolean\n /**\n * The `withCount` count tokens + negotiation profile for this type's read endpoints.\n * Absent when no read endpoint advertises `withCount`.\n */\n countable?: CountableDescriptor\n /**\n * The `withCount` of the operations that answer with one resource, keyed `fetchOne`, `create`\n * or `update`: the relations each can count and the profile it negotiates. An operation that\n * documents no `withCount` has no entry, and the map is absent when none does.\n */\n resourceCountable?: Readonly<Partial<Record<ResourceCountOperation, CountableDescriptor>>>\n /**\n * The `relatedQuery` an operation answering with resources of this type takes, the operations\n * of this type that take it, and the profile it needs. Absent when no operation documents it.\n */\n relatedQuery?: RelatedQueryDescriptor\n /**\n * The relation paths the read endpoints accept in `include` — the exact enum the OpenAPI\n * document advertises, including nested dotted paths (`tracks.album`). Drives `include`\n * narrowing. Absent when the type advertises no includable relations (so `include` is then\n * a compile error, matching the server's `400 INCLUSION_NOT_ALLOWED`).\n */\n includable?: readonly string[]\n /**\n * The types this type's compound documents can carry in `included`: the types its\n * {@link includable} paths reach, read from the document's typed `included`. Absent when nothing\n * is includable, or the document types `included` only as `{type, id}`.\n */\n included?: readonly string[]\n /**\n * The attributes whose single keys a sparse fieldset may select, under the Nested Fieldsets\n * profile: attribute name -> the pattern a key must match (a regular expression source,\n * unanchored and without delimiters), `\\*` for a list whose items take keys. Each adds\n * `<attribute>.${string}` to the members `fields` takes for this type. Absent when no attribute\n * declares a nested fieldset.\n */\n nestedFieldsets?: Readonly<Record<string, string>>\n /**\n * The paths into nested objects a sparse fieldset may select of the attributes in\n * {@link nestedFieldsets}: attribute name -> one entry per path, each the pattern of every key\n * along it after the attribute's own, such as `['geo', '(?:lat|lng)']` for `location.geo.lat`,\n * or `['\\\\*', '(?:sku|qty)']` for `lines.*.sku`, where `\\*` stands for every item of a list.\n * A key that is a plain name is escaped the way the server escapes it. Absent when no nested fieldset\n * key holds an object or a list whose own keys may be selected.\n */\n nestedFieldsetPaths?: Readonly<Record<string, readonly (readonly string[])[]>>\n /**\n * The sort tokens the COLLECTION read accepts in `sort` — signed field names (`title`,\n * `-title`). Drives `sort` narrowing. Absent when the collection advertises no sorting (so\n * `sort` is then a compile error, matching the server's `400 SORTING_UNSUPPORTED`).\n */\n sortable?: readonly string[]\n /**\n * The sort families the COLLECTION read accepts beside {@link sortable}: keys matched by\n * prefix, such as `meta.<name>`. Each adds `<prefix>.${string}` and `-<prefix>.${string}` to the\n * `sort` type. Absent when the collection declares none.\n */\n sortFamilies?: readonly SortFamilyDescriptor[]\n /**\n * The filter keys the COLLECTION read accepts in `filter[...]`. Drives `filter` key narrowing\n * (values stay `unknown` — value shapes/operators vary per filter, out of scope for v0.1).\n * Absent when the collection advertises no filters (so any `filter` is then a compile error,\n * matching the server's `400 FILTERING_UNRECOGNIZED`).\n */\n filterable?: readonly string[]\n /**\n * The keys of {@link filterable} whose filter takes a list. Each is typed `readonly string[]` and\n * sent as `filter[<key>][]` once per member, so a member may contain a comma. Absent when no\n * filter takes a list.\n */\n listFilters?: readonly string[]\n /**\n * The filter families the COLLECTION read accepts beside {@link filterable}: keys matched by\n * prefix, such as `value.<name>`. Each adds `<prefix>.${string}` to the `filter` type. Absent\n * when the collection declares none.\n */\n filterFamilies?: readonly FilterFamilyDescriptor[]\n /** Custom actions declared on this type, keyed by action name. Absent/empty when none. */\n actions?: Readonly<Record<string, ActionDescriptor>>\n /**\n * The OAuth scopes each of the type's operations needs, read from the operation's `security`\n * (generator contract 16). Keyed like {@link ResourceExamples.operations}: `fetchCollection`,\n * `fetchOne`, `create`, `update`, `delete`, and per relation `fetchRelated.<relation>`,\n * `fetchRelationship.<relation>`, `updateRelationship.<relation>`,\n * `addRelationship.<relation>` and `removeRelationship.<relation>`. An operation that needs\n * no scope has no entry, and the map is absent when none does. An action's scopes are on its\n * {@link ActionDescriptor.scopes}.\n */\n scopes?: Readonly<Record<string, readonly string[]>>\n /**\n * The writes that may answer `202 Accepted` with a job to poll, keyed `create` or `update`. A\n * delete never does. Absent when every write answers synchronously; an action's is on its\n * {@link ActionDescriptor.accepted}.\n */\n accepted?: Readonly<Partial<Record<AcceptedOperation, AcceptedDescriptor>>>\n /**\n * The top-level `meta` each of the type's operations declares, keyed `fetchMany`, `fetchOne`,\n * `create`, `update` or `delete`. A delete's applies to its meta-only `200`. An operation that\n * declares none has no entry, and the map is absent when none does. A relation's related read\n * has its own on {@link RelationDescriptor.documentMeta}, an action's on\n * {@link ActionDescriptor.documentMeta}.\n */\n documentMeta?: Readonly<Partial<Record<DocumentMetaOperation, DocumentMetaDescriptor>>>\n /**\n * The top-level `meta` each of the type's writes takes, keyed `create`, `update` or `delete`,\n * read from the request document the server marks `x-request-meta`. A delete declaring it takes\n * a meta-only request document. A write that declares none has no entry, and the map is absent\n * when none does.\n */\n requestMeta?: Readonly<Partial<Record<RequestMetaOperation, DocumentMetaDescriptor>>>\n /**\n * The top-level `meta` each of the type's operations takes inside an atomic batch, keyed like\n * {@link requestMeta}, read from the atomic operation kinds the type has of its own.\n */\n atomicRequestMeta?: Readonly<Partial<Record<RequestMetaOperation, DocumentMetaDescriptor>>>\n /** The `meta` of the type's resource objects, as a read renders it and a write sends it. */\n resourceMeta?: ResourceMetaDescriptor\n}\n\n/** A write that can answer `202 Accepted`. */\nexport type AcceptedOperation = 'create' | 'update'\n\nexport type ApiDescriptor = Readonly<Record<string, ResourceDescriptor>>\n\n/**\n * Whether a relation is polymorphic: flagged {@link RelationDescriptor.polymorphic}, or, when the\n * flag is absent, listing more than one related type.\n */\nexport function isPolymorphic(\n relation: Pick<RelationDescriptor, 'polymorphic' | 'types'>,\n): boolean {\n return relation.polymorphic ?? relation.types.length > 1\n}\n\n/**\n * The server-level Atomic Operations capability: the single `/operations`\n * endpoint, detected when its requestBody uses the atomic ext media type. `null` when the\n * server exposes no atomic endpoint. Carried alongside the per-type descriptor (not inside\n * it — atomic is server-level, not per-type) so the runtime `client.atomic` builder can\n * reach the path.\n */\nexport interface AtomicDescriptor {\n path: string\n /** The OAuth scopes the endpoint itself needs (generator contract 16). Absent when none. */\n scopes?: readonly string[]\n}\n\n/** Example bodies keyed by the media type they are declared for, such as `application/vnd.api+json`. */\nexport type MediaExamples = Readonly<Record<string, unknown>>\n\n/**\n * The worked examples one operation declares (generator contract 12): its request body, and its\n * success responses keyed by status code. Each body is the whole wire document, not the flat input\n * or materialised result the client works with. A part the document gives no example for is absent.\n */\nexport interface OperationExamples {\n request?: MediaExamples\n responses?: Readonly<Record<string, MediaExamples>>\n}\n\n/**\n * The examples of one type's operations. `operations` is keyed by the operation's name in core's\n * terms, its `operationId` without the type: `fetchCollection`, `fetchOne`, `create`, `update`,\n * `delete`, and per relation `fetchRelated.<relation>`, `fetchRelationship.<relation>`,\n * `updateRelationship.<relation>`, `addRelationship.<relation>` and\n * `removeRelationship.<relation>`. `actions` is keyed by action name, as\n * {@link ResourceDescriptor.actions} is.\n */\nexport interface ResourceExamples {\n operations?: Readonly<Record<string, OperationExamples>>\n actions?: Readonly<Record<string, OperationExamples>>\n}\n\n/** The operation examples of every type that has one, keyed by wire type. */\nexport type ApiExamples = Readonly<Record<string, ResourceExamples>>\n","import type { FilterFamilyDescriptor } from './descriptor'\n\n/** The filter vocabulary {@link listFilterMatcher} reads: a type's, or a collection action's. */\nexport interface FilterSpec {\n filterable?: readonly string[]\n listFilters?: readonly string[]\n filterFamilies?: readonly FilterFamilyDescriptor[]\n}\n\n/**\n * Whether a `filter[...]` key takes a list, by the rule the server matches keys with: an exact\n * key first, then the filter family with the longest prefix whose suffix pattern accepts the rest\n * of the key. A family never matches its bare prefix. `undefined` when nothing in `spec` takes a\n * list, so every filter value is sent as before.\n */\nexport function listFilterMatcher(\n spec: FilterSpec | undefined,\n): ((key: string) => boolean) | undefined {\n const lists = new Set(spec?.listFilters ?? [])\n const families = (spec?.filterFamilies ?? []).filter((family) => family.list === true)\n if (lists.size === 0 && families.length === 0) {\n return undefined\n }\n const exact = new Set(spec?.filterable ?? [])\n // oxlint-disable-next-line no-array-sort -- sorting a freshly-copied array\n const byLength = [...(spec?.filterFamilies ?? [])].sort(\n (a, b) => b.prefix.length - a.prefix.length,\n )\n return (key) => {\n if (lists.has(key)) {\n return true\n }\n if (exact.has(key)) {\n return false\n }\n for (const family of byLength) {\n const prefix = `${family.prefix}.`\n if (!key.startsWith(prefix)) {\n continue\n }\n const suffix = key.slice(prefix.length)\n if (suffix !== '' && new RegExp(`^(?:${family.suffixPattern})$`, 'u').test(suffix)) {\n return family.list === true\n }\n }\n return false\n }\n}\n","import type { ActionLocationDescriptor } from './descriptor'\nimport type { Document } from './request'\n\n/**\n * The URL an action answered with (generator contract 17), read from its location document. The\n * client never fetches it: a presigned storage URL is for the browser or the caller to open.\n */\nexport interface ActionLocation {\n /** The URL, from `links.location.href`. */\n url: string\n /**\n * The media type the URL serves: the link's `type`, else the one the action declares. A server\n * may name another type for one response, such as a file whose type varies.\n */\n type: string\n /** When the URL stops working, as the server's ISO 8601 string. Absent when it doesn't expire. */\n expiresAt?: string\n}\n\n/**\n * Whether a value is an {@link ActionLocation}, for an action that answers with either a resource\n * or a URL. A materialised resource always has an `id`, which a location never has.\n */\nexport function isActionLocation(value: unknown): value is ActionLocation {\n if (typeof value !== 'object' || value === null || Array.isArray(value) || 'id' in value) {\n return false\n }\n const record = value as Record<string, unknown>\n return typeof record['url'] === 'string' && typeof record['type'] === 'string'\n}\n\n/** A link's `href` and the object it came from, whether written as a string or a link object. */\nfunction linkObject(link: unknown): { href: string; link: Record<string, unknown> } | undefined {\n if (typeof link === 'string') {\n return { href: link, link: {} }\n }\n if (typeof link === 'object' && link !== null && !Array.isArray(link)) {\n const object = link as Record<string, unknown>\n return typeof object['href'] === 'string' ? { href: object['href'], link: object } : undefined\n }\n return undefined\n}\n\n/**\n * The URL a location document carries, or `undefined` when the document is something else, such\n * as a resource document from an action that answers with either.\n */\nexport function readActionLocation(\n doc: Document,\n declared: ActionLocationDescriptor,\n): ActionLocation | undefined {\n if (doc.data !== undefined) {\n return undefined\n }\n const location = linkObject(doc.links?.['location'])\n if (location === undefined) {\n return undefined\n }\n const out: ActionLocation = {\n url: location.href,\n type: typeof location.link['type'] === 'string' ? location.link['type'] : declared.mediaType,\n }\n const meta = location.link['meta']\n const linkExpiry =\n typeof meta === 'object' && meta !== null\n ? (meta as Record<string, unknown>)['expiresAt']\n : undefined\n const expiresAt = linkExpiry ?? doc.meta?.['expiresAt']\n if (typeof expiresAt === 'string') {\n out.expiresAt = expiresAt\n }\n return out\n}\n","/**\n * A request body that is not text: the binary, multipart and URL-encoded payloads a custom action\n * can take.\n */\nexport type TransportRawBody =\n | Blob\n | ArrayBuffer\n | Uint8Array<ArrayBuffer>\n | FormData\n | URLSearchParams\n\n/** A single outbound request, already serialised. */\nexport interface TransportRequest {\n method: string\n url: string\n headers: Record<string, string>\n body?: string\n /**\n * A body that is not text, sent instead of {@link body}. Only a custom action with a binary,\n * multipart or URL-encoded request media type sets it, and a custom transport must send it as\n * is for those actions to work.\n */\n rawBody?: TransportRawBody\n /**\n * Read a successful response as binary into {@link TransportResponse.binary}. Absent means text,\n * which is every JSON:API response. Only a custom action answering with a binary media type\n * sets it; an error response is still read as text so the client can parse its JSON:API errors.\n */\n responseType?: 'blob' | 'arraybuffer'\n /**\n * Aborts the request when signalled. Optional: a transport that ignores it still works, the\n * caller just can't cancel an in-flight request through it.\n */\n signal?: AbortSignal\n}\n\n/** A single inbound response, body still a string for the runtime to parse. */\nexport interface TransportResponse {\n status: number\n headers: Record<string, string>\n /** The response body as text; empty when it was read into {@link binary} instead. */\n body: string\n /** The body of a successful response to a request that set `responseType`. */\n binary?: Blob | ArrayBuffer\n}\n\n/**\n * The transport seam: a tiny, `fetch`-shaped function (not a class), so any impl\n * (native `fetch`, undici, an axios adapter) drops in. Retries are deliberately out\n * of scope here — the transport (or the TanStack layer) owns them.\n */\nexport type JsonApiTransport = (req: TransportRequest) => Promise<TransportResponse>\n\n/** The default transport, backed by the global `fetch`. */\nexport const fetchTransport: JsonApiTransport = async (req) => {\n const init: RequestInit = { method: req.method, headers: req.headers }\n if (req.rawBody !== undefined) {\n init.body = req.rawBody\n } else if (req.body !== undefined) {\n init.body = req.body\n }\n if (req.signal !== undefined) {\n init.signal = req.signal\n }\n\n const res = await fetch(req.url, init)\n\n const headers: Record<string, string> = {}\n res.headers.forEach((value, key) => {\n headers[key] = value\n })\n\n if (req.responseType !== undefined && res.ok) {\n const binary = req.responseType === 'blob' ? await res.blob() : await res.arrayBuffer()\n return { status: res.status, headers, body: '', binary }\n }\n return { status: res.status, headers, body: await res.text() }\n}\n","import { type PollOptions, toAccepted } from './accepted'\nimport { type AtomicRecorder, runAtomic } from './atomic'\nimport {\n type AcceptedDescriptor,\n type ActionDescriptor,\n type ActionScope,\n type ApiDescriptor,\n type AtomicDescriptor,\n type InputMediaKind,\n isPolymorphic,\n type ResourceCountOperation,\n} from './descriptor'\nimport { JsonApiError } from './errors'\nimport { type FilterSpec, listFilterMatcher } from './filters'\nimport { fieldsOfUrl } from './nested-fieldset'\nimport { readActionLocation } from './location'\nimport { materialise, type MaterialiseContext, relatedPaginator } from './materialise'\nimport { stampFromDocument } from './request-stamp'\nimport { resolvePaginator } from './pagination'\nimport {\n type Document,\n execute,\n executeRaw,\n type ExecutedResponse,\n executeResponse,\n type JsonApiContext,\n type JsonApiRequest,\n type ReadQuery,\n} from './request'\nimport type {\n ActionCallOptions,\n ActionsAccessor,\n Client,\n DefaultActionTypes,\n DefaultAttributes,\n DefaultWriteAttributes,\n RelationReadQuery,\n RelationshipAccessor,\n ResourceHandle,\n SingletonAccessor,\n TypeAccessor,\n} from './result-types'\nimport {\n toDocument,\n toRelationshipDocument,\n withTopLevelMeta,\n withRemappedDocumentMetaPaths,\n withRemappedPaths,\n withRemappedRelationshipPaths,\n} from './serialize-write'\nimport { fetchTransport, type JsonApiTransport } from './transport'\nimport { JSON_API_MEDIA_TYPE } from './types'\nimport { resolveValidator, type ValidationOption } from './validate'\nimport { type InputSchemas, withInputCheck } from './input-validation'\n\n/**\n * The `fetch` headers init type. `@types/node` declares the global `RequestInit` (used\n * by the transport) but not `HeadersInit`; we derive it from `RequestInit.headers` to\n * stay dep-free and consistent with the rest of the runtime's web-globals usage.\n */\nexport type HeadersInit = NonNullable<RequestInit['headers']>\n\n/** Options for {@link createClient}. */\nexport interface ClientOptions {\n /** Base URL the generated path templates are resolved against. */\n baseUrl: string\n /** Transport seam; defaults to the `fetch` adapter when omitted. */\n transport?: JsonApiTransport\n /** Per-request header provider (e.g. bearer auth); may be async. */\n headers?: () => HeadersInit | Promise<HeadersInit>\n /**\n * Follow a server link (`$next()`, `$prev()`) that leaves `baseUrl`'s origin. Off by default, so\n * such a link rejects without sending a request. When on, the request goes out without\n * {@link headers}.\n */\n allowCrossOriginLinks?: boolean\n /**\n * The server-level Atomic Operations capability (the codegen's `atomic` constant): `{ path }`\n * when the server exposes the atomic endpoint, else `null`/omitted. When present, the client\n * exposes `client.atomic(tx => …)`; otherwise calling it throws.\n */\n atomic?: AtomicDescriptor | null\n /**\n * The opt-in per-field validation seam. Off by default — the client always runs\n * light structural guards (is this a JSON:API document? does each `data`/`included` member\n * carry `type`+`id`?) but otherwise trusts the wire. Supply either the schema-driven config\n * `{ schemas, validator }` — the codegen-emitted per-type `schemas` map plus a validation\n * engine adapter (each wire resource is validated against `schemas[type]`; a type with no\n * schema is skipped) — or a bare validator function that owns schema lookup itself. The\n * validation engine (e.g. ajv) is brought by the caller; the client never depends on one.\n */\n validate?: ValidationOption\n /**\n * Schemas to check each create's and update's input against before sending it, by wire type.\n * An input that fails rejects with an {@link InputValidationError} and sends nothing. Pass the\n * `inputSchemas` that `json-api-codegen --zod` generates, or your own Standard Schemas.\n */\n validateInput?: InputSchemas\n}\n\n/** The ambient runtime context every read shares: transport seam + descriptor + materialise glue. */\ninterface ClientContext {\n readonly request: JsonApiContext\n readonly materialise: MaterialiseContext\n readonly descriptor: ApiDescriptor\n readonly inputSchemas?: InputSchemas\n}\n\n/** Substitute `{key}` placeholders in a path template (`/albums/{id}/{rel}` -> `/albums/1/tracks`). */\nconst fill = (template: string, vars: Record<string, string>): string =>\n template.replace(/\\{(\\w+)\\}/g, (_, key: string) => vars[key] ?? `{${key}}`)\n\n/**\n * Fill a type's path template, putting a relation's URI segment (its `uriField`, else its name)\n * in place of `{rel}`. `vars.rel` stays the relation's name everywhere else.\n */\nfunction fillPath(\n ctx: ClientContext,\n type: string,\n template: string,\n vars: Record<string, string>,\n): string {\n const rel = vars['rel']\n const uriField = rel === undefined ? undefined : ctx.descriptor[type]?.relations[rel]?.uriField\n return fill(template, uriField === undefined ? vars : { ...vars, rel: uriField })\n}\n\n/**\n * Run an operation: resolve the path template from the type's descriptor, fill its\n * placeholders, execute, and materialise the resulting document. A no-body / 204 response\n * materialises to `undefined`; an operation the type does not declare (no path template) throws\n * a local `Error` before any request. `linkage` marks a relationship-endpoint read (primary\n * `data` is pure resource-identifier linkage) so an attribute-less, relation-less member is\n * still materialised as an identifier.\n */\nasync function run(\n ctx: ClientContext,\n type: string,\n operation: string,\n vars: Record<string, string>,\n query: ReadQuery | undefined,\n linkage = false,\n relationForCount?: string,\n): Promise<unknown> {\n const template = ctx.descriptor[type]?.paths[operation]\n if (template === undefined) {\n throw new Error(`No \"${operation}\" path declared for type \"${type}\"`)\n }\n const req: JsonApiRequest = { method: 'GET', path: fillPath(ctx, type, template, vars) }\n if (query !== undefined) {\n const { signal, ...params } = query\n req.query = params\n const listFilter = listFilterMatcher(filterSpec(ctx, type, operation, vars['rel']))\n if (listFilter !== undefined) {\n req.listFilter = listFilter\n }\n if (signal !== undefined) {\n req.signal = signal\n }\n negotiateProfiles(ctx, type, params, req, relationForCount, operation)\n applyRelatedQuery(ctx, renderedType(ctx, type, operation, vars['rel']), params, req)\n }\n const doc = await execute(ctx.request, req)\n // Resolve the strategy that answers from the endpoint's paginator and the `page` sent, so an\n // EMPTY page still reports the real `$page.kind` and a menu read reports the arm it picked.\n // A related/relationship read uses the RELATION's paginator, which may diverge from the related\n // type's collection (D6a).\n const relation =\n (operation === 'fetchRelated' || operation === 'fetchRelationship') && vars['rel'] !== undefined\n ? ctx.descriptor[type]?.relations[vars['rel']]\n : undefined\n const paginator =\n operation === 'fetchMany'\n ? ctx.descriptor[type]?.paginator\n : relation !== undefined\n ? relatedPaginator(relation, ctx.materialise)\n : undefined\n const primaryType = operation === 'fetchMany' ? type : undefined\n const paginatorOverride =\n paginator === undefined ? undefined : resolvePaginator(paginator, query?.page)\n return doc === undefined\n ? undefined\n : materialise(\n doc,\n withFields(ctx.materialise, query?.fields),\n linkage,\n primaryType,\n paginatorOverride,\n )\n}\n\n/** The materialise context for a response to a request that sent `fields`. */\nfunction withFields(\n ctx: MaterialiseContext,\n fields: Readonly<Record<string, readonly string[]>> | undefined,\n): MaterialiseContext {\n return fields === undefined ? ctx : { ...ctx, fields }\n}\n\n/**\n * The filter vocabulary a read's `filter` is matched against: the type's for its collection read.\n * A related or relationship read takes the relation's own when its descriptor declares one, even an\n * empty one, else the related type's when the relation has one related type.\n */\nfunction filterSpec(\n ctx: ClientContext,\n type: string,\n operation: string,\n rel: string | undefined,\n): FilterSpec | undefined {\n if (operation === 'fetchMany') {\n return ctx.descriptor[type]\n }\n const relation = rel === undefined ? undefined : ctx.descriptor[type]?.relations[rel]\n if (relation?.filterable !== undefined || relation?.filterFamilies !== undefined) {\n return relation\n }\n const types = relation?.types\n return types?.length === 1 ? ctx.descriptor[types[0]!] : undefined\n}\n\n/**\n * The type whose resources an operation answers with, which keys its `relatedQuery`: the type\n * itself, or a related read's related type when the relation is monomorphic. A relationship read\n * answers with linkage, so it has none.\n */\nfunction renderedType(\n ctx: ClientContext,\n type: string,\n operation: string,\n rel: string | undefined,\n): string | undefined {\n if (operation === 'fetchRelationship') {\n return undefined\n }\n if (operation !== 'fetchRelated') {\n return type\n }\n const relation = rel === undefined ? undefined : ctx.descriptor[type]?.relations[rel]\n return relation === undefined || isPolymorphic(relation) ? undefined : relation.types[0]\n}\n\n/** Whether a `relatedQuery` carries a filter or sort for any relation, so it reaches the wire. */\nfunction sendsRelatedQuery(relatedQuery: ReadQuery['relatedQuery']): boolean {\n return Object.values(relatedQuery ?? {}).some(\n (entry) =>\n Object.keys(entry?.filter ?? {}).length > 0 ||\n (entry?.sort !== undefined && entry.sort.length > 0),\n )\n}\n\n/**\n * Prepare a request's `relatedQuery` for resources of type `rendered`: match each entry's list\n * filters against its relation's related-read vocabulary, and negotiate the type's Relationship\n * Queries profile, after any Countable one, when the query sends an entry.\n */\nfunction applyRelatedQuery(\n ctx: ClientContext,\n rendered: string | undefined,\n query: ReadQuery,\n req: JsonApiRequest,\n): void {\n if (rendered === undefined || !sendsRelatedQuery(query.relatedQuery)) {\n return\n }\n const matchers = new Map<string, ((key: string) => boolean) | undefined>()\n req.relatedListFilter = (rel, key) => {\n if (!matchers.has(rel)) {\n matchers.set(rel, listFilterMatcher(filterSpec(ctx, rendered, 'fetchRelated', rel)))\n }\n return matchers.get(rel)?.(key) ?? false\n }\n const profile = ctx.descriptor[rendered]?.relatedQuery?.profile\n if (profile !== undefined && !(req.profiles ?? []).includes(profile)) {\n req.profiles = [...(req.profiles ?? []), profile]\n }\n}\n\n/**\n * Add the Countable profile a query's `withCount` requires to the request's negotiated\n * `profiles`. A `withCount` read or write needs it in `Accept`, else the server rejects it (400)\n * under strict query-param validation. The profile URI is read from the descriptor (never\n * hardcoded): the relation's `countable` for a related or relationship read, the operation's\n * `resourceCountable` entry for a single-resource read or a write, else the type's `countable`.\n */\nfunction negotiateProfiles(\n ctx: ClientContext,\n type: string,\n query: ReadQuery,\n req: JsonApiRequest,\n relationForCount?: string,\n operation?: string,\n): void {\n const profiles: string[] = []\n if (query.withCount !== undefined && query.withCount.length > 0) {\n const descriptor = ctx.descriptor[type]\n const profile =\n relationForCount !== undefined\n ? descriptor?.relations[relationForCount]?.countable?.profile\n : ((isResourceCountOperation(operation)\n ? descriptor?.resourceCountable?.[operation]?.profile\n : undefined) ?? descriptor?.countable?.profile)\n if (profile !== undefined) {\n profiles.push(profile)\n }\n }\n if (profiles.length > 0) {\n req.profiles = [...(req.profiles ?? []), ...profiles]\n }\n}\n\n/** Whether an operation is one answering with one resource that may take `withCount`. */\nfunction isResourceCountOperation(\n operation: string | undefined,\n): operation is ResourceCountOperation {\n return operation === 'fetchOne' || operation === 'create' || operation === 'update'\n}\n\n/**\n * A write opts object: an optional `include`/`fields` narrowing the materialised response, the\n * relations to count, a `relatedQuery` for its relationships, and `wait` to poll a\n * `202 Accepted` job until it's done.\n */\ninterface WriteOpts {\n include?: readonly string[]\n fields?: Record<string, readonly string[]>\n withCount?: readonly string[]\n relatedQuery?: ReadQuery['relatedQuery']\n wait?: boolean | PollOptions\n /** The request document's top-level `meta`. */\n meta?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Project a write's opts to the read-query families the response honours: `include`, `fields`,\n * `withCount` and `relatedQuery`.\n */\nfunction writeQuery(opts: WriteOpts | undefined): ReadQuery | undefined {\n if (opts === undefined) {\n return undefined\n }\n const query: ReadQuery = {}\n if (opts.include !== undefined) {\n query.include = [...opts.include]\n }\n if (opts.withCount !== undefined) {\n query.withCount = [...opts.withCount]\n }\n if (opts.relatedQuery !== undefined) {\n query.relatedQuery = opts.relatedQuery\n }\n if (opts.fields !== undefined) {\n const fields: Record<string, string[]> = {}\n for (const [k, v] of Object.entries(opts.fields)) {\n fields[k] = [...v]\n }\n query.fields = fields\n }\n return Object.keys(query).length > 0 ? query : undefined\n}\n\n/** A write's spec: how to address it, what to send, and how to shape the result + errors. */\ninterface WriteSpec {\n type: string\n operation: string\n vars: Record<string, string>\n method: string\n body: unknown\n query?: ReadQuery | undefined\n /** Materialise the primary `data` as identifier linkage (relationship endpoints) vs resources. */\n linkage?: boolean\n /** Remap a thrown error's pointers to flat input paths (resource-write vs relationship-write). */\n remap: (error: JsonApiError) => JsonApiError\n /** The `202 Accepted` the write declares, if any. */\n accepted?: AcceptedDescriptor | undefined\n /** Poll an accepted job until it's done, with these options. */\n wait?: PollOptions | undefined\n /** Resolve a meta-only document to its top-level `meta`, as a delete declaring it does. */\n metaOnly?: boolean\n}\n\n/** The poll options a call's `wait` asks for, or `undefined` when it doesn't wait. */\nconst waitOptions = (wait: boolean | PollOptions | undefined): PollOptions | undefined =>\n wait === true ? {} : wait === false ? undefined : wait\n\n/**\n * Answer a `202` the operation declares with an `Accepted`, or with its result when the caller\n * waits. The job is materialised, or is the top-level `meta` of a meta-only document; `complete`\n * shapes the document the job URL finally answers with, as the operation shapes its own.\n */\nfunction answerAccepted(\n ctx: ClientContext,\n accepted: AcceptedDescriptor,\n res: ExecutedResponse,\n complete: (doc: Document | undefined) => unknown,\n wait: PollOptions | undefined,\n): unknown {\n const value = toAccepted(\n {\n request: ctx.request,\n jobType: accepted.jobType,\n job: (doc) =>\n doc === undefined || !('data' in doc)\n ? (doc?.meta ?? {})\n : materialise(doc, ctx.materialise),\n complete,\n },\n res,\n )\n return wait === undefined ? value : value.$poll(wait)\n}\n\n/**\n * Drive a write: fill the path template, attach the body (and any `include`/`fields` query),\n * execute, and materialise the response (`undefined` for a `204`/no body — so create/update\n * return the resource and delete/`204` relationship mutations resolve `undefined`/`void`). A\n * `202` the write declares resolves to an `Accepted` job, or with `wait` to the polled result.\n * On a thrown {@link JsonApiError}, each error's flat `path` is populated (via `spec.remap`)\n * before it propagates, so a caller's `byPath()` keys are the flat input shape.\n */\nasync function runWrite(ctx: ClientContext, spec: WriteSpec): Promise<unknown> {\n const template = ctx.descriptor[spec.type]?.paths[spec.operation]\n if (template === undefined) {\n throw new Error(`No \"${spec.operation}\" path declared for type \"${spec.type}\"`)\n }\n const req: JsonApiRequest = {\n method: spec.method,\n path: fillPath(ctx, spec.type, template, spec.vars),\n body: spec.body,\n }\n if (spec.query !== undefined) {\n req.query = spec.query\n negotiateProfiles(ctx, spec.type, spec.query, req, undefined, spec.operation)\n applyRelatedQuery(ctx, spec.type, spec.query, req)\n if (req.profiles !== undefined) {\n // The profiles shape the response, not the body, so only `Accept` names them.\n req.contentType = JSON_API_MEDIA_TYPE\n }\n }\n if (spec.wait?.signal !== undefined) {\n req.signal = spec.wait.signal\n }\n let res\n try {\n res = await executeResponse(ctx.request, req)\n } catch (error) {\n if (error instanceof JsonApiError) {\n throw spec.remap(error)\n }\n throw error\n }\n // A meta-only result is not materialised, so it takes the document's stamp here.\n const complete = (doc: Document | undefined) =>\n stampFromDocument(\n doc,\n doc === undefined\n ? undefined\n : spec.metaOnly === true && !('data' in doc)\n ? doc.meta\n : materialise(\n doc,\n withFields(ctx.materialise, spec.query?.fields),\n spec.linkage ?? false,\n ),\n )\n if (res.status === 202 && spec.accepted !== undefined) {\n return answerAccepted(ctx, spec.accepted, res, complete, spec.wait)\n }\n return complete(res.document)\n}\n\n/**\n * Invoke a custom action over its declared HTTP method (`action.method`, default `POST`) at its\n * (filled) path, with a body shaped by the action's `input` mode:\n *\n * - `none` — no body;\n * - `document` — when the action names an `inputType`, FLAT input (the resource's attributes /\n * relationships) is built into the JSON:API envelope like `create`, and a `422`'s\n * `source.pointer`s are remapped to the flat paths; a bespoke command document (no `inputType`)\n * is sent verbatim;\n * - `raw` — the caller's payload, sent with the action's declared media type (e.g.\n * `application/octet-stream`), falling back to a wildcard when the spec declared none.\n *\n * An action listing several request media types (`inputMedia`) sends the one the caller picks\n * with `options.contentType`, or JSON:API when listed, else the first.\n *\n * The response is shaped by the action's `output`: `document` materialises into the resource /\n * collection view, `meta` returns the document's top-level `meta`, `none` resolves `undefined` (a\n * `204` / no body). A `metaResult` action returns the top-level `meta` of a document with no\n * `data`. An action declaring a `location` returns the URL of a location document as an\n * `ActionLocation` and never follows it. An action declaring `rawOutput` answers in the media type\n * the caller picks with `options.accept`: JSON:API as above, or a `string`, a `Blob` or\n * `ArrayBuffer`, or parsed JSON by the media type's kind. A collection action that takes filters\n * sends `options.filter` in the query string as a collection read does, and an action answering\n * with a resource sends `options.relatedQuery` as a read does. A `202` the action\n * declares resolves to an `Accepted` job, or with `options.wait` to the value its job URL ends at.\n */\nasync function runAction(\n ctx: ClientContext,\n action: ActionDescriptor,\n vars: Record<string, string>,\n input: unknown,\n options: ActionCallOptions = {},\n): Promise<unknown> {\n const req: JsonApiRequest = { method: action.method ?? 'POST', path: fill(action.path, vars) }\n if (options.signal !== undefined) {\n req.signal = options.signal\n }\n if (options.filter !== undefined) {\n req.query = { filter: options.filter }\n const listFilter = listFilterMatcher(action)\n if (listFilter !== undefined) {\n req.listFilter = listFilter\n }\n }\n if (options.relatedQuery !== undefined) {\n req.query = { ...req.query, relatedQuery: options.relatedQuery }\n applyRelatedQuery(ctx, action.outputType, req.query, req)\n }\n let remap: ((error: JsonApiError) => JsonApiError) | undefined\n const media = requestMedia(action, options.contentType)\n if (media !== undefined && media.kind !== 'document') {\n req.body = encodeFields(media.mediaType, media.kind, input)\n req.raw = true\n req.contentType = sentContentType(media.mediaType, media.kind, req.body)\n } else if (action.input === 'document') {\n if (action.inputType !== undefined) {\n // Flat input: build the envelope like create, and remap 422 pointers to the flat paths.\n const inputType = action.inputType\n req.body = withTopLevelMeta(\n toDocument(ctx.descriptor, inputType, (input ?? {}) as Record<string, unknown>),\n options.meta,\n )\n remap = (error) => withRemappedPaths(error, ctx.descriptor, inputType)\n } else {\n // A bespoke command document (no resolvable input type): pass the caller's envelope through.\n req.body =\n typeof input === 'object' && input !== null ? withTopLevelMeta(input, options.meta) : input\n remap = withRemappedDocumentMetaPaths\n }\n } else if (action.input === 'none' && options.meta !== undefined) {\n // An action taking no document may still declare its request `meta`, sent meta-only.\n req.body = { meta: options.meta }\n req.contentType = JSON_API_MEDIA_TYPE\n remap = withRemappedDocumentMetaPaths\n } else if (action.input === 'raw') {\n req.body = encodeFields(action.contentType ?? '*/*', undefined, input)\n // Send the action's declared media type (e.g. application/octet-stream); fall back to a\n // wildcard only when the spec declared none.\n req.contentType = sentContentType(action.contentType ?? '*/*', undefined, req.body)\n req.raw = true\n }\n if (req.profiles !== undefined && req.contentType === undefined) {\n // The Relationship Queries profile shapes the response, so only `Accept` names it.\n req.contentType = JSON_API_MEDIA_TYPE\n }\n\n const raw = responseMedia(action, options.accept)\n try {\n if (raw !== undefined) {\n req.accept = raw.mediaType\n if (raw.kind === 'binary') {\n return await executeRaw(\n ctx.request,\n req,\n options.responseType === 'arrayBuffer' ? 'arraybuffer' : 'blob',\n )\n }\n const text = await executeRaw(ctx.request, req, 'text')\n return raw.kind === 'json' && text !== undefined ? (JSON.parse(text) as unknown) : text\n }\n const res = await executeResponse(ctx.request, req)\n const complete = (doc: Document | undefined) =>\n stampFromDocument(doc, actionValue(ctx, action, doc))\n if (res.status === 202 && action.accepted !== undefined) {\n const wait = waitOptions(options.wait)\n const signal = wait?.signal ?? options.signal\n return answerAccepted(\n ctx,\n action.accepted,\n res,\n complete,\n wait === undefined || signal === undefined ? wait : { ...wait, signal },\n )\n }\n return complete(res.document)\n } catch (error) {\n if (remap !== undefined && error instanceof JsonApiError) {\n throw remap(error)\n }\n throw error\n }\n}\n\n/** Shape an action's JSON:API answer by its declared `output`, or its `location`. */\nfunction actionValue(\n ctx: ClientContext,\n action: ActionDescriptor,\n doc: Document | undefined,\n): unknown {\n if (action.location !== undefined) {\n const location = doc === undefined ? undefined : readActionLocation(doc, action.location)\n if (location !== undefined) {\n return location\n }\n if (action.output === 'location') {\n throw new Error('The action answered without the location document it declares.')\n }\n }\n if (action.output === 'none' || action.output === 'location' || doc === undefined) {\n return undefined\n }\n // A `metaResult` action's `200` is meta-only, while its `201` carries the resource it created.\n if (action.output === 'meta' || (action.metaResult === true && !('data' in doc))) {\n return doc.meta\n }\n return materialise(doc, ctx.materialise)\n}\n\n/**\n * The request media type an action with several (`inputMedia`) sends: the caller's pick, matched\n * exactly or through a declared wildcard such as `image/*`, else JSON:API when listed, else the\n * first. `undefined` for an action with a single request media type.\n */\nfunction requestMedia(\n action: ActionDescriptor,\n picked: string | undefined,\n): { mediaType: string; kind: InputMediaKind } | undefined {\n const listed = action.inputMedia\n if (listed === undefined || listed.length === 0) {\n if (picked !== undefined) {\n throw new Error(`This action declares no request media types to choose \"${picked}\" from.`)\n }\n return undefined\n }\n if (picked === undefined) {\n const media = listed.find((entry) => entry.mediaType === JSON_API_MEDIA_TYPE) ?? listed[0]!\n return { mediaType: media.mediaType, kind: media.kind }\n }\n const essence = picked.split(';')[0]!.trim().toLowerCase()\n const match =\n listed.find((entry) => entry.mediaType === essence) ??\n listed.find((entry) => entry.mediaType === `${essence.split('/')[0]}/*`) ??\n listed.find((entry) => entry.mediaType === '*/*')\n if (match === undefined) {\n throw new Error(\n `This action does not accept \"${picked}\"; it accepts ${listed.map((entry) => entry.mediaType).join(', ')}.`,\n )\n }\n return { mediaType: picked, kind: match.kind }\n}\n\n/**\n * A multipart or URL-encoded body given as a plain object of fields, encoded into a `FormData` or\n * `URLSearchParams`. Any other body, a ready `FormData` included, is sent as it is.\n */\nfunction encodeFields(mediaType: string, kind: InputMediaKind | undefined, body: unknown): unknown {\n const multipart = kind === 'multipart' || mediaType.startsWith('multipart/')\n const form = kind === 'form' || mediaType === 'application/x-www-form-urlencoded'\n if ((!multipart && !form) || !isPlainObject(body)) {\n return body\n }\n return multipart ? toFormData(body) : toSearchParams(body)\n}\n\n/** Whether a body is a plain object of fields rather than a ready payload. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false\n }\n const proto = Object.getPrototypeOf(value) as unknown\n return proto === Object.prototype || proto === null\n}\n\n/**\n * The entries a field contributes: nothing for `null` or `undefined`, one `name[]` entry per item\n * for an array (the bracket suffix is how PHP servers read a repeated field as a list), else one\n * `name` entry.\n */\nfunction fieldEntries(name: string, value: unknown): [string, unknown][] {\n if (value === null || value === undefined) {\n return []\n }\n if (Array.isArray(value)) {\n return value\n .filter((item) => item !== null && item !== undefined)\n .map((item): [string, unknown] => [`${name}[]`, item])\n }\n return [[name, value]]\n}\n\n/** A field's text value: booleans as `true` or `false`, everything else through `String`. */\nfunction fieldText(value: unknown): string {\n return typeof value === 'boolean' ? (value ? 'true' : 'false') : String(value)\n}\n\n/** A multipart body from fields. A `File` keeps its name; a bare `Blob` is named after its field. */\nfunction toFormData(fields: Record<string, unknown>): FormData {\n const data = new FormData()\n for (const [field, value] of Object.entries(fields)) {\n for (const [name, item] of fieldEntries(field, value)) {\n if (typeof Blob !== 'undefined' && item instanceof Blob) {\n const fileName =\n typeof File !== 'undefined' && item instanceof File && item.name !== ''\n ? item.name\n : field\n data.append(name, item, fileName)\n } else {\n data.append(name, fieldText(item))\n }\n }\n }\n return data\n}\n\n/** A URL-encoded body from fields. */\nfunction toSearchParams(fields: Record<string, unknown>): URLSearchParams {\n const params = new URLSearchParams()\n for (const [field, value] of Object.entries(fields)) {\n for (const [name, item] of fieldEntries(field, value)) {\n params.append(name, fieldText(item))\n }\n }\n return params\n}\n\n/**\n * The `Content-Type` for a non-JSON:API body. A multipart `FormData` body gets none, so the\n * transport writes the boundary. A wildcard media type takes a `Blob` body's own type.\n */\nfunction sentContentType(\n mediaType: string,\n kind: InputMediaKind | undefined,\n body: unknown,\n): string | null {\n if (\n (kind === 'multipart' || mediaType.startsWith('multipart/')) &&\n typeof FormData !== 'undefined' &&\n body instanceof FormData\n ) {\n return null\n }\n if (mediaType.includes('*') && typeof Blob !== 'undefined' && body instanceof Blob) {\n return body.type === '' ? mediaType : body.type\n }\n return mediaType\n}\n\n/**\n * The non-JSON:API media type an action is asked to answer in: the caller's `accept` when it isn't\n * JSON:API, else, with no `accept`, the first raw media type of an action that answers in no\n * JSON:API document. `undefined` means a JSON:API response.\n */\nfunction responseMedia(\n action: ActionDescriptor,\n accept: string | undefined,\n): { mediaType: string; kind: string } | undefined {\n const raw = action.rawOutput ?? []\n if (accept === undefined) {\n return action.output === 'none' ? raw[0] : undefined\n }\n if (accept === JSON_API_MEDIA_TYPE) {\n return undefined\n }\n const media = raw.find((entry) => entry.mediaType === accept)\n if (media === undefined) {\n throw new Error(\n `This action does not answer in \"${accept}\"; it answers in ${[...(action.output === 'none' ? [] : [JSON_API_MEDIA_TYPE]), ...raw.map((entry) => entry.mediaType)].join(', ')}.`,\n )\n }\n return media\n}\n\n/**\n * Build the typed `.actions` accessor at one scope: a plain object exposing exactly the\n * type's actions declared at `scope` (collection on the type accessor, resource on a handle),\n * each a function dispatching to {@link runAction} with the action descriptor + the scope's\n * path vars (resource scope supplies `{id}`). Names not declared at this scope are absent —\n * `client.albums.actions.reissue` (resource-scoped) is undefined; reach it via `.id(id)`.\n */\nfunction actionsAccessor(\n ctx: ClientContext,\n type: string,\n scope: ActionScope,\n vars: Record<string, string>,\n): ActionsAccessor<ApiDescriptor, unknown, unknown, string, ActionScope> {\n const actions = ctx.descriptor[type]?.actions ?? {}\n const out: Record<string, (...args: unknown[]) => Promise<unknown>> = {}\n for (const [name, action] of Object.entries(actions)) {\n if (action.scope === scope) {\n // An action without input takes only the options; any other takes the body first.\n out[name] = (...args: unknown[]) =>\n action.input === 'none'\n ? runAction(ctx, action, vars, undefined, args[0] as ActionCallOptions | undefined)\n : runAction(ctx, action, vars, args[0], args[1] as ActionCallOptions | undefined)\n }\n }\n return out as ActionsAccessor<ApiDescriptor, unknown, unknown, string, ActionScope>\n}\n\n/**\n * Build the relationship accessor for `client.<type>.id(id).<rel>`, or a singleton's\n * `client.<type>.<rel>` with no `id` in `vars`: reads\n * (`.get()` linkage / `.related()` collection) plus mutations — to-many `.add` (POST) /\n * `.remove` (DELETE) / `.replace` (PATCH) and to-one `.set` (PATCH). Every mutation posts\n * a `{ data: <linkage> }` body to `fetchRelationship` and materialises the response as\n * linkage (or `undefined`/`void` for a `204`). The cardinality is read off the descriptor\n * so the linkage is coerced correctly; the static types gate which verb is callable.\n */\nfunction relationshipAccessor(\n ctx: ClientContext,\n type: string,\n owner: Record<string, string>,\n rel: string,\n): RelationshipAccessor<ApiDescriptor, unknown, string, never> {\n const vars = { ...owner, rel }\n const relation = ctx.descriptor[type]?.relations[rel]\n const cardinality = relation?.cardinality ?? 'many'\n const hasPivot = relation?.pivot === true\n const mutate = (\n verb: 'add' | 'remove' | 'replace' | 'set',\n method: string,\n refs: unknown,\n opts: { meta?: Readonly<Record<string, unknown>> } | undefined,\n ): Promise<unknown> =>\n runWrite(ctx, {\n type,\n operation: 'fetchRelationship',\n vars,\n method,\n body: withTopLevelMeta(toRelationshipDocument(refs, cardinality), opts?.meta),\n linkage: true,\n remap: (error) => withRemappedRelationshipPaths(error, rel, hasPivot),\n metaOnly: relation?.mutationMeta?.[verb] !== undefined,\n })\n\n // Whether the relation advertises a mutation verb: the descriptor's `mutations` flags are\n // authoritative when present (mirrors the type-level `AdvertisesVerb`), so a verb the\n // bundle forbids (`cannotReplace` -> no PATCH) is absent at runtime, not just untyped. A\n // relation with no `mutations` block falls back to cardinality alone.\n const advertises = (verb: 'add' | 'remove' | 'replace' | 'set'): boolean => {\n const mutations = relation?.mutations\n return mutations === undefined ? true : mutations[verb] === true\n }\n\n // A read is present only when the relation exposes that endpoint (the descriptor's\n // `relationship`/`related` flags, from the bundle's `withoutRelationshipEndpoint()` /\n // `withoutRelatedEndpoint()`). A suppressed read is omitted (a JS caller gets \"not a function\"\n // rather than a 404); the static types gate it to `never` for a typed caller.\n // A write-only relation is never rendered, so it has neither read.\n const accessor: Record<string, unknown> = {}\n const readable = relation?.writeOnly !== true\n if (readable && relation?.relationship !== false) {\n accessor['get'] = (query?: RelationReadQuery) =>\n run(ctx, type, 'fetchRelationship', vars, query as ReadQuery | undefined, true, rel)\n }\n if (readable && relation?.related !== false) {\n accessor['related'] = (query?: RelationReadQuery) =>\n run(ctx, type, 'fetchRelated', vars, query as ReadQuery | undefined, false, rel)\n }\n type MutationOpts = { meta?: Readonly<Record<string, unknown>> } | undefined\n if (cardinality === 'many') {\n if (advertises('add')) {\n accessor['add'] = (refs: unknown, opts?: MutationOpts) => mutate('add', 'POST', refs, opts)\n }\n if (advertises('remove')) {\n accessor['remove'] = (refs: unknown, opts?: MutationOpts) =>\n mutate('remove', 'DELETE', refs, opts)\n }\n if (advertises('replace')) {\n accessor['replace'] = (refs: unknown, opts?: MutationOpts) =>\n mutate('replace', 'PATCH', refs, opts)\n }\n } else if (advertises('set')) {\n accessor['set'] = (ref: unknown, opts?: MutationOpts) => mutate('set', 'PATCH', ref, opts)\n }\n\n return accessor as unknown as RelationshipAccessor<ApiDescriptor, unknown, string, never>\n}\n\n/**\n * The reserved members on a {@link ResourceHandle} — names the Proxy resolves itself, so a\n * relation of the same name is shadowed and must route through `.rel(name)`. The codegen\n * imports this to warn at build time (keeping the runtime + the collision detector in sync).\n * `then` is reserved so a handle is never mistaken for a thenable.\n */\nexport const HANDLE_RESERVED: ReadonlySet<string> = new Set([\n 'type',\n 'id',\n 'get',\n 'update',\n 'delete',\n 'rel',\n 'actions',\n 'then',\n])\n\n/**\n * Run a type's update. `vars` fill its path (`{ id }`, or nothing for a singleton) and `id` is\n * the one the body carries.\n */\nfunction runUpdate(\n ctx: ClientContext,\n type: string,\n vars: Record<string, string>,\n id: string,\n patch: Record<string, unknown>,\n opts: WriteOpts | undefined,\n): Promise<unknown> {\n // The body is built inside `write`, so input the schema rejects never reaches toDocument().\n return withInputCheck(ctx.inputSchemas, { type, operation: 'update', input: patch }, () =>\n runWrite(ctx, {\n type,\n operation: 'update',\n vars,\n method: 'PATCH',\n body: withTopLevelMeta(toDocument(ctx.descriptor, type, patch, { id }), opts?.meta),\n query: writeQuery(opts),\n remap: (error) => withRemappedPaths(error, ctx.descriptor, type),\n accepted: ctx.descriptor[type]?.accepted?.update,\n wait: waitOptions(opts?.wait),\n }),\n )\n}\n\n/**\n * Wrap a handle's verbs in a Proxy resolving each relation not shadowed by a reserved member to\n * its relationship accessor, addressed by `vars`.\n */\nfunction withRelations<T extends object>(\n ctx: ClientContext,\n type: string,\n vars: Record<string, string>,\n base: T,\n): T {\n const relations = ctx.descriptor[type]?.relations ?? {}\n return new Proxy(base, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !HANDLE_RESERVED.has(prop) && prop in relations) {\n return relationshipAccessor(ctx, type, vars, prop)\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\n/** Build the id-scoped resource handle (a Proxy resolving relation accessors by name). */\nfunction resourceHandle(\n ctx: ClientContext,\n type: string,\n id: string,\n): ResourceHandle<ApiDescriptor, unknown, unknown, string> {\n const vars = { id }\n return withRelations(ctx, type, vars, {\n type,\n id,\n get: (query?: ReadQuery) => run(ctx, type, 'fetchOne', vars, query),\n update: (patch: Record<string, unknown>, opts?: WriteOpts) =>\n runUpdate(ctx, type, vars, id, patch, opts),\n delete: (opts?: { meta?: Readonly<Record<string, unknown>> }) =>\n runWrite(ctx, {\n type,\n operation: 'delete',\n vars,\n method: 'DELETE',\n // A delete declaring its request `meta` takes a meta-only document; any other, no body.\n body: opts?.meta === undefined ? undefined : { meta: opts.meta },\n remap: (error) => withRemappedPaths(error, ctx.descriptor, type),\n metaOnly: ctx.descriptor[type]?.documentMeta?.delete !== undefined,\n }) as never,\n rel: (name: string) => relationshipAccessor(ctx, type, vars, name),\n actions: actionsAccessor(ctx, type, 'resource', vars),\n }) as unknown as ResourceHandle<ApiDescriptor, unknown, unknown, string>\n}\n\n/**\n * Build the accessor of a singleton type (`client.inboxes`): a handle on the caller's one\n * resource, whose paths carry no id. Its update takes the resource's `id` in the input, since\n * the server reads it from the body.\n */\nfunction singletonAccessor(\n ctx: ClientContext,\n type: string,\n): SingletonAccessor<ApiDescriptor, unknown, unknown, string> {\n const vars = {}\n return withRelations(ctx, type, vars, {\n type,\n get: (query?: ReadQuery) => run(ctx, type, 'fetchOne', vars, query),\n update: (input: Record<string, unknown>, opts?: WriteOpts) => {\n const { id, ...patch } = input\n if (typeof id !== 'string' || id === '') {\n return Promise.reject(\n new Error(\n `Updating the \"${type}\" singleton needs its id in the input, such as the id of the resource its get() read.`,\n ),\n )\n }\n return runUpdate(ctx, type, vars, id, patch, opts)\n },\n rel: (name: string) => relationshipAccessor(ctx, type, vars, name),\n actions: actionsAccessor(ctx, type, 'resource', vars),\n }) as unknown as SingletonAccessor<ApiDescriptor, unknown, unknown, string>\n}\n\n/** Build the collection-scoped accessor for one wire type (`client.albums`). */\nfunction typeAccessor(\n ctx: ClientContext,\n type: string,\n): TypeAccessor<ApiDescriptor, unknown, unknown, string> {\n return {\n list: (query?: ReadQuery) => run(ctx, type, 'fetchMany', {}, query) as Promise<never>,\n get: (id: string, query?: ReadQuery) =>\n run(ctx, type, 'fetchOne', { id }, query) as Promise<never>,\n create: (input: Record<string, unknown>, opts?: WriteOpts) =>\n withInputCheck(ctx.inputSchemas, { type, operation: 'create', input }, () =>\n runWrite(ctx, {\n type,\n operation: 'create',\n vars: {},\n method: 'POST',\n body: withTopLevelMeta(toDocument(ctx.descriptor, type, input), opts?.meta),\n query: writeQuery(opts),\n remap: (error) => withRemappedPaths(error, ctx.descriptor, type),\n accepted: ctx.descriptor[type]?.accepted?.create,\n wait: waitOptions(opts?.wait),\n }),\n ) as Promise<never>,\n id: (id: string) => resourceHandle(ctx, type, id),\n actions: actionsAccessor(ctx, type, 'collection', {}),\n } as unknown as TypeAccessor<ApiDescriptor, unknown, unknown, string>\n}\n\n/**\n * Build a descriptor-driven read client. Generic at runtime (a Proxy over the descriptor),\n * not per-type codegen: `client.<type>` yields a {@link TypeAccessor}, or a\n * {@link SingletonAccessor} for a singleton type, `.id(id)` a handle,\n * and a handle's relation accessors drive the relationship/related endpoints. Navigation\n * (`$next()`/`$prev()`, related links) is wired through `materialise`'s `navigate` seam,\n * which resolves the server's link against `baseUrl`, executes it and re-materialises.\n */\nexport function createClient<\n D extends ApiDescriptor,\n A = DefaultAttributes<D>,\n W = DefaultWriteAttributes<D>,\n Act = DefaultActionTypes,\n E extends string = string,\n L = Record<never, never>,\n O = Record<never, never>,\n>(descriptor: D, options: ClientOptions): Client<D, A, W, Act, E, L, O> {\n const request: JsonApiContext = {\n baseUrl: options.baseUrl,\n transport: options.transport ?? fetchTransport,\n ...(options.headers !== undefined ? { headers: options.headers } : {}),\n ...(options.allowCrossOriginLinks !== undefined\n ? { allowCrossOriginLinks: options.allowCrossOriginLinks }\n : {}),\n }\n\n const validator = resolveValidator(options.validate)\n const ctx: ClientContext = {\n request,\n descriptor,\n ...(options.validateInput !== undefined ? { inputSchemas: options.validateInput } : {}),\n materialise: {\n descriptor,\n navigate: async (url, linkage = false, paginator, signal) => {\n const doc = await execute(request, {\n method: 'GET',\n path: url,\n link: true,\n ...(signal !== undefined ? { signal } : {}),\n })\n return doc === undefined\n ? undefined\n : materialise(\n doc,\n withFields(ctx.materialise, fieldsOfUrl(url)),\n linkage,\n undefined,\n paginator,\n )\n },\n ...(validator !== undefined ? { validate: validator } : {}),\n },\n }\n\n const atomicDescriptor = options.atomic ?? null\n // `client.atomic(tx => …)`: post the recorded batch to the atomic endpoint. Built once and\n // reused; throws when the server declares no atomic capability (`atomic` was null/omitted).\n // Typed via the single conditional-return `Client['atomic']` signature (tuple-of-handles ->\n // positional results; void -> loose results); the runtime forwards the callback to `runAtomic`.\n const atomic = (build: (tx: AtomicRecorder<D, W>) => unknown): Promise<unknown> => {\n if (atomicDescriptor === null) {\n throw new Error('This API does not expose an Atomic Operations endpoint')\n }\n return runAtomic(\n request,\n ctx.materialise,\n descriptor,\n atomicDescriptor.path,\n build as (tx: AtomicRecorder<D, W>) => void,\n ctx.inputSchemas,\n )\n }\n\n const accessors = new Map<\n string,\n | TypeAccessor<ApiDescriptor, unknown, unknown, string>\n | SingletonAccessor<ApiDescriptor, unknown, unknown, string>\n >()\n return new Proxy(Object.create(null) as object, {\n get(_target, prop) {\n if (prop === 'atomic') {\n return atomic\n }\n if (typeof prop !== 'string' || !(prop in descriptor)) {\n return undefined\n }\n let accessor = accessors.get(prop)\n if (accessor === undefined) {\n accessor =\n descriptor[prop]?.singleton === true\n ? singletonAccessor(ctx, prop)\n : typeAccessor(ctx, prop)\n accessors.set(prop, accessor)\n }\n return accessor\n },\n has(_target, prop) {\n return prop === 'atomic' || (typeof prop === 'string' && prop in descriptor)\n },\n }) as Client<D, A, W, Act, E, L, O>\n}\n","import { type CodesOf, errorText, type JsonApiErrorOf } from './error-shared'\nimport { JsonApiError, type JsonApiErrorObject } from './errors'\nimport { joinInputPath, splitInputPath } from './input-path'\nimport { InputValidationError, type StandardSchemaIssue } from './input-validation'\n\n/** One segment of a Standard Schema issue path: a key, or an array index. */\nexport type PathSegment = string | number\n\n/**\n * One error shaped as a Standard Schema issue (`message` plus `path` segments), so a form library\n * that takes Standard Schema issues takes it as is.\n */\nexport interface FieldError<C extends string = string> {\n /** The error's `detail`, else its `title`, else its `code`. */\n readonly message: string\n /** The input path as segments: `orderedTracks[0].$pivot.position` is `['orderedTracks', 0, '$pivot', 'position']`. Empty for a form-level error. */\n readonly path: readonly PathSegment[]\n /** The input path as the runtime keys it, `''` for a form-level error. */\n readonly key: string\n readonly code?: C | (string & {})\n /** The failing operation's index in an atomic batch. */\n readonly opIndex?: number\n /** The error object as the server sent it, with its remapped `path`. Absent for an {@link InputValidationError}'s issue. */\n readonly error?: JsonApiErrorObject<C>\n}\n\n/** A write's errors for a form, split into the inputs they point at and the rest. */\nexport interface FieldErrors<I = unknown, C extends string = string> {\n /** Errors on an input, grouped by its path. */\n readonly fields: Readonly<Record<string, readonly FieldError<C>[]>>\n /** Errors that point at no input: no `source`, a `source.parameter` or `source.header`, or a pointer the client owns, such as `/data/type`. */\n readonly form: readonly FieldError<C>[]\n /** Every error, in the order the server sent them. */\n readonly issues: readonly FieldError<C>[]\n /** The first message on the input at `path`. */\n first(path: InputPath<I>): string | undefined\n /** Every message on the input at `path`. */\n messages(path: InputPath<I>): string[]\n /** Only the errors of the atomic operation at `index`. */\n op(index: number): FieldErrors<unknown, C>\n}\n\ndeclare const writeInput: unique symbol\n\n/**\n * A {@link JsonApiError} tagged with the input of the write that raised it, at the type level\n * only, so {@link fieldErrors} types its paths without a type argument.\n */\nexport type WriteError<C extends string = string, I = unknown> = JsonApiError<C> & {\n readonly [writeInput]?: I\n}\n\ntype InputOf<E> = [JsonApiErrorOf<E>] extends [never]\n ? unknown\n : JsonApiErrorOf<E> extends { readonly [writeInput]?: infer I }\n ? I\n : unknown\n\ntype Scalar = string | number | boolean | bigint | symbol | Date\n\n/** The next depth down; the paths stop at four levels of nesting. */\ntype Deeper = [never, 0, 1, 2, 3]\n\n/**\n * Every path the runtime can key an error on for write input `I`: attribute keys, nested map\n * keys joined with `.`, to-many members as `[n]` with their `$pivot` fields, `$meta` members, and\n * `$documentMeta` members. A union-typed value contributes only the keys its members share. Any\n * string when `I` is unknown.\n */\nexport type InputPath<I> = unknown extends I ? string : KeyPaths<I, 4> | `$documentMeta.${string}`\n\ntype KeyPaths<T, D extends number> = [D] extends [never]\n ? never\n : [T] extends [object]\n ? { [K in keyof T & string]-?: K | `${K}${SubPaths<NonNullable<T[K]>, D>}` }[keyof T & string]\n : never\n\ntype SubPaths<V, D extends number> = [V] extends [never]\n ? never\n : [V] extends [readonly (infer M)[]]\n ? `[${number}]` | `[${number}]${MemberPaths<NonNullable<M>, D>}`\n : MemberPaths<V, D>\n\n// A linkage ref (it has `type`) contributes only its `$pivot` fields.\ntype MemberPaths<V, D extends number> = [V] extends [Scalar]\n ? never\n : 'type' extends keyof V\n ? [V] extends [{ $pivot?: infer P }]\n ? P extends object\n ? '.$pivot' | `.$pivot.${keyof P & string}`\n : never\n : never\n : `.${KeyPaths<V, Deeper[D]>}`\n\n/**\n * The 4xx `error`'s errors keyed by the write input they point at, or `undefined` when `error`\n * is not a 4xx {@link JsonApiError} or none of its errors points at an input. An\n * {@link InputValidationError} gives its issues the same way. Pass the input type when `error`\n * carries none: `fieldErrors<Parameters<typeof client.albums.create>[0]>(caught)`.\n */\nexport function fieldErrors<I = never, E = unknown>(\n error: E,\n): FieldErrors<[I] extends [never] ? InputOf<E> : I, CodesOf<E>> | undefined\nexport function fieldErrors(error: unknown): FieldErrors | undefined {\n if (error instanceof InputValidationError) {\n return group(error.issues.map((issue) => fromIssue(issue, error.opIndex)))\n }\n if (!(error instanceof JsonApiError) || !error.is4xx()) {\n return undefined\n }\n const issues = error.errors.map(toFieldError)\n return issues.some((issue) => issue.key !== '') ? group(issues) : undefined\n}\n\nfunction group<C extends string>(issues: readonly FieldError<C>[]): FieldErrors<unknown, C> {\n const fields: Record<string, FieldError<C>[]> = {}\n const form: FieldError<C>[] = []\n for (const issue of issues) {\n if (issue.key === '') {\n form.push(issue)\n } else {\n ;(fields[issue.key] ??= []).push(issue)\n }\n }\n return {\n fields,\n form,\n issues,\n first: (path) => fields[path]?.[0]?.message,\n messages: (path) => fields[path]?.map((issue) => issue.message) ?? [],\n op: (index) => group(issues.filter((issue) => issue.opIndex === index)),\n }\n}\n\nfunction toFieldError<C extends string>(error: JsonApiErrorObject<C>): FieldError<C> {\n // The runtime leaves a pointer it can't map to an input verbatim, so it still starts with `/`.\n const key = error.path === undefined || error.path.startsWith('/') ? '' : error.path\n return {\n message: errorText(error, true) ?? 'Invalid',\n path: splitInputPath(key),\n key,\n ...(error.code === undefined ? {} : { code: error.code }),\n ...(error.opIndex === undefined ? {} : { opIndex: error.opIndex }),\n error,\n }\n}\n\nfunction fromIssue(issue: StandardSchemaIssue, opIndex: number | undefined): FieldError {\n const path = (issue.path ?? []).map((segment) => {\n const key = typeof segment === 'object' ? segment.key : segment\n return typeof key === 'number' ? key : String(key)\n })\n const key = joinInputPath(path)\n return { message: issue.message, path, key, ...(opIndex === undefined ? {} : { opIndex }) }\n}\n","import type { Collection } from './result-types'\n\n/** Options for {@link loadAll}. */\nexport interface LoadAllOptions {\n /** Stops the walk, rejecting with the signal's reason. */\n signal?: AbortSignal\n /** Stop after this many pages, as a guard against an unexpectedly large collection. */\n maxPages?: number\n}\n\n/**\n * Follow `next` links from a first page until the last, and return every member in one plain\n * array. It takes any collection: a list, a related read, or a to-many relationship of a resource\n * you read, which holds only its first page of members when the server renders its linkage:\n *\n * ```ts\n * const album = await client.albums.get('1', { include: ['tracks'] })\n * const tracks = await loadAll(album.tracks)\n * ```\n */\nexport async function loadAll<T>(\n first: Collection<T> | PromiseLike<Collection<T>>,\n options: LoadAllOptions = {},\n): Promise<T[]> {\n const { signal, maxPages = Number.POSITIVE_INFINITY } = options\n let page: Collection<T> | undefined = await first\n const all: T[] = []\n let count = 0\n while (page !== undefined && count < maxPages) {\n all.push(...page)\n count++\n if (count >= maxPages) {\n break\n }\n signal?.throwIfAborted()\n page = await page.$next(signal !== undefined ? { signal } : undefined)\n }\n return all\n}\n","import type { ApiDescriptor } from './descriptor'\nimport { materialise, type MaterialiseContext } from './materialise'\nimport type { Document } from './request'\n\n/** One resource as plain data: `type`, `id`, attributes, and relation values by name. */\nexport interface MockData {\n readonly type: string\n readonly id: string\n}\n\ntype DataObject = MockData & Readonly<Record<string, unknown>>\n\n/** The members a linkage member carries beside its identity, which never become attributes. */\nconst MEMBER_KEYS = new Set(['type', 'id', 'meta', '$pivot'])\n\n/**\n * Build a materialised resource from its plain data, as a read returns it: the relations the data\n * nests hydrate, the identifiers stay identifiers, and each member's `$pivot` lands on its linkage\n * `meta.pivot`, so `$pivot`, `$edge`, `$rel` and `$count` all work. For tests and stories; the\n * generated client binds it to its descriptor and types it.\n */\nexport function mockResource(descriptor: ApiDescriptor, data: MockData): object {\n return materialise(mockDocument(descriptor, data), mockContext(descriptor)) as object\n}\n\n/** {@link mockResource} for a collection of type `type`, as a list read returns it. */\nexport function mockCollection(\n descriptor: ApiDescriptor,\n type: string,\n data: readonly MockData[],\n): object {\n return materialise(mockDocument(descriptor, data), mockContext(descriptor), false, type) as object\n}\n\nfunction mockContext(descriptor: ApiDescriptor): MaterialiseContext {\n return {\n descriptor,\n navigate: () =>\n Promise.reject(new Error('A mock resource has no server to follow its links to.')),\n }\n}\n\n/** The JSON:API document plain data stands for: the primary data, and every nested resource in `included`. */\nexport function mockDocument(\n descriptor: ApiDescriptor,\n data: MockData | readonly MockData[],\n): Document {\n const primary = new Set<string>()\n const included = new Map<string, Record<string, unknown>>()\n const toResource = (value: DataObject): Record<string, unknown> => {\n const relations = descriptor[value.type]?.relations ?? {}\n const attributes: Record<string, unknown> = {}\n const relationships: Record<string, unknown> = {}\n for (const [key, member] of Object.entries(value)) {\n if (key === 'type' || key === 'id') {\n continue\n }\n if (key in relations) {\n if (member !== undefined) {\n relationships[key] = { data: linkageOf(member) }\n }\n } else if (key !== 'meta' && key !== '$pivot') {\n attributes[key] = member\n }\n }\n return {\n type: value.type,\n id: value.id,\n ...(Object.keys(attributes).length > 0 ? { attributes } : {}),\n ...(Object.keys(relationships).length > 0 ? { relationships } : {}),\n ...(value['meta'] !== undefined ? { meta: value['meta'] } : {}),\n }\n }\n const linkageOf = (value: unknown): unknown => {\n if (value === null) {\n return null\n }\n if (Array.isArray(value)) {\n return value.map((member: DataObject) => identifierOf(member))\n }\n return identifierOf(value as DataObject)\n }\n const identifierOf = (member: DataObject): Record<string, unknown> => {\n const id = `${member.type}:${member.id}`\n if (isFullResource(member) && !primary.has(id) && !included.has(id)) {\n // Reserve the slot first so a nested cycle back to this member stops here.\n included.set(id, {})\n included.set(id, toResource(member))\n }\n const pivot = (member as { $pivot?: unknown }).$pivot\n const meta = member['meta'] as Record<string, unknown> | undefined\n const linkageMeta = pivot === undefined ? meta : { ...meta, pivot }\n return {\n type: member.type,\n id: member.id,\n ...(linkageMeta !== undefined ? { meta: linkageMeta } : {}),\n }\n }\n const list = (Array.isArray(data) ? data : [data]) as readonly DataObject[]\n for (const value of list) {\n primary.add(`${value.type}:${value.id}`)\n }\n const resources = list.map(toResource)\n return {\n data: Array.isArray(data) ? resources : resources[0],\n ...(included.size > 0 ? { included: [...included.values()] } : {}),\n }\n}\n\n/** Whether a relation member carries more than its identity, so it stands for an included resource. */\nfunction isFullResource(member: DataObject): boolean {\n return Object.keys(member).some((key) => !MEMBER_KEYS.has(key))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,IAAI,QAAQ;;;;;;AAOZ,SAAgB,mBAA2B;CACzC,SAAS;CACT,OAAO;AACT;AAEA,MAAM,yBAAS,IAAI,QAAwB;;;;;;AAO3C,SAAgB,aAAgB,OAAU,OAAkB;CAC1D,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO,IAAI,OAAO,KAAK;CAEzB,OAAO;AACT;AAEA,MAAM,iCAAiB,IAAI,QAAwB;;;;;;AAOnD,SAAgB,cAAc,KAAyB,OAAqB;CAC1E,IAAI,QAAQ,KAAA,GACV,eAAe,IAAI,KAAK,KAAK;AAEjC;;;;;AAMA,SAAgB,kBAAqB,KAAyB,OAAa;CACzE,MAAM,QAAQ,QAAQ,KAAA,IAAY,KAAA,IAAY,eAAe,IAAI,GAAG;CACpE,OAAO,UAAU,KAAA,IAAY,QAAQ,aAAa,OAAO,KAAK;AAChE;;;;;;;AAQA,SAAgB,eAAe,OAAoC;CACjE,OAAO,OAAO,UAAU,YAAY,UAAU,OAAO,OAAO,IAAI,KAAK,IAAI,K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Object","isObject","isObject"],"sources":["../src/request-stamp.ts","../src/types.ts","../src/request.ts","../src/accepted.ts","../src/pagination.ts","../src/materialise.ts","../src/input-validation.ts","../src/input-path.ts","../src/serialize-write.ts","../src/atomic.ts","../src/descriptor.ts","../src/filters.ts","../src/location.ts","../src/transport.ts","../src/client.ts","../src/field-errors.ts","../src/load-all.ts","../src/mock.ts"],"sourcesContent":["/**\n * Request stamps: when the request behind a result started, relative to every other request made in\n * this process.\n *\n * The client takes a stamp as each request starts and records it on the top-level value it\n * materialises from the response: a read's resource, collection or linkage (`$next()`/`$prev()`\n * pages included), a write's returned resource, and an atomic batch's results. A cache can then\n * tell which of two results carrying the same resource is the newer, whatever order their\n * responses arrived in.\n *\n * The stamp is a per-process counter rather than `Date.now()`: two requests started in the same\n * millisecond still get distinct, ordered stamps, and a clock change can't reorder them. It means\n * nothing outside the process that issued it, so a value that crossed one (through JSON on a server\n * render, or storage) carries none. Stamps live in a `WeakMap` keyed by the result, so the result\n * keeps its shape and nothing is added to it.\n *\n * @internal\n */\n\n/** The last stamp handed out; `0` is older than any request (no request is ever stamped `0`). */\nlet clock = 0\n\n/**\n * A new stamp, later than every stamp handed out before it. The client takes one as each request\n * starts; anything ordering its own events against the client's requests takes them here too.\n * @internal\n */\nexport function nextRequestStamp(): number {\n clock += 1\n return clock\n}\n\nconst stamps = new WeakMap<object, number>()\n\n/**\n * Record `stamp` as the start of the request `value` was materialised from, when it is an object.\n * Returns `value`.\n * @internal\n */\nexport function stampRequest<T>(value: T, stamp: number): T {\n if (typeof value === 'object' && value !== null) {\n stamps.set(value, stamp)\n }\n return value\n}\n\nconst documentStamps = new WeakMap<object, number>()\n\n/**\n * Record `stamp` on the response document it was parsed from, so whatever is built from the\n * document can be stamped without the caller carrying the number.\n * @internal\n */\nexport function stampDocument(doc: object | undefined, stamp: number): void {\n if (doc !== undefined) {\n documentStamps.set(doc, stamp)\n }\n}\n\n/**\n * Stamp `value` with the request stamp of `doc`, when `doc` carries one. Returns `value`.\n * @internal\n */\nexport function stampFromDocument<T>(doc: object | undefined, value: T): T {\n const stamp = doc === undefined ? undefined : documentStamps.get(doc)\n return stamp === undefined ? value : stampRequest(value, stamp)\n}\n\n/**\n * The stamp of the request `value` was materialised from: a top-level result the client returned.\n * `undefined` for anything else, such as a plain copy of a result, a nested resource, or data the\n * client never returned.\n * @internal\n */\nexport function requestStampOf(value: unknown): number | undefined {\n return typeof value === 'object' && value !== null ? stamps.get(value) : undefined\n}\n","/** The JSON:API media type. */\nexport const JSON_API_MEDIA_TYPE = 'application/vnd.api+json'\n\n/** The Atomic Operations extension URI. */\nexport const ATOMIC_EXT = 'https://jsonapi.org/ext/atomic'\n\n/**\n * The media-type parameters a request opts into: extension URIs (`ext`) and/or profile URIs\n * (`profile`). Each is rendered as a space-joined, quoted media-type parameter per RFC 6839 /\n * the JSON:API spec (`ext=\"<uri> <uri>\"`, `profile=\"<uri> <uri>\"`).\n */\nexport interface MediaTypeParams {\n ext?: readonly string[] | undefined\n profiles?: readonly string[] | undefined\n}\n\n/**\n * Compose the JSON:API media type with any opted-in `ext`/`profile` parameters. Each parameter\n * is a space-joined, double-quoted URI list, in the canonical order `ext` then `profile` so the\n * output is deterministic (stable for caching/assertions). Empty/absent lists are omitted; with\n * neither, the bare {@link JSON_API_MEDIA_TYPE} is returned (no behaviour change for a plain\n * request). Used for both `Accept` and (when a body is present) `Content-Type`.\n */\nexport function mediaType(params: MediaTypeParams = {}): string {\n let out = JSON_API_MEDIA_TYPE\n if (params.ext !== undefined && params.ext.length > 0) {\n out += `; ext=\"${params.ext.join(' ')}\"`\n }\n if (params.profiles !== undefined && params.profiles.length > 0) {\n out += `; profile=\"${params.profiles.join(' ')}\"`\n }\n return out\n}\n\n/**\n * The media type for an Atomic Operations request/response: the JSON:API media type carrying\n * the atomic `ext` parameter. Sent as both `Content-Type` and `Accept` on a `client.atomic`\n * batch (per the JSON:API atomic extension).\n */\nexport const ATOMIC_MEDIA_TYPE = mediaType({ ext: [ATOMIC_EXT] })\n\n/** A resource identifier: the shape a non-included but linked relation takes. */\nexport interface ResourceIdentifier<TType extends string = string> {\n type: TType\n id: string\n meta?: Record<string, unknown>\n}\n\n/** A local id reference used inside an atomic transaction (`{ type, lid }`). */\nexport interface LocalIdentifier<TType extends string = string> {\n type: TType\n lid: string\n}\n","import type { HeadersInit } from './client'\nimport { JsonApiError, type JsonApiErrorObject } from './errors'\nimport type {\n JsonApiTransport,\n TransportRawBody,\n TransportRequest,\n TransportResponse,\n} from './transport'\nimport { nextRequestStamp, stampDocument } from './request-stamp'\nimport { mediaType } from './types'\n\n/**\n * A read query, in the flat shape the fluent surface accepts. Serialised to the\n * JSON:API bracketed query-parameter families by {@link serializeQuery}.\n */\nexport interface ReadQuery {\n filter?: Record<string, unknown>\n sort?: string | string[]\n include?: string[]\n fields?: Record<string, string[]>\n /** Relationship-count tokens (the Countable profile) — serialised comma-joined onto `withCount`. */\n withCount?: readonly string[]\n /**\n * A `filter` and `sort` per relation (the Relationship Queries profile), serialised as\n * `relatedQuery[<relation>][filter][<key>]` and `relatedQuery[<relation>][sort]`.\n */\n relatedQuery?: Readonly<\n Record<\n string,\n { filter?: Readonly<Record<string, unknown>>; sort?: string | readonly string[] } | undefined\n >\n >\n page?: Record<string, unknown>\n /** Cancels the read when signalled. Never serialised; passed to the transport. */\n signal?: AbortSignal\n}\n\n/** A loose JSON:API document — enough structure for the runtime to materialise. */\nexport interface Document {\n data?: unknown\n included?: unknown[]\n links?: Record<string, unknown>\n meta?: Record<string, unknown>\n jsonapi?: Record<string, unknown>\n}\n\n/** The ambient context a request executes in (carried by the client). */\nexport interface JsonApiContext {\n baseUrl: string\n transport: JsonApiTransport\n headers?: () => HeadersInit | Promise<HeadersInit>\n /** Follow server links to another origin, without {@link headers}. Off by default. */\n allowCrossOriginLinks?: boolean\n}\n\n/** A single read/write request, before serialisation. */\nexport interface JsonApiRequest {\n method: string\n /**\n * A path appended to `baseUrl` (a filled path template such as `/albums/1`), or an absolute\n * `http(s)://` URL. With {@link link} set, a link from the server instead.\n */\n path: string\n /**\n * `path` is a link the server sent (a `links` member such as `next`, or a `Location` header).\n * It resolves against `baseUrl` per RFC 3986, so a root-relative `/api/v5/albums?page[number]=2`\n * keeps the base's origin but not its path, where a path template is appended to the base.\n */\n link?: boolean\n query?: ReadQuery\n /**\n * The filter keys of {@link query} that take a list, sent as `filter[<key>][]` once per member.\n * The client sets it from the descriptor; without it an array filter value is comma-joined.\n */\n listFilter?: (key: string) => boolean\n /**\n * The filter keys of a {@link ReadQuery.relatedQuery} entry that take a list, by the entry's\n * relation. The client sets it from that relation's related-read vocabulary.\n */\n relatedListFilter?: (relation: string, key: string) => boolean\n body?: unknown\n /**\n * Override the request `Content-Type`, which defaults to the negotiated JSON:API media type on\n * every `POST` and on any other request with a body. Set for a custom action's non-JSON:API\n * input. When set it wins over {@link ext}/{@link profiles} for `Content-Type`; `null` sends\n * none, so the transport can write a multipart body's boundary itself.\n */\n contentType?: string | null\n /**\n * Override the request `Accept` header (defaults to the negotiated JSON:API media type). Set\n * for a `raw`-input action that still expects a document response; when set it wins over\n * {@link ext}/{@link profiles} for `Accept`.\n */\n accept?: string\n /**\n * Extension URIs to negotiate (the media-type `ext` parameter), e.g. the atomic ext. Composed\n * into both `Accept` and (when a body is present) `Content-Type` via the JSON:API media type,\n * unless {@link accept}/{@link contentType} override the respective header.\n */\n ext?: readonly string[]\n /**\n * Profile URIs to negotiate (the media-type `profile` parameter), e.g. the Countable profile a\n * `withCount` read requires. Composed into both `Accept` and (when a body is present)\n * `Content-Type`, unless {@link accept}/{@link contentType} override the respective header.\n */\n profiles?: readonly string[]\n /**\n * Send the body verbatim instead of JSON-stringifying it: a string, or a binary, `FormData` or\n * `URLSearchParams` body. Used for a custom action's non-JSON:API input; any other value still\n * falls back to `JSON.stringify`.\n */\n raw?: boolean\n /** Passed through to the transport so the caller can cancel the request. */\n signal?: AbortSignal\n}\n\nconst isAbsolute = (path: string): boolean => /^https?:\\/\\//i.test(path)\n\n// Stands in for the origin when `baseUrl` is relative and there's no page to resolve it against.\nconst RELATIVE_ORIGIN = 'http://relative.invalid'\n\n/** A server link resolved for following, and whether it stays on the base URL's origin. */\ninterface ResolvedLink {\n url: string\n sameOrigin: boolean\n}\n\n/**\n * Resolve a server link against `baseUrl` per RFC 3986 and check where it lands. A link on the\n * base's origin is followed; a relative base (e.g. `/api`) takes the page's origin in a browser and\n * otherwise only accepts a link that keeps the host. Anything that isn't plain http(s) is refused.\n */\nfunction resolveLink(link: string, baseUrl: string): ResolvedLink {\n // The URL parser drops tabs and newlines and trims control characters, so check what it sees.\n let normalised = link.replace(/[\\t\\n\\r]/g, '')\n let start = 0\n while (start < normalised.length && normalised.charCodeAt(start) <= 0x20) start++\n normalised = normalised.slice(start)\n const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalised)?.[1]?.toLowerCase()\n if (scheme !== undefined && scheme !== 'http' && scheme !== 'https') {\n throw new Error(`Refusing to follow link \"${link}\": only http(s) links are followed`)\n }\n\n const relativeBase = !isAbsolute(baseUrl)\n const page = (globalThis as { location?: { href?: unknown } }).location?.href\n const base = new URL(\n baseUrl,\n relativeBase ? (typeof page === 'string' ? page : RELATIVE_ORIGIN) : undefined,\n )\n const resolved = new URL(link, base)\n // `https:host` names a scheme without `//`, which the parser may read as a path or a host.\n const sameOrigin =\n resolved.origin === base.origin && (scheme === undefined || /^https?:\\/\\//i.test(normalised))\n\n if (!sameOrigin) {\n return { url: resolved.href, sameOrigin }\n }\n return {\n url: relativeBase ? resolved.pathname + resolved.search + resolved.hash : resolved.href,\n sameOrigin,\n }\n}\n\nconst append = (parts: string[], key: string, value: unknown): void => {\n if (value === undefined || value === null || value === '') {\n return\n }\n parts.push(`${key}=${encodeURIComponent(String(value))}`)\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Append a filter value under its (already-bracketed) key. A plain object is a STRUCTURED filter\n * value — a `Range`/`DateRange` deepObject (`{ min, max }`) — and recurses into nested bracketed\n * keys (`filter[k][min]=`), matching the server's deepObject wire shape; an array goes out once per\n * member as `filter[k][]=` for a filter that takes a list, so a member may hold a comma, and joins\n * with `,` otherwise; a scalar is appended directly. Without the object branch a `{ min, max }` value would reach the\n * wire as `filter[k]=[object Object]` and be silently ignored by the server.\n */\nconst appendFilterValue = (parts: string[], key: string, value: unknown, list = false): void => {\n if (isPlainObject(value)) {\n for (const [subKey, subValue] of Object.entries(value)) {\n appendFilterValue(parts, `${key}[${subKey}]`, subValue)\n }\n return\n }\n if (list && Array.isArray(value)) {\n for (const member of value) {\n append(parts, `${key}[]`, member)\n }\n return\n }\n append(parts, key, Array.isArray(value) ? value.join(',') : value)\n}\n\n/**\n * Serialise a read query to a query string (no leading `?`). Bracketed keys\n * (`filter[title]`, `page[number]`, `fields[albums]`) are kept literal; only values\n * are percent-encoded. `isListFilter` names the filter keys that take a list, whose array value\n * goes out as `filter[<key>][]` once per member, and `isRelatedListFilter` does the same for a\n * `relatedQuery` entry's filters by relation. Empty/undefined entries are skipped; key order is deterministic\n * (family order, then insertion order within a family) so URLs are stable for caching.\n */\nexport function serializeQuery(\n query: ReadQuery,\n isListFilter?: (key: string) => boolean,\n isRelatedListFilter?: (relation: string, key: string) => boolean,\n): string {\n const parts: string[] = []\n\n if (query.filter) {\n for (const [key, value] of Object.entries(query.filter)) {\n appendFilterValue(parts, `filter[${key}]`, value, isListFilter?.(key) ?? false)\n }\n }\n\n if (query.sort !== undefined) {\n append(parts, 'sort', Array.isArray(query.sort) ? query.sort.join(',') : query.sort)\n }\n\n if (query.include) {\n append(parts, 'include', query.include.join(','))\n }\n\n if (query.fields) {\n for (const [type, names] of Object.entries(query.fields)) {\n // An explicitly-empty fieldset (`fields[type]=`) is meaningful in JSON:API — it selects NO\n // members of that type (id-only), which is exactly what the return type narrows to. Emit the\n // empty param verbatim (the generic empty-skip would drop it, leaving the type over-narrowed\n // vs. the full resource the server would otherwise return).\n parts.push(`fields[${type}]=${encodeURIComponent(names.join(','))}`)\n }\n }\n\n if (query.withCount && query.withCount.length > 0) {\n append(parts, 'withCount', query.withCount.join(','))\n }\n\n for (const [relation, entry] of Object.entries(query.relatedQuery ?? {})) {\n for (const [key, value] of Object.entries(entry?.filter ?? {})) {\n appendFilterValue(\n parts,\n `relatedQuery[${relation}][filter][${key}]`,\n value,\n isRelatedListFilter?.(relation, key) ?? false,\n )\n }\n if (entry?.sort !== undefined) {\n append(\n parts,\n `relatedQuery[${relation}][sort]`,\n typeof entry.sort === 'string' ? entry.sort : entry.sort.join(','),\n )\n }\n }\n\n if (query.page) {\n for (const [key, value] of Object.entries(query.page)) {\n append(parts, `page[${key}]`, Array.isArray(value) ? value.join(',') : value)\n }\n }\n\n return parts.join('&')\n}\n\n/**\n * Execute a request: build the URL (a server link resolved against `baseUrl` and held to its\n * origin, an absolute path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request headers,\n * then drive the transport. A 2xx with a body parses to a {@link Document}; an empty /\n * 204 body resolves to `undefined`. A non-2xx throws a {@link JsonApiError} carrying the\n * parsed error objects (tolerating a non-JSON error body with an empty list).\n */\nexport async function execute(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n): Promise<Document | undefined> {\n const stamp = nextRequestStamp()\n const res = await send(ctx, req)\n const doc = parseDocument(res.body)\n stampDocument(doc, stamp)\n return doc\n}\n\n/** A response's status and headers beside its parsed {@link Document}. */\nexport interface ExecutedResponse {\n status: number\n headers: Record<string, string>\n document: Document | undefined\n /** The stamp taken as the request started; the document carries it too. */\n stamp: number\n}\n\n/**\n * Execute a request as {@link execute} does, keeping the response's status and headers. With\n * `seeOther`, a `303` the transport didn't follow resolves with no document instead of throwing,\n * so the caller can read its `Location`.\n */\nexport async function executeResponse(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n seeOther = false,\n): Promise<ExecutedResponse> {\n const stamp = nextRequestStamp()\n const res = await send(ctx, req, undefined, seeOther)\n const document = res.status === 303 ? undefined : parseDocument(res.body)\n stampDocument(document, stamp)\n return { status: res.status, headers: res.headers, document, stamp }\n}\n\n/** How {@link executeRaw} reads a successful response body. */\nexport type RawResponseType = 'text' | 'blob' | 'arraybuffer'\n\n/**\n * Execute a request whose successful response is not JSON:API, such as a custom action's CSV\n * export or image, and return its body as text or binary. Everything else matches\n * {@link execute}: the same URL, headers and negotiation, and a non-2xx still throws a\n * {@link JsonApiError} parsed from the JSON:API error document. A `204` or empty text body\n * resolves to `undefined`.\n */\nexport async function executeRaw(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n as: 'blob' | 'arraybuffer',\n): Promise<Blob | ArrayBuffer | undefined>\nexport async function executeRaw(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n as: 'text',\n): Promise<string | undefined>\nexport async function executeRaw(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n as: RawResponseType,\n): Promise<string | Blob | ArrayBuffer | undefined> {\n const res = await send(ctx, req, as === 'text' ? undefined : as)\n if (as === 'text') {\n return res.body === '' ? undefined : res.body\n }\n if (res.status === 204) {\n return undefined\n }\n if (res.binary === undefined) {\n throw new Error(\n '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.',\n )\n }\n return res.binary\n}\n\n/**\n * Build the URL (a server link resolved against `baseUrl` and held to its origin, an absolute\n * path verbatim, else `baseUrl + path`), apply content negotiation and any async per-request\n * headers, then drive the transport. A non-2xx throws a {@link JsonApiError} carrying the parsed\n * error objects (tolerating a non-JSON error body with an empty list).\n */\nasync function send(\n ctx: JsonApiContext,\n req: JsonApiRequest,\n responseType?: 'blob' | 'arraybuffer',\n seeOther = false,\n): Promise<TransportResponse> {\n let url: string\n let sendHeaders = true\n if (req.link) {\n const link = resolveLink(req.path, ctx.baseUrl)\n if (!link.sameOrigin && ctx.allowCrossOriginLinks !== true) {\n throw new Error(\n `Refusing to follow link \"${req.path}\": it leaves the base URL's origin (set allowCrossOriginLinks to follow it without the configured headers)`,\n )\n }\n url = link.url\n sendHeaders = link.sameOrigin\n } else {\n url = isAbsolute(req.path) ? req.path : ctx.baseUrl + req.path\n }\n if (req.query) {\n const qs = serializeQuery(req.query, req.listFilter, req.relatedListFilter)\n if (qs) {\n url += (url.includes('?') ? '&' : '?') + qs\n }\n }\n\n // Compose the negotiated media type (`application/vnd.api+json` + any opted-in ext/profile\n // parameters) once; a bare request yields the plain JSON:API media type. An explicit\n // `accept`/`contentType` override wins over the negotiated value for its header.\n const negotiated = mediaType({ ext: req.ext, profiles: req.profiles })\n const headers: Record<string, string> = { Accept: req.accept ?? negotiated }\n\n const transportReq: TransportRequest = { method: req.method, url, headers }\n if (req.signal !== undefined) {\n transportReq.signal = req.signal\n }\n if (responseType !== undefined) {\n transportReq.responseType = responseType\n }\n // A JSON:API server answers 415 to a POST without the JSON:API Content-Type, even with no body.\n if (req.body !== undefined || req.method.toUpperCase() === 'POST') {\n const contentType = req.contentType === undefined ? negotiated : req.contentType\n if (contentType !== null) {\n headers['Content-Type'] = contentType\n }\n }\n if (typeof req.body === 'string' && req.raw) {\n transportReq.body = req.body\n } else if (req.raw && isRawBody(req.body)) {\n transportReq.rawBody = req.body\n } else if (req.body !== undefined) {\n transportReq.body = JSON.stringify(req.body)\n }\n\n if (ctx.headers && sendHeaders) {\n mergeHeaders(headers, await ctx.headers())\n }\n\n const res = await ctx.transport(transportReq)\n\n if ((res.status >= 200 && res.status < 300) || (seeOther && res.status === 303)) {\n return res\n }\n\n throw new JsonApiError(res.status, parseErrors(res.body))\n}\n\n/** Whether a raw body goes to the transport as is rather than through `JSON.stringify`. */\nfunction isRawBody(body: unknown): body is TransportRawBody {\n return (\n (typeof Blob !== 'undefined' && body instanceof Blob) ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) ||\n (typeof FormData !== 'undefined' && body instanceof FormData) ||\n (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams)\n )\n}\n\n/**\n * Merge a `HeadersInit` (object / tuple array / `Headers`) into the outgoing map,\n * preserving the caller's casing (unlike the WHATWG `Headers`, which lowercases). The\n * caller's headers override the runtime defaults, so per-request `Accept` etc. can win.\n */\nfunction mergeHeaders(into: Record<string, string>, extra: HeadersInit): void {\n if (extra instanceof Headers) {\n extra.forEach((value, key) => {\n into[key] = value\n })\n } else if (Array.isArray(extra)) {\n for (const [key, value] of extra) {\n if (key !== undefined && value !== undefined) {\n into[key] = String(value)\n }\n }\n } else {\n for (const [key, value] of Object.entries(extra)) {\n into[key] = String(value)\n }\n }\n}\n\nfunction parseDocument(body: string): Document | undefined {\n if (body === '') {\n return undefined\n }\n return JSON.parse(body) as Document\n}\n\nfunction parseErrors(body: string): JsonApiErrorObject[] {\n if (body === '') {\n return []\n }\n try {\n const doc = JSON.parse(body) as { errors?: JsonApiErrorObject[] }\n return Array.isArray(doc.errors) ? doc.errors : []\n } catch {\n return []\n }\n}\n","import {\n type Document,\n executeResponse,\n type ExecutedResponse,\n type JsonApiContext,\n} from './request'\n\n/** Options for waiting on an accepted write: `wait` on the call, or {@link Accepted.$poll}. */\nexport interface PollOptions {\n /**\n * How long to keep polling, in milliseconds, before rejecting with a {@link PollTimeoutError}.\n * Defaults to five minutes.\n */\n timeout?: number\n /** Stops polling when signalled. The call rejects with the signal's reason, as a request does. */\n signal?: AbortSignal\n}\n\n/**\n * A write the server accepted for later (`202 Accepted`). `Job` is the job it answered with,\n * `Result` what the write resolves to once the job is done, and `Meta` the job document's\n * top-level `meta`.\n */\nexport interface Accepted<Job, Result = unknown, Meta = Record<string, unknown> | undefined> {\n /**\n * The job, materialised as its type's resource, or the document's top-level `meta` when the\n * server answered with a meta-only document.\n */\n readonly job: Job\n /** The `202` document's top-level `meta`, typed with the members the operation declares. */\n readonly meta: Meta\n /** The job URL, from `Content-Location`, which {@link $poll} reads until the job is done. */\n readonly contentLocation: string\n /**\n * How long the server asks the client to wait before polling, in seconds, from `Retry-After`. An\n * HTTP date is counted from when the response arrived. Absent when the server sent none.\n */\n readonly retryAfter: number | undefined\n /** Poll the job URL until the job is done, and resolve to what the write returns. */\n $poll(options?: PollOptions): Promise<Result>\n}\n\n/** Thrown when a job is still pending when the poll's timeout runs out. */\nexport class PollTimeoutError extends Error {\n readonly contentLocation: string\n readonly timeout: number\n\n constructor(contentLocation: string, timeout: number) {\n super(`The job at ${contentLocation} was still pending after ${timeout}ms`)\n this.name = 'PollTimeoutError'\n this.contentLocation = contentLocation\n this.timeout = timeout\n }\n}\n\nconst ACCEPTED = Symbol.for('@haddowg/json-api-client/accepted')\n\n/** Whether a write's result is an {@link Accepted} job rather than its normal result. */\nexport function isAccepted(value: unknown): value is Accepted<unknown, unknown> {\n return typeof value === 'object' && value !== null && ACCEPTED in value\n}\n\nconst DEFAULT_TIMEOUT = 5 * 60 * 1000\nconst DEFAULT_INTERVAL = 1000\n\n/** How the client reads and finishes one accepted write. */\nexport interface AcceptedTarget {\n readonly request: JsonApiContext\n readonly jobType: string\n /** Shape the job's materialised document (or `meta`) for {@link Accepted.job}. */\n readonly job: (doc: Document | undefined) => unknown\n /** Shape the finished response into what the write returns. */\n readonly complete: (doc: Document | undefined) => unknown\n}\n\n/** A response header by name, whatever case the transport wrote it in. */\nfunction header(headers: Record<string, string>, name: string): string | undefined {\n const wanted = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === wanted) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * A `Retry-After` value in seconds: delta-seconds as sent, an HTTP date as the seconds left until\n * it, rounded up and never negative. `undefined` when absent or unreadable.\n */\nexport function parseRetryAfter(value: string | undefined, now = Date.now()): number | undefined {\n const trimmed = value?.trim()\n if (trimmed === undefined || trimmed === '') {\n return undefined\n }\n if (/^\\d+$/.test(trimmed)) {\n return Number(trimmed)\n }\n const at = Date.parse(trimmed)\n return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - now) / 1000))\n}\n\n/** Whether a document is a meta-only one: no primary `data` member. */\nconst isMetaOnly = (doc: Document | undefined): boolean => doc === undefined || !('data' in doc)\n\n/** The `type` of a document's single primary resource, if it has one. */\nfunction primaryType(doc: Document | undefined): unknown {\n const data = doc?.data\n return typeof data === 'object' && data !== null && !Array.isArray(data)\n ? (data as Record<string, unknown>)['type']\n : undefined\n}\n\n/** Build the {@link Accepted} for a `202` response. */\nexport function toAccepted(\n target: AcceptedTarget,\n res: ExecutedResponse,\n): Accepted<unknown, unknown, unknown> {\n const contentLocation = header(res.headers, 'Content-Location')\n if (contentLocation === undefined) {\n throw new Error('The server answered 202 Accepted without a Content-Location to poll.')\n }\n const metaJob = isMetaOnly(res.document)\n const retryAfter = parseRetryAfter(header(res.headers, 'Retry-After'))\n const value = {\n job: target.job(res.document),\n contentLocation,\n retryAfter,\n }\n Object.defineProperty(value, ACCEPTED, { value: true, enumerable: false })\n Object.defineProperty(value, 'meta', { value: res.document?.meta, enumerable: false })\n Object.defineProperty(value, '$poll', {\n value: (options?: PollOptions) => poll(target, contentLocation, metaJob, retryAfter, options),\n enumerable: false,\n })\n return value as Accepted<unknown, unknown, unknown>\n}\n\n/**\n * Poll the job URL. A `2xx` still holding the job (its type, or a meta-only document for a\n * meta-only job) is pending: wait for its `Retry-After`, else the `202`'s, else a second. A `303`\n * the transport didn't follow is done, and its `Location` is fetched; any other `2xx` is the\n * redirect already followed. A non-2xx throws the usual {@link JsonApiError}.\n */\nasync function poll(\n target: AcceptedTarget,\n contentLocation: string,\n metaJob: boolean,\n acceptedRetryAfter: number | undefined,\n options: PollOptions = {},\n): Promise<unknown> {\n const timeout = options.timeout ?? DEFAULT_TIMEOUT\n const signal = options.signal\n const deadline = Date.now() + timeout\n const get = (path: string, seeOther: boolean) =>\n executeResponse(\n target.request,\n { method: 'GET', path, link: true, ...(signal !== undefined ? { signal } : {}) },\n seeOther,\n )\n const holdsJob = (doc: Document | undefined): boolean =>\n doc !== undefined && (primaryType(doc) === target.jobType || (metaJob && isMetaOnly(doc)))\n\n let delay = (acceptedRetryAfter ?? DEFAULT_INTERVAL / 1000) * 1000\n for (;;) {\n const remaining = deadline - Date.now()\n if (remaining <= 0) {\n throw new PollTimeoutError(contentLocation, timeout)\n }\n // A Retry-After past the deadline still gets one last poll at the deadline.\n await sleep(Math.min(delay, remaining), signal)\n const res = await get(contentLocation, true)\n if (res.status === 303) {\n const location = header(res.headers, 'Location')\n if (location === undefined) {\n throw new Error(`The job at ${contentLocation} answered 303 without a Location.`)\n }\n return target.complete((await get(location, false)).document)\n }\n if (!holdsJob(res.document)) {\n return target.complete(res.document)\n }\n const retryAfter = parseRetryAfter(header(res.headers, 'Retry-After')) ?? acceptedRetryAfter\n delay = (retryAfter ?? DEFAULT_INTERVAL / 1000) * 1000\n }\n}\n\n/** Resolve after `ms`, or reject with the signal's reason when it aborts first. */\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason)\n return\n }\n const onAbort = () => {\n clearTimeout(timer)\n reject(signal!.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n","/**\n * Pagination: resolving which strategy answers a read (runtime) and typing a read's `page`\n * parameter and `$page` from the descriptor (compile time). Both follow the paginator the\n * server advertises: a bare kind (canonical wire keys), a strategy with renamed keys, or a\n * MultiPaginator menu the client picks from by `kind`.\n */\nimport type {\n MenuDescriptor,\n PaginatorDescriptor,\n PaginatorKind,\n PaginatorRole,\n PaginatorStrategy,\n StrategyDescriptor,\n} from './descriptor'\n\n/** The wire key for each role when the server keeps the default names. */\nexport const CANONICAL_PAGE_KEYS = {\n page: { number: 'number', size: 'size' },\n offset: { offset: 'offset', limit: 'limit' },\n cursor: { after: 'after', before: 'before', size: 'size' },\n fixed: { number: 'number' },\n none: {},\n} as const satisfies Record<PaginatorKind, Partial<Record<PaginatorRole, string>>>\n\n/** Role -> wire key for the strategy that answered. */\nexport type PageKeys = Readonly<Partial<Record<PaginatorRole, string>>>\n\n/** The strategy that answers one read, with its wire keys and, for a menu pick, the arm's `kind`. */\nexport interface ResolvedPaginator {\n kind: PaginatorKind\n keys: PageKeys\n /** The menu arm the request picked with `page[kind]`. Absent when it picked none (the default). */\n arm?: string\n}\n\n/**\n * Resolve the strategy that answers a read from the endpoint's paginator and the `page` the\n * request sends. A menu answers with the arm named by `page.kind`, else its `default`.\n */\nexport function resolvePaginator(\n paginator: PaginatorDescriptor | undefined,\n page?: Readonly<Record<string, unknown>>,\n): ResolvedPaginator {\n if (paginator === undefined) {\n return { kind: 'none', keys: {} }\n }\n if (typeof paginator === 'string') {\n return { kind: paginator, keys: CANONICAL_PAGE_KEYS[paginator] }\n }\n if (paginator.strategy !== 'multi') {\n return { kind: paginator.strategy, keys: paginator.keys }\n }\n const picked = page?.['kind']\n const arm =\n typeof picked === 'string' && Object.hasOwn(paginator.arms, picked) ? picked : undefined\n const resolved = resolvePaginator(paginator.arms[arm ?? paginator.default])\n return arm === undefined ? resolved : { ...resolved, arm }\n}\n\n/** Navigation links by relation (`first`/`prev`/`next`/`last`), when present. */\nexport interface PageLinks {\n first?: string\n prev?: string\n next?: string\n last?: string\n}\n\n/** Normalised pagination state on a collection, as the runtime builds it; count-free-safe. */\nexport interface Page {\n kind: PaginatorKind\n /** Role -> wire key for the strategy that answered. */\n keys: PageKeys\n /** The menu arm the request picked with `page[kind]`, when it picked one. */\n arm?: string\n /** The raw `meta.page` block, when present (shape varies by kind). */\n meta?: Record<string, unknown>\n links: PageLinks\n}\n\n/**\n * The `meta.page` block each built-in strategy renders. `total`/`lastPage` (and `to` on an empty\n * page) are absent when the server does not count.\n */\nexport type PageMeta<K extends PaginatorKind> = K extends 'page'\n ? {\n currentPage: number\n perPage: number\n from: number\n to?: number\n total?: number\n lastPage?: number\n }\n : K extends 'fixed'\n ? { currentPage: number; total?: number; lastPage?: number }\n : K extends 'offset'\n ? { offset: number; limit: number; from: number; to?: number; total?: number }\n : K extends 'cursor'\n ? { perPage: number; from?: string; to?: string; hasMore: boolean }\n : Record<string, unknown>\n\n/** `$page` typed by the strategy `K` that answers, its wire keys and the picked menu arm. */\nexport type TypedPage<\n K extends PaginatorKind,\n Keys extends PageKeys,\n Arm extends string | undefined = undefined,\n> = {\n kind: K\n keys: Keys\n meta?: PageMeta<K>\n links: PageLinks\n} & (Arm extends string ? { arm: Arm } : { arm?: never })\n\n/** A non-menu paginator entry as `{ strategy, keys }` (a bare kind takes the canonical keys). */\ntype StrategyOf<P> = P extends PaginatorKind\n ? { strategy: P; keys: (typeof CANONICAL_PAGE_KEYS)[P] }\n : P extends StrategyDescriptor\n ? P\n : never\n\n/** Cursors are opaque strings; every other role is a count. */\ntype RoleValue<R> = R extends 'after' | 'before' ? string : number\n\n/** The page members one strategy accepts, keyed by their wire names. */\ntype StrategyParams<S> = S extends { keys: infer K }\n ? { -readonly [R in keyof K as K[R] extends string ? K[R] : never]?: RoleValue<R> }\n : never\n\n/** True when `P` is the loose `PaginatorDescriptor` union rather than a generated literal. */\ntype IsLoose<P> = [PaginatorKind] extends [P] ? true : false\n\ntype ArmName<M extends MenuDescriptor> = Extract<keyof M['arms'], string>\n\ntype ArmParams<M extends MenuDescriptor, A> =\n A extends ArmName<M> ? { kind: A } & StrategyParams<StrategyOf<M['arms'][A]>> : never\n\ntype KeysOfUnion<U> = U extends unknown ? keyof U : never\n\n/**\n * The default arm's members without `kind`. Members only another arm reads are `never`: the\n * server would select that arm by them, while the response is typed as the default.\n */\ntype DefaultArmParams<M extends MenuDescriptor> = StrategyParams<\n StrategyOf<M['arms'][M['default']]>\n> & { kind?: undefined } & {\n [X in Exclude<\n KeysOfUnion<StrategyParams<StrategyOf<M['arms'][ArmName<M>]>>>,\n keyof StrategyParams<StrategyOf<M['arms'][M['default']]>>\n >]?: never\n}\n\n/**\n * The `page` parameter an endpoint with paginator `P` accepts: its strategy's members under\n * their wire keys (numbers, cursors as strings). A menu takes one arm tagged by `kind`, or the\n * default arm's members untagged. `never` for an unpaginated endpoint; a loose record when the\n * descriptor is not a generated literal.\n */\nexport type PageParams<P> =\n IsLoose<P> extends true\n ? Readonly<Record<string, unknown>>\n : P extends 'none'\n ? never\n : P extends MenuDescriptor\n ? ArmParams<P, ArmName<P>> | DefaultArmParams<P>\n : StrategyParams<StrategyOf<P>>\n\n/** The member of page parameter union `P` that argument `Q` selects by its `kind`, if any. */\ntype SelectedArm<Q, P> = Q extends { kind: infer K }\n ? Extract<P, { kind: K }>\n : Extract<P, { kind?: undefined }>\n\n/**\n * A page argument `Q` with any member outside the arm it selects turned into `never`, so a typo,\n * or another arm's member, is an error.\n */\nexport type ExactPageParams<Q, P> = Q & {\n [K in Exclude<\n keyof Q,\n KeysOfUnion<[SelectedArm<Q, P>] extends [never] ? P : SelectedArm<Q, P>>\n >]: never\n}\n\ntype StrategyPage<S, Arm extends string | undefined = undefined> = S extends {\n strategy: infer K extends PaginatorStrategy\n keys: infer Keys extends PageKeys\n}\n ? TypedPage<K, Keys, Arm>\n : Page\n\ntype MenuPage<M extends MenuDescriptor, Q> = [Q] extends [never]\n ? StrategyPage<StrategyOf<M['arms'][M['default']]>>\n : Q extends { kind: infer A extends ArmName<M> }\n ? StrategyPage<StrategyOf<M['arms'][A]>, A>\n : StrategyPage<StrategyOf<M['arms'][M['default']]>>\n\n/**\n * The `$page` a read on an endpoint with paginator `P` carries, given the `page` argument `Q`\n * it sent: the picked menu arm's strategy, the default's when it picked none, else the\n * endpoint's own strategy.\n */\nexport type PageOf<P, Q = undefined> =\n IsLoose<P> extends true\n ? Page\n : P extends MenuDescriptor\n ? MenuPage<P, Q>\n : P extends 'none'\n ? TypedPage<'none', Record<never, never>>\n : StrategyPage<StrategyOf<P>>\n\n/**\n * The `page` argument that reads another page from the strategy that answered `P` (a `$page`):\n * its members under their wire keys, tagged with the menu arm it picked. A loose record for an\n * untyped `Page`.\n */\nexport type PageParamsOf<P extends Page> = PaginatorKind extends P['kind']\n ? Readonly<Record<string, string | number>>\n : StrategyParams<{ keys: P['keys'] }> &\n (P extends { arm: infer A extends string } ? { kind: A } : unknown)\n\n/**\n * The `page` params for the page after `list`, read from its `next` link, or `undefined` on the\n * last page (or before anything has loaded). Works the same for every strategy, because the\n * server's link already carries the right parameters: counts come back as numbers, cursors as\n * strings, under the wire keys the strategy uses, with the menu arm's `kind` when the link names\n * one. Feed the result back as the `page` of the next read:\n *\n * ```ts\n * const next = nextPageParams(albums)\n * if (next) albums = await client.albums.list({ page: next })\n * ```\n */\nexport function nextPageParams<P extends Page>(\n list: { readonly $page: P } | undefined,\n): PageParamsOf<P> | undefined {\n return pageParams(list?.$page, list?.$page.links.next)\n}\n\n/** The `page` params for the page before `list`, from its `prev` link. See {@link nextPageParams}. */\nexport function prevPageParams<P extends Page>(\n list: { readonly $page: P } | undefined,\n): PageParamsOf<P> | undefined {\n return pageParams(list?.$page, list?.$page.links.prev)\n}\n\nconst CURSOR_ROLES: readonly string[] = ['after', 'before']\n\nfunction pageParams<P extends Page>(\n page: P | undefined,\n link: string | undefined,\n): PageParamsOf<P> | undefined {\n if (page === undefined || link === undefined) {\n return undefined\n }\n const keys = Object.entries(page.keys) as [PaginatorRole, string][]\n const query = link.includes('?') ? link.slice(link.indexOf('?') + 1).split('#')[0] : ''\n const params: Record<string, string | number> = {}\n // `forEach` rather than `for…of`: iterating `URLSearchParams` needs the DOM iterable lib, which\n // the client's ES2022 consumers (generated clients type-checked without DOM) don't have.\n new URLSearchParams(query).forEach((value, name) => {\n const member = /^page\\[([^\\]]+)\\]$/.exec(name)?.[1]\n if (member === undefined) {\n return\n }\n const role = keys.find(([, key]) => key === member)?.[0]\n const count = Number(value)\n params[member] =\n role !== undefined && !CURSOR_ROLES.includes(role) && value !== '' && Number.isFinite(count)\n ? count\n : value\n })\n return params as PageParamsOf<P>\n}\n","import type {\n ApiDescriptor,\n PaginatorDescriptor,\n PaginatorKind,\n RelationDescriptor,\n} from './descriptor'\nimport { type Page, type ResolvedPaginator, resolvePaginator } from './pagination'\nimport { type NestedFieldset, nestedFieldset } from './nested-fieldset'\nimport type { Document } from './request'\nimport { stampFromDocument } from './request-stamp'\nimport type { ResourceIdentifier } from './types'\nimport { assertJsonApiDocument, type ResolvedValidator, validateDocument } from './validate'\n\n/** A trimmed, by-reference top-level envelope shared by every resource from one response. */\nexport interface DocumentEnvelope {\n jsonapi?: Record<string, unknown>\n meta?: Record<string, unknown>\n links?: Record<string, unknown>\n}\n\n/** A JSON:API link object. */\nexport interface LinkObject {\n href: string\n rel?: string\n describedby?: string | LinkObject\n title?: string\n type?: string\n hreflang?: string | string[]\n meta?: Record<string, unknown>\n}\n\n/**\n * A link as the wire carries it. A server renders the links it builds as link objects unless it\n * opts out to bare strings, and an author-supplied link keeps whichever shape it was given.\n */\nexport type Link = string | LinkObject\n\n/** Resource-level links (`self` is the common one; the wire may carry more). */\nexport interface ResourceLinks {\n self?: Link\n [key: string]: unknown\n}\n\n/**\n * The relationship-instance envelope for a materialised related value (its `$edge`). `Meta`\n * types `meta` when the relation declares its identifier meta members.\n */\nexport interface Edge<Meta extends Record<string, unknown> = Record<string, unknown>> {\n links?: Record<string, unknown>\n meta?: Meta\n}\n\n/**\n * A member a cache layer (an optimistic draft in `@haddowg/json-api-query`) predicted for a\n * relation but couldn't show yet, because no copy of it fits the slot: its identifier, and the\n * member the write supplied when it supplied more than an identifier (a row the user picked, or a\n * new resource's create input), so a placeholder can show what is known of it.\n */\nexport interface PendingMember<TType extends string = string> extends ResourceIdentifier<TType> {\n /** The member the write supplied, when it carried more than its identifier. */\n readonly member?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Where an optimistic create was placed in a list: first (`'start'`), last (`'end'`), or before\n * the member at an index of the list (of the page, in an infinite query's pages).\n */\nexport type PendingPlacement = 'start' | 'end' | number\n\n/**\n * A create a cache layer placed in a list but couldn't show as a member, because the row it can\n * build from the create's input doesn't hold everything the list's members promise (an attribute\n * only the server sets, or an included resource that isn't cached). `input` is what the write sent\n * (`I` types it where the create input's type is known), `id` the id the row carries (the one sent,\n * or a temporary id swapped for the server's once the write succeeds), and `at` where in the list\n * it belongs.\n */\nexport interface PendingCreate<\n I = Readonly<Record<string, unknown>>,\n TType extends string = string,\n> {\n readonly type: TType\n readonly id: string\n readonly at: PendingPlacement\n readonly input: I\n}\n\n/** The uniform shape `$rel(name)` returns. */\nexport interface RelationView {\n data?: unknown\n links?: Record<string, unknown>\n meta?: Record<string, unknown>\n}\n\n/** Non-enumerable envelope accessors shared by every materialised resource. */\nexport interface ResourceEnvelope {\n readonly $meta: Record<string, unknown> | undefined\n readonly $links: ResourceLinks | undefined\n /** The `self` link's href, whether the wire carried a bare URL or a link object. */\n readonly $self: string | undefined\n readonly $document: DocumentEnvelope\n readonly $raw: RawResource\n /**\n * The keys the request's sparse fieldset selected of each attribute it narrowed, under the Nested\n * Fieldsets profile. An attribute named here holds only those of its keys the resource has.\n */\n readonly $nestedFieldset: NestedFieldset\n $rel(name: string): RelationView | undefined\n /**\n * A relationship's count, from its `meta.total` (a `withCount` read): a finite number, else\n * `undefined`. Read from the raw relationship, so it works when the relation carries no data.\n */\n $count(name: string): number | undefined\n /**\n * `'pending'` while a cache layer holds an unconfirmed optimistic change to this resource (an\n * attribute it predicted, or a change to one of its relations), else `undefined`.\n */\n readonly $optimistic: 'pending' | undefined\n /**\n * The members a cache layer predicted for relation `name` but couldn't show yet, because no copy\n * of them fits the slot, each carrying the member the write supplied when it supplied one. Empty\n * when there are none.\n */\n $pending(name: string): readonly PendingMember[]\n}\n\n/** Edge-local accessors carried by a materialised related VALUE (per-edge view). */\nexport interface EdgeEnvelope {\n readonly $edge: Edge | undefined\n readonly $pivot: Record<string, unknown> | undefined\n /** `'pending'` while a cache layer holds an unconfirmed optimistic change to this member. */\n readonly $optimistic: 'pending' | undefined\n}\n\n/** Relationship-level accessors carried by an augmented to-many array. */\nexport interface ArrayEnvelope {\n readonly $page: Page\n readonly $links: Record<string, unknown> | undefined\n readonly $meta: Record<string, unknown> | undefined\n $next(options?: NavigateOptions): Promise<unknown>\n $prev(options?: NavigateOptions): Promise<unknown>\n}\n\n/** The accessor a to-many relationship array carries beside its {@link ArrayEnvelope}. */\nexport interface RelationArrayEnvelope {\n /** The relationship's count, from its `meta.total`: a finite number, else `undefined`. */\n readonly $count: number | undefined\n}\n\n/** Per-call options for `$next()`/`$prev()`. */\nexport interface NavigateOptions {\n /** Cancels the page fetch when signalled. */\n signal?: AbortSignal\n}\n\n/** The runtime context materialise reads its descriptor + navigation seam from. */\nexport interface MaterialiseContext {\n descriptor: ApiDescriptor\n /**\n * Re-fetch + re-materialise a link (wired in Build 4); returns the materialised value.\n * `linkage` propagates the originating surface so a paginated relationship-endpoint\n * array re-materialises as identifiers (not resources) on `$next()`/`$prev()`. `paginator`\n * carries the strategy that answered the current page, so the re-materialised page reports the\n * same `$page` (a divergent per-relation paginator, a picked menu arm, or an EMPTY next page\n * that carries no member to sniff).\n */\n navigate: (\n url: string,\n linkage?: boolean,\n paginator?: ResolvedPaginator,\n signal?: AbortSignal,\n ) => Promise<unknown>\n /**\n * The opt-in per-resource validator, resolved from `ClientOptions.validate`. When\n * present, every wire resource in `data`/`included` is validated against its per-type schema\n * before the document is materialised. Absent => no per-field validation (the default).\n */\n validate?: ResolvedValidator | undefined\n /**\n * The sparse fieldsets the request sent, by type, which tell an attribute narrowed to some of\n * its keys from one rendered whole (see {@link ResourceEnvelope.$nestedFieldset}).\n */\n fields?: Readonly<Record<string, readonly string[]>> | undefined\n}\n\n/** A raw JSON:API resource object (or bare identifier) off the wire. */\ninterface RawResource {\n type: string\n id: string\n meta?: Record<string, unknown>\n links?: ResourceLinks\n attributes?: Record<string, unknown>\n relationships?: Record<string, RawRelationship>\n}\n\ninterface RawRelationship {\n data?: unknown\n links?: Record<string, unknown>\n meta?: Record<string, unknown>\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nconst define = (target: object, key: string, value: unknown): void => {\n Object.defineProperty(target, key, { value, enumerable: false, configurable: true })\n}\n\nconst defineGetter = (target: object, key: string, get: (this: object) => unknown): void => {\n Object.defineProperty(target, key, { get, enumerable: false, configurable: true })\n}\n\n// ── The cache-layer overlay ─────────────────────────────────────────────────────────────────\n\n/**\n * What a cache layer (such as `@haddowg/json-api-query`'s optimistic drafts) reports about the\n * materialised values it holds, consulted by `$optimistic`, `$pending()` and `$count`. Each call\n * gets the value the accessor was read on followed by the values it reads through to (a per-edge\n * view, then the node it views), so a layer that recorded any of them answers for all.\n *\n * @internal\n */\nexport interface MaterialisedOverlay {\n /** `'pending'` when the layer holds an unconfirmed change to any of `targets`. */\n optimistic(targets: readonly object[]): 'pending' | undefined\n /** The members of relation `name` the layer predicted for `targets` but couldn't show. */\n pending(targets: readonly object[], name: string): readonly PendingMember[]\n /**\n * The creates the layer placed in the collection `targets` (an augmented array, then what it\n * reads through to) but couldn't show as members. Absent: none.\n */\n creates?(targets: readonly object[]): readonly PendingCreate[]\n /**\n * The total the collection `targets` reports, given the `raw` total its response carried\n * (`$page.meta.total`, and a top-level collection's `$meta.total`). Absent: the raw total.\n */\n total?(targets: readonly object[], raw: number): number\n /**\n * The count `targets` report for relation `name`, given the `raw` count the response carried.\n * `name` is `undefined` when the target is the to-many array itself (its own `$count`).\n */\n count(\n targets: readonly object[],\n name: string | undefined,\n raw: number | undefined,\n ): number | undefined\n}\n\nlet overlay: MaterialisedOverlay | undefined\n\n/**\n * Install the cache layer's {@link MaterialisedOverlay}, or remove it with `undefined`. One layer is\n * installed at a time; without one, `$optimistic` is `undefined`, `$pending()` is empty and `$count`\n * is the response's count.\n *\n * @internal\n */\nexport function setMaterialisedOverlay(next: MaterialisedOverlay | undefined): void {\n overlay = next\n}\n\nconst NO_IDENTIFIERS: readonly PendingMember[] = Object.freeze([])\n\nconst NO_CREATES: readonly PendingCreate[] = Object.freeze([])\n\n/** The value each per-edge view reads through to. */\nconst SOURCES = new WeakMap<object, object>()\n\n/** The raw (response) count of each node's relations, by node. */\nconst RAW_COUNTS = new WeakMap<object, (name: string) => number | undefined>()\n\n/** `target` followed by the values it reads through to, nearest first. */\nfunction chainOf(target: object): object[] {\n const chain: object[] = []\n let at: object | undefined = target\n while (at !== undefined && !chain.includes(at)) {\n chain.push(at)\n at = SOURCES.get(at)\n }\n return chain\n}\n\n/** The raw count of relation `name` the first value in `chain` with one carries. */\nfunction rawCount(chain: readonly object[], name: string): number | undefined {\n for (const value of chain) {\n const count = RAW_COUNTS.get(value)\n if (count !== undefined) {\n return count(name)\n }\n }\n return undefined\n}\n\n/** {@link rawCount} for the chain starting at `target`, without building the chain. */\nfunction rawCountOf(target: object, name: string): number | undefined {\n let at: object | undefined = target\n while (at !== undefined) {\n const count = RAW_COUNTS.get(at)\n if (count !== undefined) {\n return count(name)\n }\n at = SOURCES.get(at)\n }\n return undefined\n}\n\n/** Define the overlay-backed accessors (`$optimistic`, `$pending`, `$count`) of a resource value. */\nfunction attachOverlayAccessors(target: object): void {\n defineGetter(target, '$optimistic', () => overlay?.optimistic(chainOf(target)))\n define(\n target,\n '$pending',\n (name: string): readonly PendingMember[] =>\n overlay?.pending(chainOf(target), name) ?? NO_IDENTIFIERS,\n )\n define(target, '$count', (name: string): number | undefined => {\n if (overlay === undefined) {\n return rawCountOf(target, name)\n }\n const chain = chainOf(target)\n return overlay.count(chain, name, rawCount(chain, name))\n })\n}\n\n/** A relationship object's `meta.total` when it is a finite number, else `undefined`. */\nconst relationTotal = (rel: RawRelationship | undefined): number | undefined => {\n const total = rel?.meta?.['total']\n return typeof total === 'number' && Number.isFinite(total) ? total : undefined\n}\n\n/**\n * Materialise a JSON:API document into a hydrated graph (ADR 0002):\n *\n * - single resource -> a flattened resource object (own enumerable type/id/attributes/\n * relations + non-enumerable `$`-accessors);\n * - collection / related collection -> an augmented array of resource objects;\n * - relationship linkage -> an augmented array of identifier views (to-many) or a single\n * identifier / null (to-one).\n *\n * Included resources hydrate into nested per-edge views (reads through to the shared\n * node for attributes, owns its own `$edge`/`$pivot`); linked-but-not-included relations\n * stay as identifiers; links-only relations are `undefined`. The envelope rides\n * non-enumerable `$`-accessors so `{...res}` / `JSON.stringify(res)` are clean.\n *\n * `linkage` discriminates a relationship-endpoint response (primary `data` is pure\n * resource-identifier linkage) from a resource/collection response (primary `data` is a\n * full resource) — a structural guess can't tell them apart for an attribute-less,\n * relation-less resource, so the caller passes the surface it issued.\n *\n * `paginatorOverride` sets the top-level array's `$page` for a related/relationship read, where the\n * paginator is the RELATION's (which may diverge from the related type's collection — D6a), for a\n * menu read that picked an arm, and where an empty page carries no member to sniff a type from. A\n * bare kind is read with its canonical wire keys. `primaryType` is preferred for a\n * top-level collection read (statically-known); both override the sniff-from-`data[0]` fallback.\n */\nexport function materialise(\n doc: Document,\n ctx: MaterialiseContext,\n linkage = false,\n primaryType?: string,\n paginatorOverride?: ResolvedPaginator | PaginatorKind,\n): unknown {\n const value = materialiseDocument(doc, ctx, linkage, primaryType, paginatorOverride)\n if (typeof value === 'object' && value !== null) {\n MATERIALISED.add(value)\n }\n return stampFromDocument(doc, value)\n}\n\nconst MATERIALISED = new WeakSet<object>()\n\n/**\n * Whether `value` is a top-level result `materialise` built: a resource, a collection or a linkage\n * value, including the pages `$next()` and `$prev()` re-materialise. A plain copy of one, such as\n * data that went through `JSON.stringify` on a server and back, has lost its `$`-accessors and\n * answers `false`, which is how a hydrated cache entry is told from a fresh read.\n */\nexport function isMaterialised(value: unknown): value is object {\n return typeof value === 'object' && value !== null && MATERIALISED.has(value)\n}\n\nfunction materialiseDocument(\n doc: Document,\n ctx: MaterialiseContext,\n linkage: boolean,\n primaryType: string | undefined,\n paginatorOverride: ResolvedPaginator | PaginatorKind | undefined,\n): unknown {\n // Always-on light structural guards: prove the envelope invariant the runtime relies on (a\n // JSON:API document; each data/included member carries type+id). Then, only when configured,\n // run the opt-in per-field validation over each wire resource by its type.\n assertJsonApiDocument(doc)\n if (ctx.validate !== undefined) {\n validateDocument(doc, ctx.validate, ctx.fields)\n }\n\n const env: DocumentEnvelope = {}\n if (doc.jsonapi !== undefined) env.jsonapi = doc.jsonapi\n if (doc.meta !== undefined) env.meta = doc.meta\n if (doc.links !== undefined) env.links = doc.links\n\n const index = buildIndex(doc.included, linkage ? undefined : doc.data)\n // One node per type:id, shared by reference for attribute reads.\n const nodes = new Map<string, object>()\n const build = (raw: RawResource): object => buildNode(raw, env, index, nodes, ctx)\n\n const data = doc.data\n\n if (data === null) {\n return null\n }\n\n if (Array.isArray(data)) {\n const raws = data as RawResource[]\n const members = linkage\n ? raws.map((raw) => buildIdentifierView(raw))\n : raws.map((raw) => buildEdgeView(build(raw), raw))\n return augmentArray(members, doc, ctx, linkage, primaryType, paginatorOverride)\n }\n\n if (isObject(data)) {\n const raw = data as unknown as RawResource\n if (linkage) {\n return buildIdentifierView(raw)\n }\n return build(raw)\n }\n\n // No primary data (e.g. a meta-only document); expose nothing materialisable.\n return undefined\n}\n\n/**\n * Index `included` and the primary resources by `type:id` so relationship linkage can be hydrated.\n * A server never repeats a primary resource in `included`, so a member that links back to one\n * (`tracks.album` on an album) is found only among the primary data.\n */\nfunction buildIndex(included: unknown[] | undefined, primary: unknown): Map<string, RawResource> {\n const index = new Map<string, RawResource>()\n const add = (raw: unknown): void => {\n if (isObject(raw) && typeof raw['type'] === 'string' && typeof raw['id'] === 'string') {\n index.set(key(raw['type'], raw['id']), raw as unknown as RawResource)\n }\n }\n for (const raw of included ?? []) add(raw)\n for (const raw of Array.isArray(primary) ? primary : [primary]) add(raw)\n return index\n}\n\nconst key = (type: string, id: string): string => `${type}:${id}`\n\n/**\n * Build (or reuse) the shared NODE for a resource: flattened type/id/attributes + hydrated\n * relations as own enumerable props, plus the resource-level `$`-accessors. The node is\n * memoised by `type:id` so attribute reads share one object; per-edge data never lands here.\n */\nfunction buildNode(\n raw: RawResource,\n env: DocumentEnvelope,\n index: Map<string, RawResource>,\n nodes: Map<string, object>,\n ctx: MaterialiseContext,\n): object {\n const id = key(raw.type, raw.id)\n const existing = nodes.get(id)\n if (existing) return existing\n\n const node: Record<string, unknown> = { type: raw.type, id: raw.id }\n // Seed the cache before recursing so a relation cycle resolves to this same node.\n nodes.set(id, node)\n const cycleViews: Record<string, unknown>[] = []\n UNFINISHED.set(node, cycleViews)\n\n if (raw.attributes) {\n for (const [k, v] of Object.entries(raw.attributes)) {\n node[k] = v\n }\n }\n\n const rels = raw.relationships ?? {}\n const resType = ctx.descriptor[raw.type]\n for (const [name, rel] of Object.entries(rels)) {\n if (!('data' in rel)) {\n // Links-only relation: no value to carry an edge -> undefined (reachable via $rel).\n continue\n }\n const relDesc = resType?.relations[name]\n node[name] = hydrateRelation(\n rel,\n resolvePaginator(relatedPaginator(relDesc, ctx)),\n env,\n index,\n nodes,\n ctx,\n )\n }\n\n attachResourceEnvelope(node, raw, env, rels, nestedFieldset(ctx.fields?.[raw.type]))\n UNFINISHED.delete(node)\n for (const view of cycleViews) {\n readLateRelations(view, node)\n }\n return node\n}\n\n/** Nodes still being built, each with the per-edge views a relation cycle copied of it so far. */\nconst UNFINISHED = new WeakMap<object, Record<string, unknown>[]>()\n\n/** A back-reference's relations that read through to its node; a property, read on every walk. */\nconst LATE: unique symbol = Symbol('late relations')\n\n/** Nodes some back-reference reads relations through to. */\nconst READ_THROUGH = new WeakSet<object>()\n\n/**\n * A relation cycle copied `view` of `node` before the node's later relations were set. Each one it\n * missed reads the node's slot as linkage: the view sits past the end of its include path, and a\n * hydrated value would close the cycle. Non-enumerable, so a spread, `JSON.stringify` and a cache\n * walk meet no cycle.\n */\nfunction readLateRelations(view: Record<string, unknown>, node: Record<string, unknown>): void {\n const late = new Set<string>()\n for (const name of Object.keys(node)) {\n if (!Object.hasOwn(view, name)) {\n late.add(name)\n defineGetter(view, name, () => linkageOf(node[name]))\n }\n }\n if (late.size > 0) {\n Object.defineProperty(view, LATE, { value: late })\n READ_THROUGH.add(node)\n }\n}\n\n/** Each slot value's linkage, so a back-reference reads the same value until its node's changes. */\nconst LINKAGE = new WeakMap<object, unknown>()\n\n/** A relation slot's value as linkage: identifier views, in an array keeping the slot's envelope. */\nfunction linkageOf(slot: unknown): unknown {\n if (typeof slot !== 'object' || slot === null) {\n return slot\n }\n if (LINKAGE.has(slot)) {\n return LINKAGE.get(slot)\n }\n const value = Array.isArray(slot)\n ? withSlotEnvelope(slot, slot.map(identifierOf))\n : identifierOf(slot)\n LINKAGE.set(slot, value)\n return value\n}\n\nfunction identifierOf(member: unknown): unknown {\n if (!isObject(member) || typeof member['type'] !== 'string' || typeof member['id'] !== 'string') {\n return member\n }\n const meta = (member as { $edge?: Edge }).$edge?.meta\n return buildIdentifierView({\n type: member['type'],\n id: member['id'],\n ...(meta !== undefined ? { meta } : {}),\n } as RawResource)\n}\n\n/** `members` carrying `slot`'s non-index members (`$page`, `$links`, `$next()` and the rest). */\nfunction withSlotEnvelope(slot: readonly unknown[], members: unknown[]): unknown[] {\n for (const name of Reflect.ownKeys(slot)) {\n if (name !== 'length' && !(typeof name === 'string' && /^\\d+$/.test(name))) {\n Object.defineProperty(members, name, Object.getOwnPropertyDescriptor(slot, name)!)\n }\n }\n return members\n}\n\n/**\n * The relations of `view` that read through to its node as linkage (a back-reference a relation\n * cycle built before the node's later relations were set), or `undefined`. A cache layer leaves\n * these slots alone: they follow the node.\n * @internal\n */\nexport function lateRelationsOf(view: object): ReadonlySet<string> | undefined {\n return (view as { [LATE]?: ReadonlySet<string> })[LATE]\n}\n\n/**\n * Tell the client a cache layer wrote relation `name` of the cached copy `copy`: a node that\n * back-references read the relation through to takes the value too, so they read it.\n * @internal\n */\nexport function relationWritten(copy: object, name: string, value: unknown): void {\n let at: object | undefined = SOURCES.get(copy)\n while (at !== undefined) {\n if (READ_THROUGH.has(at)) {\n ;(at as Record<string, unknown>)[name] = value\n }\n at = SOURCES.get(at)\n }\n}\n\n/**\n * Resolve one relationship's value from its `data`: an included member hydrates to a per-edge\n * view, a linked-but-not-included member stays an identifier, an empty to-one is `null`, and a\n * to-many's linkage is an augmented array (of views and/or identifiers).\n *\n * `related` is the relation's paginator (from the descriptor), threaded so a to-many array\n * reports the same `$page` it would on its dedicated endpoint without a `page` argument.\n */\nfunction hydrateRelation(\n rel: RawRelationship,\n related: ResolvedPaginator,\n env: DocumentEnvelope,\n index: Map<string, RawResource>,\n nodes: Map<string, object>,\n ctx: MaterialiseContext,\n): unknown {\n const data = rel.data\n\n if (Array.isArray(data)) {\n const raws = data as RawResource[]\n const members = raws.map((member) => resolveMember(member, env, index, nodes, ctx))\n const hydrated = raws.some((member) => index.has(key(member.type, member.id)))\n return augmentRelationArray(members, rel, related, ctx, hydrated)\n }\n\n if (data === null || data === undefined) {\n return data === null ? null : undefined\n }\n\n if (isObject(data)) {\n // A to-one's edge envelope carries the relationship object's self/related links/meta\n // ($edge = { links:{self,related}, meta }; docs/materialisation.md) so there's no need to go via\n // the parent's $rel for to-ones.\n return resolveMember(data as unknown as RawResource, env, index, nodes, ctx, {\n links: rel.links,\n meta: rel.meta,\n })\n }\n\n return undefined\n}\n\n/** The relationship-object envelope threaded onto a to-one member's `$edge`. */\ninterface RelationEdge {\n links: Record<string, unknown> | undefined\n meta: Record<string, unknown> | undefined\n}\n\n/** A single linkage member -> a hydrated per-edge view if included, else an identifier view. */\nfunction resolveMember(\n member: RawResource,\n env: DocumentEnvelope,\n index: Map<string, RawResource>,\n nodes: Map<string, object>,\n ctx: MaterialiseContext,\n relationEdge?: RelationEdge,\n): object {\n const included = index.get(key(member.type, member.id))\n if (included) {\n return buildEdgeView(buildNode(included, env, index, nodes, ctx), member, relationEdge)\n }\n return buildIdentifierView(member, relationEdge)\n}\n\n/**\n * Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$nestedFieldset/$rel,\n * and the overlay-backed $count/$optimistic/$pending).\n */\nfunction attachResourceEnvelope(\n node: object,\n raw: RawResource,\n env: DocumentEnvelope,\n rels: Record<string, RawRelationship>,\n selection: NestedFieldset,\n): void {\n defineGetter(node, '$meta', () => raw.meta)\n defineGetter(node, '$links', () => raw.links)\n defineGetter(node, '$self', () => linkHref(raw.links?.self))\n defineGetter(node, '$document', () => env)\n defineGetter(node, '$raw', () => raw)\n defineGetter(node, '$nestedFieldset', () => selection)\n define(node, '$rel', (name: string): RelationView | undefined => {\n const rel = rels[name]\n if (!rel) return undefined\n const view: RelationView = {}\n if ('data' in rel) view.data = rel.data\n if (rel.links !== undefined) view.links = rel.links\n if (rel.meta !== undefined) view.meta = rel.meta\n return view\n })\n RAW_COUNTS.set(node, (name: string): number | undefined =>\n Object.hasOwn(rels, name) ? relationTotal(rels[name]) : undefined,\n )\n attachOverlayAccessors(node)\n}\n\n/**\n * A per-edge VIEW over a node: a distinct wrapper per membership that reads through to the\n * shared node for attributes (and the resource-level `$`-accessors) but owns its own\n * edge-local `$edge`/`$pivot`. Identity is by `type:id`, never reference.\n *\n * `relationEdge` (set for a to-one) carries the relationship object's self/related links and\n * meta, which ride the value's `$edge` (docs/materialisation.md).\n */\nfunction buildEdgeView(\n node: object,\n member: RawResource,\n relationEdge?: RelationEdge,\n pick?: (key: string) => boolean,\n): object {\n const view: Record<string, unknown> = {}\n // Copy the node's own enumerable props (type/id/attributes/relations) into this per-edge view.\n // INVARIANT (normalize.ts, ADR 0003): every cache patch must walk and patch ALL cached views\n // of a resource, not just the canonical node — `patchAll`/`walkResources`/`patchNode` do exactly\n // that, so these copied props stay consistent across writes. A future node-only write path would\n // leave edge views stale, so it must preserve this walk-every-view invariant.\n if (pick === undefined) {\n Object.assign(view, node)\n UNFINISHED.get(node)?.push(view)\n } else {\n for (const [k, v] of Object.entries(node)) {\n if (k === 'type' || k === 'id' || pick(k)) {\n view[k] = v\n }\n }\n }\n SOURCES.set(view, node)\n // Delegate the node's non-enumerable `$`-accessors so they read through to the node.\n for (const k of ['$meta', '$links', '$self', '$document', '$raw', '$nestedFieldset'] as const) {\n delegate(view, node, k)\n }\n // Looked up at the call: a relation cycle copies a node before its `$rel` is defined.\n define(view, '$rel', (name: string): RelationView | undefined => {\n const rel = (node as { $rel?: (name: string) => RelationView | undefined }).$rel\n return typeof rel === 'function' ? rel.call(node, name) : undefined\n })\n // Its own overlay accessors, which ask about this view and then the node it reads through to.\n attachOverlayAccessors(view)\n // A full-resource member's own `links` is its self-link (already on `$links`/`$self`), so a\n // to-many member's `$edge` is meta-only; a to-one additionally carries the relationship\n // object's self/related links via `relationEdge`.\n attachEdgeEnvelope(view, member, false, relationEdge)\n return view\n}\n\n/** The linkage member a per-edge or identifier view is built for: its identity and its meta. */\nexport interface EdgeMember {\n type: string\n id: string\n meta?: Record<string, unknown>\n}\n\n/**\n * A per-edge view over `node` for the membership `member` describes, as `materialise` builds one\n * for an included member: it copies `node`'s own enumerable members (those `pick` keeps, when\n * given; `type` and `id` always), reads its resource-level `$`-accessors through to `node`, and\n * owns its `$edge`/`$pivot` from `member.meta`. `node` may be any resource value, a materialised\n * one or a plain object; accessors it lacks read as `undefined`.\n *\n * For a cache layer placing a member in a slot (`@haddowg/json-api-query`'s optimistic drafts).\n *\n * @internal\n */\nexport function edgeViewOf(\n node: object,\n member: EdgeMember,\n pick?: (key: string) => boolean,\n): object {\n return buildEdgeView(node, member as RawResource, undefined, pick)\n}\n\n/**\n * An identifier view for `member`, as `materialise` builds one for a linked member that isn't\n * included: `{ type, id, meta? }` with its `$edge`/`$pivot`.\n *\n * @internal\n */\nexport function identifierViewOf(member: EdgeMember): object {\n return buildIdentifierView(member as RawResource)\n}\n\n/** An identifier VIEW for a linked-but-not-included member: a clean `{type,id,meta?}` + edge. */\nfunction buildIdentifierView(member: RawResource, relationEdge?: RelationEdge): object {\n const view: Record<string, unknown> = { type: member.type, id: member.id }\n if (member.meta !== undefined) view.meta = member.meta\n defineGetter(view, '$optimistic', () => overlay?.optimistic([view]))\n // A bare linkage member has no resource of its own, so any `links` it carries are edge links.\n attachEdgeEnvelope(view, member, true, relationEdge)\n return view\n}\n\n/**\n * Attach `$edge` (the member's identifier-level edge meta/links) and `$pivot` sugar over it.\n * For a to-one, the relationship object's self/related links + meta (`relationEdge`) merge in,\n * with member-level meta winning on key collision.\n */\nfunction attachEdgeEnvelope(\n view: object,\n member: RawResource,\n includeLinks: boolean,\n relationEdge?: RelationEdge,\n): void {\n defineGetter(view, '$edge', () => {\n const memberLinks = includeLinks ? member.links : undefined\n const links = memberLinks ?? relationEdge?.links\n const meta = mergeMeta(relationEdge?.meta, member.meta)\n if (links === undefined && meta === undefined) return undefined\n const edge: Edge = {}\n if (links !== undefined) edge.links = links\n if (meta !== undefined) edge.meta = meta\n return edge\n })\n defineGetter(view, '$pivot', () => {\n const pivot = member.meta?.['pivot']\n return isObject(pivot) ? pivot : undefined\n })\n}\n\n/** Merge a relationship-object meta with member-level meta (member wins on key collision). */\nfunction mergeMeta(\n base: Record<string, unknown> | undefined,\n override: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (base === undefined) return override\n if (override === undefined) return base\n return { ...base, ...override }\n}\n\n/** Mirror a non-enumerable accessor from `source` onto `target`, reading through live. */\nfunction delegate(target: object, source: object, k: string): void {\n const value = (source as Record<string, unknown>)[k]\n if (typeof value === 'function') {\n define(target, k, (value as (...a: unknown[]) => unknown).bind(source))\n } else {\n defineGetter(target, k, () => (source as Record<string, unknown>)[k])\n }\n}\n\n/**\n * A top-level / related collection array: `$page` from `doc`, links/meta from the document.\n * `linkage` propagates to `$next()`/`$prev()` so a relationship-endpoint page re-materialises\n * as identifiers, not resources.\n */\nfunction augmentArray(\n members: object[],\n doc: Document,\n ctx: MaterialiseContext,\n linkage: boolean,\n primaryType?: string,\n paginatorOverride?: ResolvedPaginator | PaginatorKind,\n): object[] {\n const arr = [...members]\n const links = doc.links\n defineGetter(arr, '$links', () => links)\n // Read through `this`, as `$page` and `$pending` are, so a copy of the array carrying these\n // accessors (a cache layer's edited membership) asks the overlay about itself.\n defineGetter(arr, '$meta', function (this: object) {\n return withTotal(doc.meta, this)\n })\n const paginator =\n paginatorOverride === undefined\n ? resolvePaginator(primaryPaginator(doc, ctx, primaryType))\n : typeof paginatorOverride === 'string'\n ? resolvePaginator(paginatorOverride)\n : paginatorOverride\n attachPage(arr, paginator, pageMeta(doc.meta), links, ctx, linkage)\n return arr\n}\n\n/**\n * A to-many relationship array: `$page`/links/meta come from the relationship object.\n * `paginator` is the relation's (so an in-document compound-include to-many reports the same\n * discriminant it would when fetched at its own relationship/related endpoint — \"one model,\n * three surfaces\").\n *\n * A rendered to-many holds only its first page, and its page links usually address the\n * relationship endpoint, which answers with identifiers. So `$next()`/`$prev()` keep the shape the\n * array has: an included (`hydrated`) array reads the same page from the related endpoint, which\n * answers with the resources, and an array of identifiers reads the page as linkage.\n */\nfunction augmentRelationArray(\n members: object[],\n rel: RawRelationship,\n paginator: ResolvedPaginator,\n ctx: MaterialiseContext,\n hydrated: boolean,\n): object[] {\n const arr = [...members]\n const links = rel.links\n defineGetter(arr, '$links', () => links)\n defineGetter(arr, '$meta', () => rel.meta)\n // Read through `this`, so a copy of the array carrying this accessor (a cache layer's edited\n // membership) asks the overlay about itself.\n defineGetter(arr, '$count', function (this: object) {\n const raw = relationTotal(rel)\n return overlay === undefined ? raw : overlay.count([this], undefined, raw)\n })\n attachPage(\n arr,\n paginator,\n pageMeta(rel.meta),\n links,\n ctx,\n !hydrated,\n hydrated ? (link) => relatedPageLink(link, links) : undefined,\n )\n return arr\n}\n\n/**\n * A relationship page link moved to the related endpoint: a link addressing the relationship's\n * `self` path takes its `related` path and keeps its query, so it reads the same page as\n * resources. Any other link, such as one already addressing the related endpoint, is unchanged.\n */\nfunction relatedPageLink(link: string, links: Record<string, unknown> | undefined): string {\n const self = linkHref(links?.['self'])\n const related = linkHref(links?.['related'])\n if (self === undefined || related === undefined) {\n return link\n }\n const at = link.indexOf('?')\n const path = at < 0 ? link : link.slice(0, at)\n const selfPath = self.split('?')[0]\n return path === selfPath ? `${related.split('?')[0]}${at < 0 ? '' : link.slice(at)}` : link\n}\n\n/** Attach `$page` + `$next()`/`$prev()` driven by link presence (count-free-safe). */\nfunction attachPage(\n arr: object[],\n paginator: ResolvedPaginator,\n meta: Record<string, unknown> | undefined,\n links: Record<string, unknown> | undefined,\n ctx: MaterialiseContext,\n linkage: boolean,\n follow: (link: string) => string = (link) => link,\n): void {\n const page: Page = { kind: paginator.kind, keys: paginator.keys, links: pageLinks(links) }\n if (paginator.arm !== undefined) page.arm = paginator.arm\n if (meta !== undefined) page.meta = meta\n // Through `this`, so a copy of the array (a cache layer's edited membership) reports its own\n // total and pending creates.\n defineGetter(arr, '$page', function (this: object) {\n return pageWithTotal(page, this)\n })\n define(arr, '$pending', function (this: object): readonly PendingCreate[] {\n return overlay?.creates?.([this]) ?? NO_CREATES\n })\n const go = (link: string | undefined, signal: AbortSignal | undefined) =>\n navigateLink(link === undefined ? undefined : follow(link), ctx, linkage, paginator, signal)\n define(arr, '$next', (options?: NavigateOptions) => go(page.links.next, options?.signal))\n define(arr, '$prev', (options?: NavigateOptions) => go(page.links.prev, options?.signal))\n}\n\nconst navigateLink = (\n link: string | undefined,\n ctx: MaterialiseContext,\n linkage: boolean,\n paginator: ResolvedPaginator,\n signal: AbortSignal | undefined,\n): Promise<unknown> => {\n if (link === undefined) {\n return Promise.resolve(undefined)\n }\n return signal === undefined\n ? ctx.navigate(link, linkage, paginator)\n : ctx.navigate(link, linkage, paginator, signal)\n}\n\n/** Extract the navigation links (a link may be a string or a `{href}` object). */\nfunction pageLinks(links: Record<string, unknown> | undefined): Page['links'] {\n const out: Page['links'] = {}\n if (!links) return out\n for (const k of ['first', 'prev', 'next', 'last'] as const) {\n const href = linkHref(links[k])\n if (href !== undefined) out[k] = href\n }\n return out\n}\n\nconst linkHref = (link: unknown): string | undefined => {\n if (typeof link === 'string') return link\n if (isObject(link) && typeof link['href'] === 'string') return link['href']\n return undefined\n}\n\n/** `meta` with its `total` moved as the overlay reports for `target`, when both say so. */\nfunction withTotal(\n meta: Record<string, unknown> | undefined,\n target: object,\n): Record<string, unknown> | undefined {\n const raw = meta?.['total']\n if (overlay?.total === undefined || typeof raw !== 'number' || !Number.isFinite(raw)) {\n return meta\n }\n const total = overlay.total([target], raw)\n return total === raw ? meta : cachedCopy(meta!, total, () => ({ ...meta, total }))\n}\n\n/** `page` with its `meta.total` moved as the overlay reports for `target`. */\nfunction pageWithTotal(page: Page, target: object): Page {\n const meta = page.meta === undefined ? undefined : withTotal(page.meta, target)\n if (meta === undefined || meta === page.meta) {\n return page\n }\n return cachedCopy(page, meta['total'] as number, () => ({ ...page, meta }))\n}\n\n/** The copies made of each value per total, so an unchanged total reads back the same object. */\nconst COPIES = new WeakMap<object, Map<number, object>>()\n\nfunction cachedCopy<V extends object>(value: V, total: number, make: () => V): V {\n const copies = COPIES.get(value) ?? new Map<number, object>()\n COPIES.set(value, copies)\n let copy = copies.get(total)\n if (copy === undefined) {\n copy = make()\n copies.set(total, copy)\n }\n return copy as V\n}\n\nconst pageMeta = (meta: Record<string, unknown> | undefined): Record<string, unknown> | undefined =>\n isObject(meta?.['page']) ? (meta['page'] as Record<string, unknown>) : undefined\n\n/**\n * The document's paginator (from the primary type's descriptor). Prefers the statically-known\n * `primaryType` (passed by the descriptor binding at the call site) so an EMPTY page still reports\n * the collection's real kind; falls back to sniffing the first member's type (for a re-materialised\n * `$next()` page or a related read, where the primary type isn't threaded).\n */\nfunction primaryPaginator(\n doc: Document,\n ctx: MaterialiseContext,\n primaryType?: string,\n): PaginatorDescriptor | undefined {\n const first = Array.isArray(doc.data) ? doc.data[0] : doc.data\n const type =\n primaryType ??\n (isObject(first) && typeof first['type'] === 'string' ? first['type'] : undefined)\n return type !== undefined ? ctx.descriptor[type]?.paginator : undefined\n}\n\n/**\n * A to-many relation's paginator. The relation's OWN related/relationship endpoint may\n * paginate differently than the related type's top-level collection (D6a), so prefer the\n * per-relation `paginator` (carried in the descriptor only when it diverges); otherwise fall back\n * to the related type's own paginator (the relationship and related endpoints both paginate that\n * type), so the discriminant is identical across the three surfaces. A polymorphic relation\n * resolves off its first declared related type (its members span types, matching the relationship\n * endpoint's first-member resolution).\n */\nexport function relatedPaginator(\n relation: RelationDescriptor | undefined,\n ctx: MaterialiseContext,\n): PaginatorDescriptor | undefined {\n if (relation?.paginator !== undefined) return relation.paginator\n const relatedType = relation?.types[0]\n return relatedType === undefined ? undefined : ctx.descriptor[relatedType]?.paginator\n}\n\n/** The kind a relation's related read answers with when it sends no `page`. See {@link relatedPaginator}. */\nexport function relatedPaginatorKind(\n relation: RelationDescriptor | undefined,\n ctx: MaterialiseContext,\n): PaginatorKind {\n return resolvePaginator(relatedPaginator(relation, ctx)).kind\n}\n","/**\n * The parts of the Standard Schema interface (standardschema.dev) the client calls. Zod, Valibot\n * and ArkType schemas implement it.\n */\nexport interface StandardSchema<Input = unknown> {\n readonly '~standard': {\n readonly version: 1\n readonly vendor: string\n readonly validate: (value: unknown) => StandardSchemaResult | Promise<StandardSchemaResult>\n readonly types?: { readonly input: Input } | undefined\n }\n}\n\n/** What a Standard Schema's `validate` returns. */\nexport type StandardSchemaResult =\n | { readonly value: unknown; readonly issues?: undefined }\n | { readonly issues: readonly StandardSchemaIssue[] }\n\n/** One problem a Standard Schema found. */\nexport interface StandardSchemaIssue {\n readonly message: string\n readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[] | undefined\n}\n\n/**\n * The schemas `createClient({ validateInput })` checks a write's input against before sending it,\n * by wire type: `{ albums: { create: albumsCreateSchema, update: albumsUpdateSchema } }`. A type or\n * a write with no schema is sent unchecked. `json-api-codegen --zod` generates this map.\n */\nexport type InputSchemas = Readonly<\n Record<string, { readonly create?: StandardSchema; readonly update?: StandardSchema }>\n>\n\n/**\n * Thrown by a create or update whose input fails the schema `validateInput` holds for it, before\n * any request is sent. `fieldErrors(error)` takes it as it takes a server's 422.\n */\nexport class InputValidationError extends Error {\n readonly type: string\n readonly operation: 'create' | 'update'\n readonly issues: readonly StandardSchemaIssue[]\n /** The failing operation's index in an atomic batch. */\n readonly opIndex?: number\n\n constructor(\n type: string,\n operation: 'create' | 'update',\n issues: readonly StandardSchemaIssue[],\n opIndex?: number,\n ) {\n const first = issues[0]?.message\n super(\n `The ${type} ${operation} input${opIndex === undefined ? '' : ` of atomic operation ${opIndex}`} is invalid` +\n (first === undefined ? '' : `: ${first}`) +\n (issues.length > 1 ? ` (and ${issues.length - 1} more)` : ''),\n )\n this.name = 'InputValidationError'\n this.type = type\n this.operation = operation\n this.issues = issues\n if (opIndex !== undefined) {\n this.opIndex = opIndex\n }\n }\n}\n\n/** One write's input, as `validateInput` checks it. */\nexport interface InputCheck {\n readonly type: string\n readonly operation: 'create' | 'update'\n readonly input: unknown\n readonly opIndex?: number\n}\n\n/**\n * The {@link InputValidationError} `check`'s input fails its schema in `schemas` with, or\n * `undefined` when it passes or has no schema. A Promise only for a schema that validates\n * asynchronously.\n */\nexport function inputFailure(\n schemas: InputSchemas | undefined,\n check: InputCheck,\n): InputValidationError | undefined | Promise<InputValidationError | undefined> {\n const schema = schemas?.[check.type]?.[check.operation]\n if (schema === undefined) {\n return undefined\n }\n const failure = (result: StandardSchemaResult) =>\n result.issues === undefined\n ? undefined\n : new InputValidationError(check.type, check.operation, result.issues, check.opIndex)\n const result = schema['~standard'].validate(check.input)\n return result instanceof Promise ? result.then(failure) : failure(result)\n}\n\n/**\n * Run `write` once `check`'s input passes its schema, else reject with the\n * {@link InputValidationError}. A write with no schema, or a schema that validates synchronously,\n * starts in this tick.\n */\nexport function withInputCheck<T>(\n schemas: InputSchemas | undefined,\n check: InputCheck,\n write: () => Promise<T>,\n): Promise<T> {\n const proceed = (failure: InputValidationError | undefined): Promise<T> =>\n failure === undefined ? write() : Promise.reject(failure)\n const failure = inputFailure(schemas, check)\n return failure instanceof Promise ? failure.then(proceed) : proceed(failure)\n}\n","/**\n * The flat input-path key format: `.` between names, `[n]` for a to-many member's index, as in\n * `orderedTracks[0].$pivot.position`. `byPath()` and `fieldErrors()` key errors by it.\n */\nexport function joinInputPath(segments: readonly (string | number)[]): string {\n return segments\n .map((segment, i) =>\n typeof segment === 'number' ? `[${segment}]` : i === 0 ? segment : `.${segment}`,\n )\n .join('')\n}\n\n/** The segments of a flat input-path key: `a[0].b` is `['a', 0, 'b']`. */\nexport function splitInputPath(key: string): (string | number)[] {\n return Array.from(key.matchAll(/([^.[\\]]+)|\\[(\\d+)\\]/g), ([, name, index]) =>\n index === undefined ? name! : Number(index),\n )\n}\n","/**\n * The write serialisation layer (docs/writes.md and docs/errors.md).\n * Two descriptor-aware inverses of the wire shape:\n *\n * - {@link toDocument} builds the JSON:API write document from the caller's FLAT input\n * (the client owns the envelope), routing each key to `attributes` or `relationships`\n * by the descriptor and coercing relationship linkage by cardinality;\n * - {@link remapPointer} / {@link withRemappedPaths} invert a write error's\n * `source.pointer` back to that flat path so {@link JsonApiError.byPath} groups by the\n * shape the caller actually supplied (form/validation UX).\n */\nimport type { ApiDescriptor } from './descriptor'\nimport { JsonApiError, type JsonApiErrorObject } from './errors'\nimport { joinInputPath } from './input-path'\n\n/** Per-edge writable pivot data, supplied on a to-many member as the `$pivot` key. */\nconst PIVOT_KEY = '$pivot'\n\n/** The resource object's own `meta`, supplied in a write input as the `$meta` key. */\nconst META_KEY = '$meta'\n\n/**\n * The key an error on the request document's top-level `meta`, sent as a write's `meta` option, is\n * grouped under: `$meta` names the resource object's, so the document's is `$documentMeta`.\n */\nconst DOCUMENT_META_KEY = '$documentMeta'\n\n/** The flat path of a pointer into the request document's top-level `meta`, else `undefined`. */\nfunction documentMetaPath(segments: readonly string[]): string | undefined {\n return segments[0] === 'meta' ? pointerPath([DOCUMENT_META_KEY, ...segments.slice(1)]) : undefined\n}\n\n/** Pointer segments as a flat input path, a numeric segment indexing an array: `tags[0]`. */\nfunction pointerPath(segments: readonly string[]): string {\n return joinInputPath(segments.map((s) => (/^\\d+$/.test(s) ? Number(s) : s)))\n}\n\n/** The reserved input keys never routed to attributes/relationships. */\nconst RESERVED_INPUT: ReadonlySet<string> = new Set(['type', 'id'])\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/**\n * A JSON:API resource identifier in a write document: `{ type, id }` or — inside an atomic\n * batch — `{ type, lid }` (a reference to a resource created earlier in the same transaction).\n * May carry writable pivot meta on a to-many member.\n */\ninterface WriteIdentifier {\n type: string\n id?: string\n lid?: string\n meta?: { pivot: Record<string, unknown> } & Record<string, unknown>\n}\n\n/** A relationship document: `{ data: <linkage> }`. */\nexport interface RelationshipDocument {\n data: WriteIdentifier | WriteIdentifier[] | null\n}\n\n/** The JSON:API write document {@link toDocument} produces. */\nexport interface WriteDocument {\n data: {\n type: string\n id?: string\n attributes?: Record<string, unknown>\n relationships?: Record<string, RelationshipDocument>\n meta?: Record<string, unknown>\n }\n /** The document's top-level `meta`, which a write takes in its options. */\n meta?: Readonly<Record<string, unknown>>\n}\n\n/** Options for {@link toDocument}. */\nexport interface ToDocumentOptions {\n /**\n * The resource id, supplied for an UPDATE (it comes from the handle, not the input). When\n * present it is always written as `data.id`. Omit for a CREATE — then `input.id` is written\n * only per the type's `clientId` policy.\n */\n id?: string\n}\n\n/**\n * Build a JSON:API write document from FLAT input. Each input key is routed via the\n * descriptor: a declared relation -> `data.relationships[name] = { data: <linkage> }`;\n * anything else -> `data.attributes[name]`. Relationship linkage is coerced by cardinality:\n *\n * - to-one accepts an identifier `{type,id}`, a materialised resource object (its `{type,id}`\n * are extracted), or `null` (-> `data: null`, clearing the relationship);\n * - to-many accepts an array of those; a member may carry a `$pivot` object, rendered as the\n * member identifier's `meta.pivot` (writable pivot fields).\n *\n * `data.type` is always the accessor `type`. `data.id` is written from `opts.id` (an update),\n * else from `input.id` only when the type's `clientId` policy allows it (omitted when\n * `forbidden`, passed through when `optional`/`required`). A `$meta` object is the resource\n * object's `meta`.\n */\nexport function toDocument(\n descriptor: ApiDescriptor,\n type: string,\n input: Record<string, unknown>,\n opts?: ToDocumentOptions,\n): WriteDocument {\n const resource = descriptor[type]\n const relations = resource?.relations ?? {}\n\n const data: WriteDocument['data'] = { type }\n\n const id = resolveId(input, opts, resource?.clientId)\n if (id !== undefined) {\n data.id = id\n }\n\n const attributes: Record<string, unknown> = {}\n const relationships: Record<string, RelationshipDocument> = {}\n\n for (const [keyName, value] of Object.entries(input)) {\n if (RESERVED_INPUT.has(keyName)) {\n continue\n }\n if (keyName === META_KEY) {\n if (isObject(value)) {\n data.meta = value\n }\n continue\n }\n const relation = relations[keyName]\n if (relation !== undefined) {\n relationships[keyName] = { data: coerceLinkage(value, relation.cardinality) }\n } else {\n attributes[keyName] = value\n }\n }\n\n if (Object.keys(attributes).length > 0) {\n data.attributes = attributes\n }\n if (Object.keys(relationships).length > 0) {\n data.relationships = relationships\n }\n\n return { data }\n}\n\n/**\n * A write document with the top-level `meta` a call's options carry, or the document as it is\n * when they carry none.\n */\nexport function withTopLevelMeta<Doc extends object>(\n doc: Doc,\n meta: Readonly<Record<string, unknown>> | undefined,\n): Doc & { meta?: Readonly<Record<string, unknown>> } {\n return meta === undefined ? doc : { ...doc, meta }\n}\n\n/**\n * Build a relationship-mutation document `{ data: <linkage> }` for the\n * `/{type}/{id}/relationships/{rel}` endpoints, coercing the caller's refs by cardinality:\n *\n * - to-one accepts an identifier `{type,id}`, a materialised resource object, or `null`\n * (-> `data: null`, clearing the relationship);\n * - to-many accepts an array of those; a member may carry `$pivot`, rendered as the member\n * identifier's `meta.pivot`.\n *\n * The same {@link coerceLinkage} the whole-resource writer uses, so a relationship written\n * standalone and one embedded in a resource serialise identically.\n */\nexport function toRelationshipDocument(\n refs: unknown,\n cardinality: 'one' | 'many',\n): RelationshipDocument {\n return { data: coerceLinkage(refs, cardinality) }\n}\n\n/** Resolve the document id: an update's handle id always wins; a create honours the policy. */\nfunction resolveId(\n input: Record<string, unknown>,\n opts: ToDocumentOptions | undefined,\n clientId: ApiDescriptor[string]['clientId'] | undefined,\n): string | undefined {\n if (opts?.id !== undefined) {\n return opts.id\n }\n if (clientId === 'forbidden') {\n return undefined\n }\n const candidate = input['id']\n return typeof candidate === 'string' ? candidate : undefined\n}\n\n/** Coerce one relationship value to linkage by cardinality (array for to-many, identifier/null for to-one). */\nfunction coerceLinkage(\n value: unknown,\n cardinality: 'one' | 'many',\n): WriteIdentifier | WriteIdentifier[] | null {\n if (cardinality === 'many') {\n const members = Array.isArray(value) ? value : value == null ? [] : [value]\n return members.map((member) => toIdentifier(member))\n }\n if (value === null || value === undefined) {\n return null\n }\n return toIdentifier(value)\n}\n\n/**\n * Extract a resource identifier from a linkage input value: an identifier `{type,id}`, a\n * materialised resource object (the same `{type,id}` enumerable props), or — inside an atomic\n * batch — a local identifier `{type,lid}` referencing a just-created resource (the handle a\n * `tx.create` returns). A `$pivot` key is lifted onto `meta.pivot` (writable pivot fields).\n * Throws on a value carrying no `type`, or neither an `id` nor a `lid`.\n */\nfunction toIdentifier(value: unknown): WriteIdentifier {\n if (!isObject(value)) {\n throw new TypeError(\n `Relationship linkage must be an identifier or resource object; received ${describe(value)}`,\n )\n }\n const { type, id, lid } = value\n if (typeof type !== 'string') {\n throw new TypeError('Relationship linkage requires a `type`')\n }\n // An `id` identifies an existing resource; a `lid` references one created earlier in the\n // same atomic transaction. Exactly one is needed.\n const identifier: WriteIdentifier =\n typeof id === 'string'\n ? { type, id }\n : typeof lid === 'string'\n ? { type, lid }\n : (() => {\n throw new TypeError('Relationship linkage requires an `id` or a `lid`')\n })()\n\n const pivot = value[PIVOT_KEY]\n if (isObject(pivot)) {\n identifier.meta = { pivot }\n }\n return identifier\n}\n\nconst describe = (value: unknown): string =>\n value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value\n\n/**\n * Invert a write error's `source.pointer` to the caller's FLAT input path, descriptor-aware:\n *\n * - `/data/attributes/title` -> `title`\n * - `/data/relationships/artist/data` -> `artist`\n * - `/data/id` -> `id` (client-id create conflict)\n * - `/data/attributes/releaseInfo/label` -> `releaseInfo.label` (nested map)\n * - `/data/relationships/orderedTracks/data/0/meta/pivot/position` -> `orderedTracks[0].$pivot.position`\n * - `/data/meta/source` -> `$meta.source`\n * - `/meta/idempotencyKey` -> `$documentMeta.idempotencyKey`\n *\n * Pivot values nest under a member's `meta.pivot` (symmetric with reads — see\n * `JsonPointerBuilder::forLinkageMeta`), so a `meta/pivot/<field>` tail on\n * a member of a pivot-bearing to-many is surfaced as `.$pivot.<field>`.\n *\n * A query-side pointer is left untouched (those are already user-facing — see\n * {@link withRemappedPaths}). An unrecognised / non-write pointer is returned verbatim.\n * `/data/type` and a bare `/data` are passed through (the client owns those; the caller\n * never supplies them).\n */\nexport function remapPointer(descriptor: ApiDescriptor, type: string, pointer: string): string {\n const segments = pointer.split('/').filter((s) => s !== '')\n if (segments[0] !== 'data') {\n return documentMetaPath(segments) ?? pointer\n }\n if (segments[1] === 'meta') {\n return pointerPath([META_KEY, ...segments.slice(2)])\n }\n\n if (segments[1] === 'attributes') {\n return pointerPath(segments.slice(2))\n }\n if (segments[1] === 'id') {\n return 'id'\n }\n if (segments[1] === 'relationships') {\n return remapRelationship(descriptor[type]?.relations ?? {}, segments.slice(2))\n }\n\n return pointer\n}\n\n/**\n * Remap a relationship pointer's tail (everything after `relationships/`, or — for a\n * relationship-endpoint document — the relation name spliced ahead of the `data` tail). The\n * leading segment is the relation name; a `data` segment is dropped; a numeric index becomes\n * `[n]`; a `meta/pivot/<field>` tail on a pivot-bearing relation becomes `.$pivot.<field>`. The\n * `relations` map tells us whether the relation carries pivot (so a member's `meta.pivot`\n * fields are the pivot data the bundle validates).\n */\nfunction remapRelationship(\n relations: Readonly<Record<string, { pivot?: boolean }>>,\n rest: readonly string[],\n): string {\n const name = rest[0]\n if (name === undefined) {\n return 'data/relationships'\n }\n const hasPivot = relations[name]?.pivot === true\n\n const path: (string | number)[] = [name]\n for (let i = 1; i < rest.length; i++) {\n const seg = rest[i]!\n if (seg === 'data') {\n continue\n }\n if (/^\\d+$/.test(seg)) {\n path.push(Number(seg))\n } else if (seg === 'meta' && hasPivot && rest[i + 1] === 'pivot') {\n // Pivot values nest under `meta.pivot` — collapse the\n // `meta/pivot` pair to `$pivot`; the offending field follows.\n path.push('$pivot')\n i++\n } else {\n path.push(seg)\n }\n }\n\n return joinInputPath(path)\n}\n\n/**\n * Invert a relationship-MUTATION error's `source.pointer` to the caller's flat path, for the\n * `/{type}/{id}/relationships/{rel}` endpoints. Two pointer shapes reach here:\n *\n * - the LINKAGE document shape (validation on the linkage members), rooted at `data` — the\n * relation name is supplied by the route, not the wire:\n * - `/data` -> `<rel>` (to-one clear/set)\n * - `/data/meta/pivot/position` -> `<rel>.$pivot.position` (to-one pivot, rare)\n * - `/data/0/meta/pivot/position` -> `<rel>[0].$pivot.position`\n * - the RESOURCE-document shape that core's relationship prohibitions emit unchanged\n * (`FullReplacementProhibited`/`RemovalProhibited`/`AdditionProhibited`/\n * `RelationshipTypeInappropriate` all point at `/data/relationships/<name>`) — short-circuited\n * to the relation name (drop the `relationships/<name>` prefix) rather than treating\n * `relationships` as a linkage sub-segment.\n *\n * A pointer into the top-level `meta` becomes `$documentMeta.<member>`, and any other non-`data`\n * pointer is returned verbatim.\n */\nexport function remapRelationshipPointer(rel: string, hasPivot: boolean, pointer: string): string {\n const segments = pointer.split('/').filter((s) => s !== '')\n if (segments[0] !== 'data') {\n return documentMetaPath(segments) ?? pointer\n }\n // A resource-document relationship pointer (`/data/relationships/<name>...`): the route's\n // relation name owns the path; drop the `relationships/<name>` prefix (segments[2] is the\n // wire name, == the route `rel`) and remap the remaining tail under the route relation.\n const tail = segments[1] === 'relationships' ? segments.slice(3) : segments.slice(1)\n return remapRelationship({ [rel]: { pivot: hasPivot } }, [rel, ...tail])\n}\n\n/**\n * Return a {@link JsonApiError} with each error object's `path` populated by remapping its\n * `source.pointer` (descriptor-aware) — so {@link JsonApiError.byPath} groups by the flat input\n * shape. Errors with no write pointer (e.g. a `source.parameter` query-side error, or no\n * source) are passed through unchanged. The original error is not mutated.\n */\nexport function withRemappedPaths(\n error: JsonApiError,\n descriptor: ApiDescriptor,\n type: string,\n): JsonApiError {\n return mapErrors(error, (pointer) => ({ path: remapPointer(descriptor, type, pointer) }))\n}\n\n/**\n * The relationship-mutation twin of {@link withRemappedPaths}: remap each error's pointer\n * keyed by the relation name from the route. Handles both the linkage-document shape (rooted\n * at `data`) and the resource-document shape core's prohibition exceptions emit\n * (`/data/relationships/<rel>`). `hasPivot` lets a member-level `meta` field surface as\n * `$pivot`. The original error is not mutated.\n */\nexport function withRemappedRelationshipPaths(\n error: JsonApiError,\n rel: string,\n hasPivot: boolean,\n): JsonApiError {\n return mapErrors(error, (pointer) => ({ path: remapRelationshipPointer(rel, hasPivot, pointer) }))\n}\n\n/**\n * Give each error on the request document's top-level `meta` its `$documentMeta.<member>` path,\n * for a request whose other members the client didn't build, such as a bespoke action document or\n * a meta-only one. Every other error is passed through unchanged. The original error is not\n * mutated.\n */\nexport function withRemappedDocumentMetaPaths(error: JsonApiError): JsonApiError {\n const remapped: JsonApiErrorObject[] = error.errors.map((e) => {\n const path =\n e.source?.pointer === undefined\n ? undefined\n : documentMetaPath(e.source.pointer.split('/').filter((s) => s !== ''))\n return path === undefined ? e : { ...e, path }\n })\n return new JsonApiError(error.status, remapped, error.message)\n}\n\n/**\n * Invert an atomic-batch error's `source.pointer` to `(opIndex, flatPath)`: an atomic 422\n * points at `/atomic:operations/{n}/data/...`, so strip the `atomic:operations/{n}` prefix to\n * the op index, resolve that op's wire type (`typeForOp`), and delegate the remaining `/data`\n * tail to the same {@link remapPointer} a standalone write uses (so the flat path is identical\n * — `title`, `releaseInfo.label`, `artist`, …). A relationship op's tail is remapped under its\n * relation, as a standalone relationship write's is, when `relationForOp` names one. A pointer\n * without the atomic prefix is remapped\n * verbatim under the (whole-batch) document at op index `undefined`. The original error is not\n * mutated.\n */\nexport function withRemappedAtomicPaths(\n error: JsonApiError,\n descriptor: ApiDescriptor,\n typeForOp: (opIndex: number) => string | undefined,\n relationForOp?: (opIndex: number) => { rel: string; hasPivot: boolean } | undefined,\n): JsonApiError {\n return mapErrors(error, (pointer) => {\n const segments = pointer.split('/').filter((s) => s !== '')\n if (segments[0] !== 'atomic:operations' || segments[1] === undefined) {\n return { path: pointer }\n }\n const opIndex = Number(segments[1])\n if (!Number.isInteger(opIndex)) {\n return { path: pointer }\n }\n const type = typeForOp(opIndex)\n const relation = relationForOp?.(opIndex)\n const tail = `/${segments.slice(2).join('/')}`\n const path =\n relation !== undefined\n ? remapRelationshipPointer(relation.rel, relation.hasPivot, tail)\n : type === undefined\n ? tail\n : remapPointer(descriptor, type, tail)\n return { opIndex, path }\n })\n}\n\n/** What a per-error remap resolves to: the flat `path` and, for an atomic batch, the `opIndex`. */\ninterface RemapResult {\n path: string\n opIndex?: number\n}\n\n/** Shared error-mapper: clone each error with `path`/`opIndex` from its `source.pointer`, else pass through. */\nfunction mapErrors(error: JsonApiError, remap: (pointer: string) => RemapResult): JsonApiError {\n const remapped: JsonApiErrorObject[] = error.errors.map((e) => {\n const pointer = e.source?.pointer\n if (pointer === undefined) {\n return e\n }\n const { path, opIndex } = remap(pointer)\n return opIndex === undefined ? { ...e, path } : { ...e, path, opIndex }\n })\n return new JsonApiError(error.status, remapped, error.message)\n}\n","/**\n * The Atomic Operations transaction builder (docs/atomic-operations.md).\n * `client.atomic(tx => { … })` records a batch of operations and\n * posts them all-or-nothing to the server's `/operations` endpoint (the atomic ext media type),\n * returning the positional, materialised results.\n *\n * The `tx` recorder is NOT type-scoped (one builder spans every type), so each op carries its\n * own `type` discriminant:\n *\n * - `tx.create({ type, …flatFields })` -> an `add` op; returns a handle that DOUBLES AS a\n * `lid`-bearing relationship ref (`{ type, lid }`) so a just-created resource wires into a\n * later op without a server-assigned id;\n * - `tx.update({ type, id, …flatFields })` -> an `update` op (a `ref` to the existing resource);\n * - `tx.delete({ type, id })` -> a `remove` op;\n * - `tx.rel(ref, relationship)` reaches a relationship of the resource `ref` names, as the\n * standalone relationship accessor does: its `add`, `remove` and `replace` change the members of\n * a to-many, and its `set` a to-one's.\n *\n * Each create gets a deterministic `lid` from its op index (`atomic-<index>`), so the cross-op\n * reference is stable and human-readable. The flat->envelope serialisation reuses the same\n * {@link toDocument} the standalone writes use, so an atomic create body is identical to a\n * `POST /{type}` body (minus the swap of a server `id` for the generated `lid`).\n *\n * Content negotiation: the batch opts into the atomic extension via the request's `ext`\n * parameter ({@link ATOMIC_EXT}), so {@link execute} composes the atomic-ext media type\n * (`application/vnd.api+json; ext=\"…\"`) for both `Content-Type` and `Accept` — the generalised\n * media-type path the rest of the runtime shares.\n */\nimport type { ApiDescriptor, RequestMetaOperation } from './descriptor'\nimport { JsonApiError } from './errors'\nimport { materialise, type MaterialiseContext } from './materialise'\nimport { executeResponse, type JsonApiContext, type JsonApiRequest } from './request'\nimport { stampRequest } from './request-stamp'\nimport type {\n AtomicResultOf,\n CreateInput,\n MetaOption,\n MutationVerb,\n OptionsArg,\n RelationName,\n RelationRequestMetaOf,\n RelationshipMembers,\n RequestMetaOf,\n RequiresRequestMeta,\n TakesVerb,\n TypeName,\n UpdateInput,\n WritableRelationName,\n} from './result-types'\nimport { type InputCheck, type InputSchemas, inputFailure } from './input-validation'\nimport { toDocument, toRelationshipDocument, withRemappedAtomicPaths } from './serialize-write'\nimport type { LocalIdentifier, ResourceIdentifier } from './types'\nimport { ATOMIC_EXT } from './types'\n\n/**\n * A reference to a resource for an `update`/`remove` op: a bare identifier (or a materialised\n * resource — its `{type,id}` extracted), OR a `{ type, lid }` local identifier targeting a\n * resource CREATED EARLIER IN THE SAME BATCH (e.g. a `tx.create` handle), so an op can update\n * or remove a just-created resource that has no server id yet (per the JSON:API atomic ext,\n * `ref` may carry `lid` instead of `id`).\n */\nexport type AtomicRef =\n | ResourceIdentifier\n | { type: string; id: string }\n | LocalIdentifier\n | { type: string; lid: string }\n\n/**\n * Flat create input for type `T`: the `type` discriminant plus the type's flat create\n * attributes/relation slots (reusing {@link CreateInput}; relation slots may reference a prior\n * `tx.create` handle). `D`/`W` thread the descriptor + write-attribute map for precise fields;\n * the loose defaults keep a codegen-less caller compiling.\n */\nexport type AtomicCreateInput<D extends ApiDescriptor, W, T extends TypeName<D>> = {\n type: T\n} & CreateInput<D, W, T, 'atomicCreate'>\n\n/**\n * Flat update input for type `T`: the `type` discriminant + the target's identity (`id`, OR a\n * `lid` for a resource created earlier in the same batch) plus the type's flat update\n * attributes/relation slots (reusing {@link UpdateInput}).\n */\nexport type AtomicUpdateInput<D extends ApiDescriptor, W, T extends TypeName<D>> =\n | ({ type: T; id: string; lid?: never } & UpdateInput<D, W, T, 'atomicUpdate'>)\n | ({ type: T; lid: string; id?: never } & UpdateInput<D, W, T, 'atomicUpdate'>)\n\n/**\n * The options argument of an atomic operation of type `T`: the operation's `meta`, typed by the\n * type's `atomicRequestMeta` and required when a member is. A type declaring none takes any.\n */\nexport type AtomicOperationArgs<\n D extends ApiDescriptor,\n T extends TypeName<D>,\n Op extends RequestMetaOperation,\n> = OptionsArg<\n RequiresRequestMeta<RequestMetaOf<D, T, Op, true>>,\n MetaOption<RequestMetaOf<D, T, Op, true>>\n>\n\n/**\n * The options argument of an atomic operation with verb `V` on relation `R` of type `T`: its\n * `meta`, typed by the relation's `atomicRequestMeta` and required when a member is. A relation\n * declaring none takes any.\n */\nexport type AtomicRelationshipArgs<\n D extends ApiDescriptor,\n T extends TypeName<D>,\n R extends RelationName<D, T>,\n V extends MutationVerb,\n> = OptionsArg<\n RequiresRequestMeta<RelationRequestMetaOf<D, T, R, V, true>>,\n MetaOption<RelationRequestMetaOf<D, T, R, V, true>>\n>\n\n/**\n * The handle a {@link AtomicRecorder.create} returns. It is a `lid`-bearing relationship ref\n * (`{ type, lid }`) — pass it (or spread it) into a later op's relation slot to wire the\n * just-created resource without a server id. It also carries its op `kind` (`'create'`) and its\n * `opIndex` (its position in the batch, the created resource's positional result) so the typed\n * result tuple can map it back to the right positional result.\n */\nexport interface AtomicCreateHandle<T extends string = string> extends LocalIdentifier {\n readonly type: T\n readonly kind: 'create'\n readonly opIndex: number\n}\n\n/**\n * The handle a {@link AtomicRecorder.update} returns: its type discriminant `T`, its op `kind`\n * (`'update'`) and its `opIndex`. Returned (alongside the create handle) from the callback so its\n * positional result is typed as the materialised resource of `T`.\n */\nexport interface AtomicUpdateHandle<T extends string = string> {\n readonly type: T\n readonly kind: 'update'\n readonly opIndex: number\n}\n\n/**\n * The handle a {@link AtomicRecorder.delete} returns: its op `kind` (`'delete'`) and its\n * `opIndex`. A delete carries no data, so its positional result is `undefined`.\n */\nexport interface AtomicDeleteHandle {\n readonly kind: 'delete'\n readonly opIndex: number\n}\n\n/**\n * The handle a relationship operation returns (the `add`, `remove`, `replace` or `set` of\n * {@link AtomicRecorder.rel}): the target's type `T`, its `relationship` `R`, its op `kind`\n * (`'relationship'`) and its `opIndex`. Its positional result is the linkage the server answered\n * with.\n */\nexport interface AtomicRelationshipHandle<T extends string = string, R extends string = string> {\n readonly type: T\n readonly relationship: R\n readonly kind: 'relationship'\n readonly opIndex: number\n}\n\n/**\n * Any handle a recorder method returns — the element type of the callback's result tuple, used\n * as the inference constraint for the typed-tuple `atomic` form. The discriminant is left open\n * (`string`, NOT `TypeName<D>`) DELIBERATELY, so the type is descriptor-agnostic: a tighter\n * `TypeName<D>` constraint would flow the full type union into each element's contextual type\n * during array-literal inference, widening a `tx.create({ type: 'albums' })` handle's `T` back to\n * the whole union — losing the per-op narrowing. The recorder methods already guarantee each `T`\n * is a real `TypeName<D>`, so the open constraint is sound; `AtomicResultOf` re-infers the precise\n * `T` per element (guarded by `TypeName<D>` there).\n */\nexport type AtomicHandle =\n | AtomicCreateHandle<string>\n | AtomicUpdateHandle<string>\n | AtomicDeleteHandle\n | AtomicRelationshipHandle<string, string>\n\n/**\n * A relationship verb inside an atomic batch: present only when relation `R`'s cardinality matches\n * the verb's and the relation advertises it in its `mutations` flags, as the standalone accessor's\n * verbs are gated, and `never` otherwise.\n */\ntype AtomicRelationMutation<\n D extends ApiDescriptor,\n T extends TypeName<D>,\n R extends RelationName<D, T>,\n V extends MutationVerb,\n> =\n TakesVerb<D, T, R, V> extends true\n ? (\n members: RelationshipMembers<D, T, R, V>,\n ...opts: AtomicRelationshipArgs<D, T, R, V>\n ) => AtomicRelationshipHandle<T, R>\n : never\n\n/**\n * What {@link AtomicRecorder.rel} returns: relation `R` of a resource of type `T`, whose verbs\n * each record one relationship operation. A to-many takes `add`, `remove` and `replace` and a\n * to-one `set`, each only when the relation advertises it.\n */\nexport interface AtomicRelationshipRecorder<\n D extends ApiDescriptor,\n T extends TypeName<D>,\n R extends RelationName<D, T>,\n> {\n /** Add `members` to the to-many: an `add` op on its relationship. */\n add: AtomicRelationMutation<D, T, R, 'add'>\n /** Remove `members` from the to-many: a `remove` op on its relationship. */\n remove: AtomicRelationMutation<D, T, R, 'remove'>\n /** Replace every member of the to-many with `members`: an `update` op on its relationship. */\n replace: AtomicRelationMutation<D, T, R, 'replace'>\n /** Set the to-one to `member`, or clear it with `null`: an `update` op on its relationship. */\n set: AtomicRelationMutation<D, T, R, 'set'>\n}\n\n/** A single recorded atomic operation, in wire shape (`op` + `ref`/`data`, and its `meta`). */\ninterface AtomicOperation {\n op: 'add' | 'update' | 'remove'\n ref?: { type: string; id?: string; lid?: string; relationship?: string }\n data?: unknown\n meta?: Readonly<Record<string, unknown>>\n}\n\n/** The identity of an op's target resource: a server `id` or a same-batch `lid`. */\ntype AtomicIdentity = { id: string } | { lid: string }\n\n/**\n * The recorder handed to the `client.atomic` callback. Each method appends an op (preserving\n * order) and returns a handle carrying the op's discriminant `T`, `kind`, and `opIndex`. The\n * methods are generic over `T` (inferred from the input's `type`), so a create/update is typed\n * by the type's write-input ({@link CreateInput}/{@link UpdateInput}) and its handle resolves to\n * the materialised resource of `T`. `create` still returns a usable `{ type, lid }` ref so a\n * just-created resource wires into a later op without a server id.\n */\nexport interface AtomicRecorder<D extends ApiDescriptor, W> {\n create<T extends TypeName<D>>(\n input: AtomicCreateInput<D, W, T>,\n ...opts: AtomicOperationArgs<D, T, 'create'>\n ): AtomicCreateHandle<T>\n update<T extends TypeName<D>>(\n input: AtomicUpdateInput<D, W, T>,\n ...opts: AtomicOperationArgs<D, T, 'update'>\n ): AtomicUpdateHandle<T>\n delete<T extends TypeName<D>>(\n ref: AtomicRef & { type: T },\n ...opts: AtomicOperationArgs<D, T, 'delete'>\n ): AtomicDeleteHandle\n /**\n * Relation `relationship` of the resource `ref` names, by its server `id` or the `lid` of a\n * resource created earlier in the batch. Its verbs record operations on the relationship. Only\n * a relation that takes at least one verb is accepted.\n */\n rel<T extends TypeName<D>, R extends WritableRelationName<D, T>>(\n ref: AtomicRef & { type: T },\n relationship: R,\n ): AtomicRelationshipRecorder<D, T, R>\n}\n\n/** The wire `op` each relationship verb records: `replace` and `set` both update the relationship. */\nconst RELATIONSHIP_OPS = {\n add: 'add',\n remove: 'remove',\n replace: 'update',\n set: 'update',\n} as const satisfies Record<MutationVerb, AtomicOperation['op']>\n\n/** The options an atomic recorder method takes at runtime. */\ninterface AtomicOperationOptions {\n meta?: Readonly<Record<string, unknown>>\n}\n\n/** An operation with its `meta` added when the caller sent any. */\nconst withOperationMeta = (\n operation: AtomicOperation,\n opts: AtomicOperationOptions | undefined,\n): AtomicOperation => (opts?.meta === undefined ? operation : { ...operation, meta: opts.meta })\n\n/** One positional result of an atomic batch: the materialised `data` (a resource/`null`) plus any op `meta`. */\nexport interface AtomicResult<Data = unknown> {\n data: Data\n meta?: Record<string, unknown>\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/** The deterministic local id for the create at `opIndex` (stable + human-readable). */\nconst lidFor = (opIndex: number): string => `atomic-${opIndex}`\n\n/**\n * The typed result tuple for a callback that returns a tuple of handles `Ops`: each returned\n * handle maps (by {@link AtomicResultOf}) to its materialised positional result — a create/update\n * handle to the `AtomicResult` of its type, a delete handle to `undefined`. The mapping is\n * positional in the RETURNED order (sound regardless of subset/reorder, since the runtime resolves\n * each handle by its `opIndex`).\n */\nexport type AtomicResults<D extends ApiDescriptor, A, Ops extends readonly AtomicHandle[]> = {\n -readonly [K in keyof Ops]: AtomicResultOf<D, A, Ops[K]>\n}\n\n/**\n * Run an atomic transaction. Invokes `build` with a recorder, collecting the operations (always\n * via the recorder's side effect, preserving op order), then posts `{ \"atomic:operations\": [...] }`\n * to the atomic endpoint with the ext media type as both `Content-Type` and `Accept`. The server's\n * `{ \"atomic:results\": [...] }` is parsed positionally — each result's `data` materialised the same\n * as a read.\n *\n * The return shape depends on what `build` returns:\n *\n * - returns a tuple of handles -> a per-op POSITIONALLY-TYPED tuple: each returned handle is\n * resolved to its result BY ITS `opIndex` (`results[handle.opIndex]`), so the tuple is sound\n * regardless of the order/subset the callback returns the handles in (a delete handle resolves\n * to `undefined`);\n * - returns void/nothing -> the loose, ordered `AtomicResult[]` (backward-compatible).\n *\n * A thrown {@link JsonApiError} has each error's pointer remapped to `(opIndex, flatPath)` (the\n * failing op's type drives the flat-path inversion) before it propagates.\n */\nexport function runAtomic<D extends ApiDescriptor, A, W, const Ops>(\n request: JsonApiContext,\n materialiseCtx: MaterialiseContext,\n descriptor: D,\n path: string,\n build: (tx: AtomicRecorder<D, W>) => Ops,\n inputSchemas?: InputSchemas,\n): Promise<Ops extends readonly AtomicHandle[] ? AtomicResults<D, A, Ops> : AtomicResult[]>\nexport async function runAtomic(\n request: JsonApiContext,\n materialiseCtx: MaterialiseContext,\n descriptor: ApiDescriptor,\n path: string,\n // A recorder over a loose descriptor isn't assignable from one over the caller's, whose\n // required relations differ per type, so the implementation takes the callback untyped.\n build: (tx: never) => readonly AtomicHandle[] | void,\n inputSchemas?: InputSchemas,\n): Promise<AtomicResult[] | readonly (AtomicResult | undefined)[]> {\n const operations: AtomicOperation[] = []\n /** Each create and update input, checked against `inputSchemas` before the batch is sent. */\n const checks: InputCheck[] = []\n /** The wire type of each op, by index — drives the error-pointer remap. */\n const typeByOp: string[] = []\n /** The relation each relationship op writes, by index, which its pointers are remapped under. */\n const relationByOp = new Map<number, { rel: string; hasPivot: boolean }>()\n\n const relationship = (\n verb: MutationVerb,\n { type, identity }: { type: string; identity: AtomicIdentity },\n name: string,\n members: unknown,\n opts: AtomicOperationOptions | undefined,\n ): AtomicRelationshipHandle => {\n const opIndex = operations.length\n const { data } = toRelationshipDocument(members, verb === 'set' ? 'one' : 'many')\n operations.push(\n withOperationMeta(\n { op: RELATIONSHIP_OPS[verb], ref: { type, ...identity, relationship: name }, data },\n opts,\n ),\n )\n typeByOp.push(type)\n relationByOp.set(opIndex, {\n rel: name,\n hasPivot: descriptor[type]?.relations[name]?.pivot === true,\n })\n return { type, relationship: name, kind: 'relationship', opIndex }\n }\n\n const recorder: AtomicRecorder<ApiDescriptor, unknown> = {\n create(input, ...[opts]: [AtomicOperationOptions?]) {\n const opIndex = operations.length\n const lid = lidFor(opIndex)\n const data = atomicResourceData(descriptor, input, { lid })\n const { type: _type, ...fields } = input\n checks.push({ type: input.type, operation: 'create', input: fields, opIndex })\n operations.push(withOperationMeta({ op: 'add', data }, opts))\n typeByOp.push(input.type)\n return { type: input.type, lid, kind: 'create', opIndex }\n },\n update(input, ...[opts]: [AtomicOperationOptions?]) {\n const opIndex = operations.length\n const identity: AtomicIdentity =\n input.id !== undefined ? { id: input.id } : { lid: input.lid }\n const data = atomicResourceData(descriptor, input, identity)\n const { type: _type, lid: _lid, ...fields } = input as Record<string, unknown>\n // A singleton's update schema checks its id; any other type's checks the patch alone.\n const { id: _id, ...patch } = fields\n checks.push({\n type: input.type,\n operation: 'update',\n input: descriptor[input.type]?.singleton === true ? fields : patch,\n opIndex,\n })\n operations.push(\n withOperationMeta({ op: 'update', ref: { type: input.type, ...identity }, data }, opts),\n )\n typeByOp.push(input.type)\n return { type: input.type, kind: 'update', opIndex }\n },\n delete(ref, ...[opts]: [AtomicOperationOptions?]) {\n const opIndex = operations.length\n const { type, identity } = toRef(ref, 'atomic delete')\n operations.push(withOperationMeta({ op: 'remove', ref: { type, ...identity } }, opts))\n typeByOp.push(type)\n return { kind: 'delete', opIndex }\n },\n rel(ref, name) {\n const target = toRef(ref, 'atomic rel')\n if (typeof name !== 'string') {\n throw new TypeError('atomic rel requires a relationship name')\n }\n const verb =\n (v: MutationVerb) =>\n (members: unknown, ...[opts]: [AtomicOperationOptions?]) =>\n relationship(v, target, name, members, opts)\n // Over a loose descriptor no relation takes a verb, so the verbs join untyped.\n return {\n add: verb('add'),\n remove: verb('remove'),\n replace: verb('replace'),\n set: verb('set'),\n } as never\n },\n }\n\n // The callback always drives the recorder side effect (collecting ops in order); its RETURN\n // VALUE — when it's a tuple of handles — selects the typed positional result per handle.\n const returned = (\n build as (tx: AtomicRecorder<ApiDescriptor, unknown>) => readonly AtomicHandle[] | void\n )(recorder)\n\n // In batch order, so the first failing operation rejects the batch.\n for (const check of checks) {\n const failure = await inputFailure(inputSchemas, check)\n if (failure !== undefined) {\n throw failure\n }\n }\n\n const req: JsonApiRequest = {\n method: 'POST',\n path,\n body: { 'atomic:operations': operations },\n // Opt into the atomic extension; `execute` composes the ext media type for both\n // `Content-Type` and `Accept` (the shared media-type-negotiation path).\n ext: [ATOMIC_EXT],\n }\n\n let doc\n let stamp: number\n try {\n ;({ document: doc, stamp } = await executeResponse(request, req))\n } catch (error) {\n if (error instanceof JsonApiError) {\n throw withRemappedAtomicPaths(\n error,\n descriptor,\n (opIndex) => typeByOp[opIndex],\n (opIndex) => relationByOp.get(opIndex),\n )\n }\n throw error\n }\n\n const results = parseResults(\n doc as { ['atomic:results']?: unknown } | undefined,\n materialiseCtx,\n (opIndex) => relationByOp.has(opIndex),\n stamp,\n )\n\n // Loose form: the callback returned nothing, or not an all-handles array -> the ordered results\n // array (backward-compatible). The all-handles guard keeps the runtime in step with the type\n // predicate (`Ops extends readonly AtomicHandle[]`): a stray non-handle element resolves to the\n // loose AtomicResult[] the type promises rather than a row of undefined.\n const isHandleTuple =\n Array.isArray(returned) &&\n returned.every((h) => h !== null && typeof h === 'object' && 'opIndex' in h)\n if (!isHandleTuple) {\n return stampRequest(results, stamp)\n }\n // Typed-tuple form: resolve each RETURNED handle by its `opIndex` (a delete -> undefined), so\n // the tuple is sound regardless of the order/subset of handles returned. (A server returning no\n // `atomic:results` for an op yields undefined; the reference bundle always returns the created/\n // updated resource, so create/update results are typed present.)\n return stampRequest(\n returned.map((handle) => (handle.kind === 'delete' ? undefined : results[handle.opIndex])),\n stamp,\n )\n}\n\n/**\n * Build the resource `data` for an `add`/`update` op from flat input via {@link toDocument}\n * (so attributes/relationships route identically to a standalone write), then carry the op's\n * identity onto the resource: a server `id` (a create's server-assigned id is omitted; an\n * update by id keeps it) or a same-batch `lid` (a create's generated lid, or an update/remove\n * targeting an earlier op's resource).\n */\nfunction atomicResourceData(\n descriptor: ApiDescriptor,\n input: { type: string; [field: string]: unknown },\n identity: AtomicIdentity,\n): Record<string, unknown> {\n // Strip the identity keys before routing — `lid` is not an attribute, and `id` (when present\n // as a flat field) is carried via the identity, not the body. The identity is applied below.\n const { id: _id, lid: _lid, ...fields } = input as Record<string, unknown>\n const { data } = toDocument(\n descriptor,\n input.type,\n fields,\n 'id' in identity ? { id: identity.id } : undefined,\n )\n const out: Record<string, unknown> = { ...data }\n if ('lid' in identity) {\n // A lid-targeted op rides a local id, never a server id.\n delete out['id']\n out['lid'] = identity.lid\n }\n return out\n}\n\n/**\n * Coerce an op's target ref (an identifier, a materialised resource, or a same-batch `{type,lid}`\n * handle) to `{ type, identity }` — `identity` an `id` or a `lid`; throws if neither is present.\n * `what` names the operation in the error.\n */\nfunction toRef(ref: unknown, what: string): { type: string; identity: AtomicIdentity } {\n if (!isObject(ref)) {\n throw new TypeError(`${what} requires an identifier \\`{ type, id }\\` or \\`{ type, lid }\\``)\n }\n const { type, id, lid } = ref as { type?: unknown; id?: unknown; lid?: unknown }\n if (typeof type !== 'string') {\n throw new TypeError(`${what} requires a \\`type\\``)\n }\n if (typeof id === 'string') {\n return { type, identity: { id } }\n }\n if (typeof lid === 'string') {\n return { type, identity: { lid } }\n }\n throw new TypeError(`${what} requires an \\`id\\` or a \\`lid\\``)\n}\n\n/**\n * Parse `{ \"atomic:results\": [...] }` positionally, materialising each result's `data`: a\n * relationship op's as linkage, any other's as a resource, each stamped with the batch's request\n * start. An absent results array (an all-`204` batch) yields `[]`.\n */\nfunction parseResults(\n doc: { ['atomic:results']?: unknown } | undefined,\n ctx: MaterialiseContext,\n isLinkage: (opIndex: number) => boolean,\n stamp: number,\n): AtomicResult[] {\n const results = doc?.['atomic:results']\n if (!Array.isArray(results)) {\n return []\n }\n return results.map((result, opIndex) => {\n const entry = isObject(result) ? result : {}\n const data =\n entry['data'] === undefined\n ? undefined\n : stampRequest(materialise({ data: entry['data'] }, ctx, isLinkage(opIndex)), stamp)\n const out: AtomicResult = { data }\n if (isObject(entry['meta'])) {\n out.meta = entry['meta']\n }\n return out\n })\n}\n","/**\n * The generated runtime descriptor (ADR 0001). The codegen emits one of these per\n * server `as const satisfies ApiDescriptor`; the client's TYPES are derived from it\n * (one source of truth). It carries everything the generic runtime needs that types\n * alone can't: attribute-vs-relation, cardinality, related type(s), per-operation\n * path templates (uriType/prefix-aware), paginator kind, and the create client-id\n * policy.\n */\nexport type Cardinality = 'one' | 'many'\n\n/**\n * The mutation verbs a single relationship endpoint advertises (derived from the HTTP\n * methods it exposes). These are NOT uniform across relations — the bundle gates them\n * per relation (`cannotAdd`/`cannotRemove`/`cannotReplace`, per-relation endpoint\n * exposure) — so the descriptor carries the capability per relation and the fluent\n * surface gates `add`/`remove`/`replace`/`set` on it.\n *\n * For a to-many: `add` <- POST, `remove` <- DELETE, `replace` <- PATCH.\n * For a to-one: `set` <- PATCH. A flag is `true` iff the endpoint advertises the verb.\n */\nexport interface RelationMutations {\n add?: boolean\n remove?: boolean\n replace?: boolean\n set?: boolean\n}\n\n/**\n * The pivot fields one side of the wire carries on a member's `meta.pivot`, the declared\n * identifier meta members a response carries on a member's `meta`, or the members a document\n * declares in its top-level `meta`: field name to wire-format\n * hint (the vocabulary of {@link ResourceDescriptor.attributes}), the fields that are always\n * present, and the fields that may be `null`.\n */\nexport interface PivotDescriptor {\n fields: Readonly<Record<string, string>>\n /**\n * On a response, the fields every member renders; on a request, the fields every member must\n * send. Absent means every field.\n */\n required?: readonly string[]\n /** The fields whose value may be `null`. Absent means none. */\n nullable?: readonly string[]\n /**\n * The members the object takes beside {@link fields}, when the server opens it: each one's\n * wire-format hint (`unknown` for any value) and whether it may be `null`. `false` closes an\n * identifier meta object. Absent closes every other object, and leaves an identifier meta object\n * open, as a server that doesn't say leaves it.\n */\n additional?: AdditionalMembersDescriptor | false\n /**\n * The values a field may take when the server lists them, from its `enum` or `const`: the field\n * is typed as one of these literals, plus `null` when it is nullable, instead of by its hint. A\n * field hinted `array` lists the values of its items, and is typed as a list of them. Absent for\n * a field that takes any value of its hint, and absent altogether in a descriptor generated\n * without it.\n */\n values?: Readonly<Record<string, readonly MetaLiteral[]>>\n}\n\n/** A literal a meta member may take: one of the values its `enum` or `const` lists. */\nexport type MetaLiteral = string | number | boolean\n\n/**\n * The undeclared members an open meta object takes: their wire-format hint, the values they are\n * limited to when the server lists them, or their items are for a hint of `array`, and whether\n * `null`.\n */\nexport interface AdditionalMembersDescriptor {\n format: string\n nullable?: boolean\n values?: readonly MetaLiteral[]\n}\n\n/**\n * The members a document declares in its top-level `meta`, read from the per-operation document\n * component the server marks `x-document-meta`: each member's wire-format hint, the members every\n * such document carries, and the members that may be `null`. A collection's also lists the `page`\n * and `total` the server writes beside them, both optional. The document's `meta` is present\n * whenever a member is required.\n */\nexport type DocumentMetaDescriptor = PivotDescriptor\n\n/** An operation of a type whose document may declare its top-level `meta`. */\nexport type DocumentMetaOperation = 'fetchMany' | 'fetchOne' | 'create' | 'update' | 'delete'\n\n/** A write of a type whose request document may declare its top-level `meta`. */\nexport type RequestMetaOperation = 'create' | 'update' | 'delete'\n\n/**\n * The `meta` of a type's resource objects, read from the components the server marks\n * `x-resource-meta`: `read` what a response renders, `create` and `update` what a write's\n * `data.meta` takes. `atomicCreate` and `atomicUpdate` are the `data.meta` of an `add` or `update`\n * inside an atomic batch, present only when they differ from `create` and `update`.\n */\nexport interface ResourceMetaDescriptor {\n read?: PivotDescriptor\n create?: PivotDescriptor\n update?: PivotDescriptor\n atomicCreate?: PivotDescriptor\n atomicUpdate?: PivotDescriptor\n}\n\nexport interface RelationDescriptor {\n cardinality: Cardinality\n /** Related JSON:API type(s). */\n types: readonly string[]\n /**\n * `true` when the relation is polymorphic: its linkage is a union of identifier types, even a\n * union of one. Read this rather than counting {@link types}, so a\n * relation declared polymorphic over one type keeps its shape when a second type is added. A\n * descriptor without the flag, such as one generated from an older document or written by\n * hand, is polymorphic when it lists more than one type; see {@link isPolymorphic}.\n */\n polymorphic?: boolean\n /** Whether members carry pivot data (`meta.pivot`). */\n pivot?: boolean\n /**\n * The pivot fields carried on each member's `meta.pivot`, as a field-name → wire-format-hint\n * map, typed as always present and never `null` on both reads and writes.\n *\n * @deprecated Describe each side with {@link readPivot} and {@link writePivot}. Read only when\n * those are absent.\n */\n pivotFields?: Readonly<Record<string, string>>\n /** The `meta.pivot` a response renders on each member (`<Type><Rel>Pivot`). */\n readPivot?: PivotDescriptor\n /**\n * `true` when a response renders `meta.pivot` on every member of the relation's linkage, as its\n * response identifiers require `meta` and its `pivot`. A linkage member's `$pivot` and `$edge`\n * are then always present. Absent means a member may come without them. A request never has to\n * send a pivot.\n */\n pivotRendered?: boolean\n /**\n * `true` for a to-many whose linkage every response renders as `data`, as its relationship\n * component requires `data`: a resource read then types its slot as a list of identifiers when\n * the read doesn't include it. Absent means a response may render only the relation's links,\n * so the slot is `undefined` unless the read includes it.\n */\n rendersData?: boolean\n /**\n * The `meta.pivot` a request may send on each member (`<Type><Rel>WritePivot`): a create,\n * update or atomic body, or a relationship mutation. One with no `fields` and no `additional`\n * takes no member, so no write may send a pivot. Absent leaves the pivot a write sends open.\n */\n writePivot?: PivotDescriptor\n /**\n * The members a response renders on each linkage member's `meta` beside any `pivot`\n * (`<Type><Rel>IdentifierMeta`), as the server's identifier meta resolver declares them. Read\n * only: no request carries them, and a related resource object does not render them.\n */\n identifierMeta?: PivotDescriptor\n /**\n * `true` for a relation create and update accept but no response renders. It stays settable\n * on write inputs and is left out of the read view, `fields` and the relationship reads.\n */\n writeOnly?: boolean\n /**\n * `true` when a create must send this relation, as the create request's\n * `relationships.required` lists it. A create input then requires it. Absent means optional,\n * as every relation is on an update.\n */\n requiredOnCreate?: boolean\n /**\n * The writes that refuse `null` for this to-one, as a required relation that is not nullable\n * does: `create`, `update` or both. A write input in one of them takes a reference, never\n * `null`. Absent means every write takes `null`, which clears the relation.\n */\n nonNullOn?: readonly ('create' | 'update')[]\n /**\n * The writes that refuse an empty linkage for this to-many, as a required relation's do, or\n * one bounded by `minItems` of 1 or more: `create`, `update` or both. A write input in one of\n * them takes a non-empty list. A create also takes one for a relation {@link requiredOnCreate}\n * marks. Absent means every write takes `[]`.\n */\n nonEmptyOn?: readonly ('create' | 'update')[]\n /**\n * The relation's segment in its related and relationship paths, when it differs from the\n * relation's name (`/articles/{id}/published-by` for `publisher`). Absent means the name.\n */\n uriField?: string\n /**\n * `false` when the related endpoint (`GET /{type}/{id}/{rel}`) is suppressed for this relation\n * (the bundle's `withoutRelatedEndpoint()`) — `.related()` is then a compile error /\n * runtime guard rather than a 404. Absent means exposed (the default).\n */\n related?: boolean\n /**\n * `false` when the relationship endpoint (`.../relationships/{rel}`) is suppressed for this\n * relation (the bundle's `withoutRelationshipEndpoint()`) — `.get()` (and every\n * mutation) is then gated off. Absent means exposed (the default).\n */\n relationship?: boolean\n /**\n * The per-relation mutation verbs the relationship endpoint advertises. An explicit `{}` means\n * the endpoint exposes no mutation verb (gates every verb OFF). Absent means the descriptor\n * carries no signal (a hand-written descriptor) — gating then falls back to cardinality alone.\n * A codegen descriptor always emits this (at least `{}`) so suppression never fails open.\n */\n mutations?: RelationMutations\n /**\n * The `withCount` count tokens + negotiation profile this relation's related/relationship reads\n * advertise: `_self_` on a to-many, and the relations of the related type it can count. Lets\n * `.related()`/`.get()` send\n * `withCount` and negotiate the right profile; absent when the relation advertises no Countable\n * profile.\n */\n countable?: CountableDescriptor\n /**\n * The paginator this relation's OWN related/relationship endpoints advertise\n * (`GET /{type}/{id}/{rel}` / `.../relationships/{rel}`), when it DIVERGES from the related\n * type's collection-level {@link ResourceDescriptor.paginator}. A related endpoint may paginate\n * differently than the related type's own collection (e.g. a cursor-paginated related to-many\n * whose target type is page-paginated at its top-level collection) — so the client resolves a\n * related/embedded to-many array's `$page.kind` from this per-relation value first, falling back\n * to the related type's collection paginator (D6a). Absent when the two agree (the common case).\n */\n paginator?: PaginatorDescriptor\n /**\n * The types the related endpoint's compound document can carry in `included`, read from the\n * document's typed `included`. Absent when nothing is includable there, or the document types\n * `included` only as `{type, id}`.\n */\n included?: readonly string[]\n /**\n * The sort tokens the relation's own related and relationship reads accept, when the descriptor\n * records them on the relation. The codegen does for a polymorphic relation, whose members\n * share no type to read them from, such as a `MorphToMany` sorting by its pivot fields, and for\n * a relation whose reads sort differently from its related type's collection read, such as by a\n * pivot field or a sort the relation declares. It records `[]` for a relation whose reads take no\n * sort, such as any to-one, and for a relation with no related or relationship read at all.\n * Narrows `sort` on `.get()`, `.related()` and `relatedQuery` as\n * {@link ResourceDescriptor.sortable} narrows a collection read, and `[]` with no\n * {@link sortFamilies} types `sort` as `never`. Absent, together with {@link sortFamilies}, means\n * not recorded: a monomorphic relation's reads then take its related type's collection sorts and\n * a polymorphic relation's take any sort.\n */\n sortable?: readonly string[]\n /** The sort families the relation's reads accept beside {@link sortable}. */\n sortFamilies?: readonly SortFamilyDescriptor[]\n /**\n * The filter keys the relation's own related and relationship reads accept, recorded as\n * {@link sortable} is, and also when the reads drop a filter default. The codegen records `[]`\n * for a relation whose reads take no filter, and for a relation with no read at all. Narrows\n * `filter` on `.get()`, `.related()` and `relatedQuery`, and `[]` with no {@link filterFamilies}\n * types `filter` as `never`. The client matches list filters against it. Absent, together with\n * {@link filterFamilies}, means not recorded: a monomorphic relation's reads then take its related\n * type's collection filters, list filters included, and a polymorphic relation's take any filter.\n */\n filterable?: readonly string[]\n /** The keys of {@link filterable} whose filter takes a list, sent as a collection read sends them. */\n listFilters?: readonly string[]\n /** The filter families the relation's reads accept beside {@link filterable}. */\n filterFamilies?: readonly FilterFamilyDescriptor[]\n /**\n * `true` when the related read takes `relatedQuery`, keyed by the relations of the related\n * type's {@link ResourceDescriptor.relatedQuery}. Only a monomorphic relation's can.\n */\n relatedQuery?: boolean\n /**\n * The top-level `meta` the relation's related read declares: the related type's collection\n * read's members for a to-many, its single read's for a to-one. Absent when it declares none.\n */\n documentMeta?: DocumentMetaDescriptor\n /**\n * The top-level `meta` each relationship write takes, keyed by its verb, read from the request\n * document the server marks `x-request-meta`. A verb that declares none has no entry, and the\n * map is absent when none does.\n */\n requestMeta?: Readonly<Partial<Record<keyof RelationMutations, DocumentMetaDescriptor>>>\n /**\n * The top-level `meta` each operation on the relation takes inside an atomic batch, keyed by its\n * verb like {@link requestMeta}, read from the atomic relationship operation kinds the type has\n * of its own for the relation. A verb that declares none has no entry, and the map is absent\n * when none does.\n */\n atomicRequestMeta?: Readonly<Partial<Record<keyof RelationMutations, DocumentMetaDescriptor>>>\n /**\n * The top-level `meta` of the meta-only `200` each relationship write answers with instead of\n * the linkage, keyed by its verb. A verb answering with the linkage has no entry, and the map is\n * absent when none answers meta-only.\n */\n mutationMeta?: Readonly<Partial<Record<keyof RelationMutations, DocumentMetaDescriptor>>>\n}\n\n/** A built-in pagination strategy. */\nexport type PaginatorStrategy = 'page' | 'offset' | 'cursor' | 'fixed'\n\n/** The strategy that answers a read, or `none` for an unpaginated endpoint. */\nexport type PaginatorKind = PaginatorStrategy | 'none'\n\n/**\n * A role a page parameter fills. `page`: number, size; `offset`: offset, limit; `cursor`: after,\n * before, size; `fixed`: number.\n */\nexport type PaginatorRole = 'number' | 'size' | 'offset' | 'limit' | 'after' | 'before'\n\n/** A strategy whose roles are filled by renamed wire keys, e.g. `{ number: 'p', size: 'size' }`. */\nexport interface StrategyDescriptor {\n strategy: PaginatorStrategy\n keys: Readonly<Partial<Record<PaginatorRole, string>>>\n}\n\n/**\n * A MultiPaginator menu: the client picks an arm by its `kind` (sent as `page[kind]`), and the\n * server answers with `default` when the request names none. Arm keys are the `kind` values.\n */\nexport interface MenuDescriptor {\n strategy: 'multi'\n default: string\n arms: Readonly<Record<string, PaginatorStrategy | StrategyDescriptor>>\n}\n\n/**\n * How an endpoint paginates. A bare kind uses the canonical wire keys (`page[number]`,\n * `page[size]`, ...); a {@link StrategyDescriptor} names renamed keys; a {@link MenuDescriptor}\n * offers several strategies.\n */\nexport type PaginatorDescriptor = PaginatorKind | StrategyDescriptor | MenuDescriptor\n\nexport type ClientIdPolicy = 'forbidden' | 'optional' | 'required'\n\n/** Where a custom action is invoked: collection-scoped (`/{type}/-actions/{name}`) or resource-scoped (`/{type}/{id}/-actions/{name}`). */\nexport type ActionScope = 'collection' | 'resource'\n\n/** The body a custom action accepts: a JSON:API document, no body, or a raw (non-JSON:API) payload. */\nexport type ActionInput = 'document' | 'none' | 'raw'\n\n/**\n * What a custom action returns: a JSON:API document (materialised into the resource view of its\n * {@link ActionDescriptor.outputType}), a meta-only document (its top-level `meta`), only the URL\n * of a location document (see {@link ActionDescriptor.location}), or nothing (a `204`).\n */\nexport type ActionOutput = 'document' | 'meta' | 'location' | 'none'\n\n/**\n * An action that answers with a URL, such as a short-lived download link (generator contract 17).\n * Asked for JSON:API, the server answers `200` with a location document whose `links.location`\n * carries the URL, and the client returns that URL without following it.\n */\nexport interface ActionLocationDescriptor {\n /** The media type the action declares the URL serves, such as `text/csv`. */\n mediaType: string\n}\n\n/**\n * How the client reads or sends a body that is not JSON:API: `binary` as a `Blob` or\n * `ArrayBuffer`, `text` as a `string`, `json` as parsed JSON typed from the media type's schema.\n */\nexport type RawMediaKind = 'binary' | 'text' | 'json'\n\n/**\n * How the client sends one of an action's request media types: a JSON:API `document` (the\n * action's usual document input), a `multipart` `FormData`, a `form` of URL-encoded fields, or a\n * {@link RawMediaKind}.\n */\nexport type InputMediaKind = RawMediaKind | 'document' | 'form' | 'multipart'\n\n/** A media type an action answers with besides JSON:API, and how its body is read. */\nexport interface RawOutputMedia {\n mediaType: string\n kind: RawMediaKind\n}\n\n/** A media type an action accepts as its request body, and how the client sends it. */\nexport interface InputMedia {\n mediaType: string\n kind: InputMediaKind\n}\n\n/**\n * A `202 Accepted` an operation declares: the server may accept the write for later and answer\n * with a job document to poll at its `Content-Location`. `jobType` is the job's JSON:API type, a\n * registered type when the descriptor has an entry for it.\n */\nexport interface AcceptedDescriptor {\n jobType: string\n /** The top-level `meta` the job document declares. Absent when it declares none. */\n meta?: DocumentMetaDescriptor\n}\n\n/**\n * A custom action declared on a type (`#[AsJsonApiAction]`). The runtime reaches it via\n * `client.<type>.actions.<name>(...)` (collection scope) or\n * `client.<type>.id(id).actions.<name>(...)` (resource scope); `input`/`output` drive how the body\n * is sent and the response shaped (see docs/writes.md).\n */\nexport interface ActionDescriptor {\n scope: ActionScope\n /** The action path template (e.g. `/albums/{id}/-actions/reissue`). */\n path: string\n /**\n * The HTTP method the action is invoked over, upper-case (e.g. `PATCH`). Absent means `POST`\n * (the default) — so an action declaring a single non-POST method (`#[AsJsonApiAction(methods:\n * ['PATCH'])]`) stays reachable rather than being silently dropped.\n */\n method?: string\n input: ActionInput\n output: ActionOutput\n /**\n * The JSON:API type of a `document`-input action's body — lets the client accept FLAT input\n * (like `create`) and build the envelope + remap `422` pointers, rather than the caller\n * hand-building `{ data: { type, attributes } }`. Absent for `none`/`raw` inputs, or a bespoke\n * command document whose type isn't a registered resource (then the raw envelope is passed\n * through).\n */\n inputType?: string\n /**\n * The JSON:API type of a `document`-output action's primary resource — the client materialises\n * the response into that type's resource view (matching the read path), so the typed result is\n * `result.title`, not `result.data.attributes.title`. Absent for `meta`/`none` outputs.\n */\n outputType?: string\n /** Whether a `document`-output action returns a single resource (`one`) or a collection (`many`). */\n outputCardinality?: Cardinality\n /**\n * `true` when the action takes `relatedQuery` for the resource it answers with, keyed by the\n * relations of its {@link outputType}'s {@link ResourceDescriptor.relatedQuery}.\n */\n relatedQuery?: boolean\n /**\n * The declared request media type for a `raw`-input action (e.g. `application/octet-stream`),\n * sent verbatim as the `Content-Type` so the server accepts the non-JSON:API body. Absent for\n * `document` (the JSON:API media type) and `none` (no body) inputs.\n */\n contentType?: string\n /**\n * The media types the action can answer with besides JSON:API (generator contract 10), in the\n * document's order. The caller picks one with the `accept` option; without it the client asks\n * for JSON:API when {@link output} is a document or meta, else for the first of these. Absent\n * when the action answers only in JSON:API.\n */\n rawOutput?: readonly RawOutputMedia[]\n /**\n * The media types the action's request body may use, in the document's order, when it lists\n * more than one. The caller picks one with the `contentType` option; without it the client\n * sends JSON:API when listed, else the first of these. Absent for a single media type, which\n * {@link input} and {@link contentType} already describe.\n */\n inputMedia?: readonly InputMedia[]\n /**\n * Whether the action leaves the server's state unchanged, as its operation's `x-safety`\n * declares (generator contract 15). Absent when the server doesn't say.\n */\n readOnly?: boolean\n /** Whether the action may destroy data, as its `x-safety` declares. Absent when not declared. */\n destructive?: boolean\n /**\n * Whether sending the action twice has the same effect as sending it once, as its `x-safety`\n * declares. Absent when the server doesn't say.\n */\n idempotent?: boolean\n /**\n * The OAuth scopes the action needs, read from its operation's `security` (generator contract\n * 16). Absent when it needs none.\n */\n scopes?: readonly string[]\n /**\n * Present when the action answers with a URL in a location document (generator contract 17).\n * With {@link output} `location` that is all it answers with; with `document` or `meta` it\n * answers with either, and the client tells them apart by the document's shape. Absent for an\n * action that answers with a bare `303`, which the transport follows as before.\n */\n location?: ActionLocationDescriptor\n /**\n * The keys a collection action accepts in `filter[...]`, the same filters its type's collection\n * read takes or a subset of them. The client sends them as the read does. Absent when the action\n * takes no filters.\n */\n filterable?: readonly string[]\n /** The keys of {@link filterable} that take a list, sent as the read sends them. */\n listFilters?: readonly string[]\n /** The filter families the action takes, as its type's collection read does. */\n filterFamilies?: readonly FilterFamilyDescriptor[]\n /**\n * Present when the action may answer `202 Accepted` with a job to poll. Absent when it always\n * answers synchronously.\n */\n accepted?: AcceptedDescriptor\n /**\n * The top-level `meta` each success status's document declares, keyed by status (`200`, `201`).\n * Every status answering with a JSON:API document is listed, `null` for one that declares\n * nothing. Absent when none declares any.\n */\n documentMeta?: Readonly<Record<string, DocumentMetaDescriptor | null>>\n /**\n * `true` for a `document` output whose `200` answers with a meta-only document while another\n * status answers with a resource, such as a `201` with the resource the action created. The\n * result is then that `200`'s `meta` or the resource. Absent otherwise.\n */\n metaResult?: boolean\n /**\n * The top-level `meta` the action's request document takes, read from the document the server\n * marks `x-request-meta`. An action with input `none` sends a meta-only document carrying it.\n * Absent when the action declares none.\n */\n requestMeta?: DocumentMetaDescriptor\n}\n\n/**\n * The `withCount` capability of a type's read endpoints (the Countable profile, core ADR\n * 0101). `tokens` are the count tokens a `withCount` query may carry (`_self_` counts the\n * collection itself; a relation name counts that relation per item); `profile` is the URI a\n * client must negotiate (in `Accept`) before the server honours `withCount` — else it is\n * rejected (400) under strict query-param validation. Absent when no read endpoint of the\n * type advertises `withCount`.\n */\nexport interface CountableDescriptor {\n tokens: readonly string[]\n profile: string\n}\n\n/** An operation answering with one resource that may take `withCount`. */\nexport type ResourceCountOperation = 'fetchOne' | 'create' | 'update'\n\n/**\n * An operation of a type that takes `relatedQuery` for the resources it answers with: the\n * collection read, the single-resource read, the create or the update.\n */\nexport type RelatedQueryOperation = 'fetchMany' | 'fetchOne' | 'create' | 'update'\n\n/**\n * The `relatedQuery` parameter for the resources of a type (the Relationship Queries profile): a\n * `filter` and `sort` per relation, applied to that relationship's members. `relations` names the\n * relations it addresses, `operations` names the type's own operations that take it, and\n * `profile` is the URI a client negotiates in `Accept` before the server honours it, read from the\n * parameter's `x-profile`. A related read or an action answering with resources of the type takes\n * the same parameter when its {@link RelationDescriptor.relatedQuery} or\n * {@link ActionDescriptor.relatedQuery} is `true`.\n */\nexport interface RelatedQueryDescriptor {\n operations: readonly RelatedQueryOperation[]\n profile: string\n /**\n * The relations an entry may be keyed by: the type's monomorphic relations a response renders.\n * Absent in a descriptor that doesn't record them, which then takes any such relation.\n */\n relations?: readonly string[]\n}\n\n/**\n * A family of sort keys matched by prefix: any key of the form `<prefix>.<suffix>`, ascending or\n * with a leading `-`, whose suffix matches `suffixPattern` (a regular expression source, unanchored\n * and without delimiters). The server accepts such keys although it can't list them.\n */\nexport interface SortFamilyDescriptor {\n prefix: string\n suffixPattern: string\n}\n\n/**\n * A family of filter keys matched by prefix: any `filter[<prefix>.<suffix>]` whose suffix matches\n * `suffixPattern` (a regular expression source, unanchored and without delimiters). `list` is\n * `true` when its filters take a list, sent as `filter[<prefix>.<suffix>][]` once per member.\n */\nexport interface FilterFamilyDescriptor {\n prefix: string\n suffixPattern: string\n list?: boolean\n}\n\nexport interface ResourceDescriptor {\n /** Attribute name -> wire format hint (drives optional value coercion). */\n attributes: Readonly<Record<string, string>>\n relations: Readonly<Record<string, RelationDescriptor>>\n /** Per-operation path templates, e.g. `{ fetchOne: '/albums/{id}' }`. */\n paths: Readonly<Record<string, string>>\n paginator: PaginatorDescriptor\n clientId: ClientIdPolicy\n /**\n * The attributes a read renders that a create can't supply (the server sets them: read-only on\n * create, or absent from the create document). Absent when every read attribute is creatable, or\n * for a type with no create.\n */\n serverOnly?: readonly string[]\n /** The attributes whose read value may be `null`. Absent when none may be. */\n nullable?: readonly string[]\n /**\n * `true` for a singleton type, which serves each caller one resource at a path with no `{id}`\n * (`/inbox`). Its {@link paths} are those of the single read, the update, and the related and\n * relationship reads, with no collection, create or delete. Absent for any other type.\n */\n singleton?: boolean\n /**\n * The `withCount` count tokens + negotiation profile for this type's read endpoints.\n * Absent when no read endpoint advertises `withCount`.\n */\n countable?: CountableDescriptor\n /**\n * The `withCount` of the operations that answer with one resource, keyed `fetchOne`, `create`\n * or `update`: the relations each can count and the profile it negotiates. An operation that\n * documents no `withCount` has no entry, and the map is absent when none does.\n */\n resourceCountable?: Readonly<Partial<Record<ResourceCountOperation, CountableDescriptor>>>\n /**\n * The `relatedQuery` an operation answering with resources of this type takes, the operations\n * of this type that take it, and the profile it needs. Absent when no operation documents it.\n */\n relatedQuery?: RelatedQueryDescriptor\n /**\n * The relation paths the read endpoints accept in `include` — the exact enum the OpenAPI\n * document advertises, including nested dotted paths (`tracks.album`). Drives `include`\n * narrowing. Absent when the type advertises no includable relations (so `include` is then\n * a compile error, matching the server's `400 INCLUSION_NOT_ALLOWED`).\n */\n includable?: readonly string[]\n /**\n * The types this type's compound documents can carry in `included`: the types its\n * {@link includable} paths reach, read from the document's typed `included`. Absent when nothing\n * is includable, or the document types `included` only as `{type, id}`.\n */\n included?: readonly string[]\n /**\n * The attributes whose single keys a sparse fieldset may select, under the Nested Fieldsets\n * profile: attribute name -> the pattern a key must match (a regular expression source,\n * unanchored and without delimiters), `\\*` for a list whose items take keys. Each adds\n * `<attribute>.${string}` to the members `fields` takes for this type. Absent when no attribute\n * declares a nested fieldset.\n */\n nestedFieldsets?: Readonly<Record<string, string>>\n /**\n * The paths into nested objects a sparse fieldset may select of the attributes in\n * {@link nestedFieldsets}: attribute name -> one entry per path, each the pattern of every key\n * along it after the attribute's own, such as `['geo', '(?:lat|lng)']` for `location.geo.lat`,\n * or `['\\\\*', '(?:sku|qty)']` for `lines.*.sku`, where `\\*` stands for every item of a list.\n * A key that is a plain name is escaped the way the server escapes it. Absent when no nested fieldset\n * key holds an object or a list whose own keys may be selected.\n */\n nestedFieldsetPaths?: Readonly<Record<string, readonly (readonly string[])[]>>\n /**\n * The sort tokens the COLLECTION read accepts in `sort` — signed field names (`title`,\n * `-title`). Drives `sort` narrowing. Absent when the collection advertises no sorting (so\n * `sort` is then a compile error, matching the server's `400 SORTING_UNSUPPORTED`).\n */\n sortable?: readonly string[]\n /**\n * The sort families the COLLECTION read accepts beside {@link sortable}: keys matched by\n * prefix, such as `meta.<name>`. Each adds `<prefix>.${string}` and `-<prefix>.${string}` to the\n * `sort` type. Absent when the collection declares none.\n */\n sortFamilies?: readonly SortFamilyDescriptor[]\n /**\n * The filter keys the COLLECTION read accepts in `filter[...]`. Drives `filter` key narrowing\n * (values stay `unknown` — value shapes/operators vary per filter, out of scope for v0.1).\n * Absent when the collection advertises no filters (so any `filter` is then a compile error,\n * matching the server's `400 FILTERING_UNRECOGNIZED`).\n */\n filterable?: readonly string[]\n /**\n * The keys of {@link filterable} whose filter takes a list. Each is typed `readonly string[]` and\n * sent as `filter[<key>][]` once per member, so a member may contain a comma. Absent when no\n * filter takes a list.\n */\n listFilters?: readonly string[]\n /**\n * The filter families the COLLECTION read accepts beside {@link filterable}: keys matched by\n * prefix, such as `value.<name>`. Each adds `<prefix>.${string}` to the `filter` type. Absent\n * when the collection declares none.\n */\n filterFamilies?: readonly FilterFamilyDescriptor[]\n /** Custom actions declared on this type, keyed by action name. Absent/empty when none. */\n actions?: Readonly<Record<string, ActionDescriptor>>\n /**\n * The OAuth scopes each of the type's operations needs, read from the operation's `security`\n * (generator contract 16). Keyed like {@link ResourceExamples.operations}: `fetchCollection`,\n * `fetchOne`, `create`, `update`, `delete`, and per relation `fetchRelated.<relation>`,\n * `fetchRelationship.<relation>`, `updateRelationship.<relation>`,\n * `addRelationship.<relation>` and `removeRelationship.<relation>`. An operation that needs\n * no scope has no entry, and the map is absent when none does. An action's scopes are on its\n * {@link ActionDescriptor.scopes}.\n */\n scopes?: Readonly<Record<string, readonly string[]>>\n /**\n * The writes that may answer `202 Accepted` with a job to poll, keyed `create` or `update`. A\n * delete never does. Absent when every write answers synchronously; an action's is on its\n * {@link ActionDescriptor.accepted}.\n */\n accepted?: Readonly<Partial<Record<AcceptedOperation, AcceptedDescriptor>>>\n /**\n * The top-level `meta` each of the type's operations declares, keyed `fetchMany`, `fetchOne`,\n * `create`, `update` or `delete`. A delete's applies to its meta-only `200`. An operation that\n * declares none has no entry, and the map is absent when none does. A relation's related read\n * has its own on {@link RelationDescriptor.documentMeta}, an action's on\n * {@link ActionDescriptor.documentMeta}.\n */\n documentMeta?: Readonly<Partial<Record<DocumentMetaOperation, DocumentMetaDescriptor>>>\n /**\n * The top-level `meta` each of the type's writes takes, keyed `create`, `update` or `delete`,\n * read from the request document the server marks `x-request-meta`. A delete declaring it takes\n * a meta-only request document. A write that declares none has no entry, and the map is absent\n * when none does.\n */\n requestMeta?: Readonly<Partial<Record<RequestMetaOperation, DocumentMetaDescriptor>>>\n /**\n * The top-level `meta` each of the type's operations takes inside an atomic batch, keyed like\n * {@link requestMeta}, read from the atomic operation kinds the type has of its own.\n */\n atomicRequestMeta?: Readonly<Partial<Record<RequestMetaOperation, DocumentMetaDescriptor>>>\n /** The `meta` of the type's resource objects, as a read renders it and a write sends it. */\n resourceMeta?: ResourceMetaDescriptor\n}\n\n/** A write that can answer `202 Accepted`. */\nexport type AcceptedOperation = 'create' | 'update'\n\nexport type ApiDescriptor = Readonly<Record<string, ResourceDescriptor>>\n\n/**\n * Whether a relation is polymorphic: flagged {@link RelationDescriptor.polymorphic}, or, when the\n * flag is absent, listing more than one related type.\n */\nexport function isPolymorphic(\n relation: Pick<RelationDescriptor, 'polymorphic' | 'types'>,\n): boolean {\n return relation.polymorphic ?? relation.types.length > 1\n}\n\n/**\n * The server-level Atomic Operations capability: the single `/operations`\n * endpoint, detected when its requestBody uses the atomic ext media type. `null` when the\n * server exposes no atomic endpoint. Carried alongside the per-type descriptor (not inside\n * it — atomic is server-level, not per-type) so the runtime `client.atomic` builder can\n * reach the path.\n */\nexport interface AtomicDescriptor {\n path: string\n /** The OAuth scopes the endpoint itself needs (generator contract 16). Absent when none. */\n scopes?: readonly string[]\n}\n\n/** Example bodies keyed by the media type they are declared for, such as `application/vnd.api+json`. */\nexport type MediaExamples = Readonly<Record<string, unknown>>\n\n/**\n * The worked examples one operation declares (generator contract 12): its request body, and its\n * success responses keyed by status code. Each body is the whole wire document, not the flat input\n * or materialised result the client works with. A part the document gives no example for is absent.\n */\nexport interface OperationExamples {\n request?: MediaExamples\n responses?: Readonly<Record<string, MediaExamples>>\n}\n\n/**\n * The examples of one type's operations. `operations` is keyed by the operation's name in core's\n * terms, its `operationId` without the type: `fetchCollection`, `fetchOne`, `create`, `update`,\n * `delete`, and per relation `fetchRelated.<relation>`, `fetchRelationship.<relation>`,\n * `updateRelationship.<relation>`, `addRelationship.<relation>` and\n * `removeRelationship.<relation>`. `actions` is keyed by action name, as\n * {@link ResourceDescriptor.actions} is.\n */\nexport interface ResourceExamples {\n operations?: Readonly<Record<string, OperationExamples>>\n actions?: Readonly<Record<string, OperationExamples>>\n}\n\n/** The operation examples of every type that has one, keyed by wire type. */\nexport type ApiExamples = Readonly<Record<string, ResourceExamples>>\n","import type { FilterFamilyDescriptor } from './descriptor'\n\n/** The filter vocabulary {@link listFilterMatcher} reads: a type's, or a collection action's. */\nexport interface FilterSpec {\n filterable?: readonly string[]\n listFilters?: readonly string[]\n filterFamilies?: readonly FilterFamilyDescriptor[]\n}\n\n/**\n * Whether a `filter[...]` key takes a list, by the rule the server matches keys with: an exact\n * key first, then the filter family with the longest prefix whose suffix pattern accepts the rest\n * of the key. A family never matches its bare prefix. `undefined` when nothing in `spec` takes a\n * list, so every filter value is sent as before.\n */\nexport function listFilterMatcher(\n spec: FilterSpec | undefined,\n): ((key: string) => boolean) | undefined {\n const lists = new Set(spec?.listFilters ?? [])\n const families = (spec?.filterFamilies ?? []).filter((family) => family.list === true)\n if (lists.size === 0 && families.length === 0) {\n return undefined\n }\n const exact = new Set(spec?.filterable ?? [])\n // oxlint-disable-next-line no-array-sort -- sorting a freshly-copied array\n const byLength = [...(spec?.filterFamilies ?? [])].sort(\n (a, b) => b.prefix.length - a.prefix.length,\n )\n return (key) => {\n if (lists.has(key)) {\n return true\n }\n if (exact.has(key)) {\n return false\n }\n for (const family of byLength) {\n const prefix = `${family.prefix}.`\n if (!key.startsWith(prefix)) {\n continue\n }\n const suffix = key.slice(prefix.length)\n if (suffix !== '' && new RegExp(`^(?:${family.suffixPattern})$`, 'u').test(suffix)) {\n return family.list === true\n }\n }\n return false\n }\n}\n","import type { ActionLocationDescriptor } from './descriptor'\nimport type { Document } from './request'\n\n/**\n * The URL an action answered with (generator contract 17), read from its location document. The\n * client never fetches it: a presigned storage URL is for the browser or the caller to open.\n */\nexport interface ActionLocation {\n /** The URL, from `links.location.href`. */\n url: string\n /**\n * The media type the URL serves: the link's `type`, else the one the action declares. A server\n * may name another type for one response, such as a file whose type varies.\n */\n type: string\n /** When the URL stops working, as the server's ISO 8601 string. Absent when it doesn't expire. */\n expiresAt?: string\n}\n\n/**\n * Whether a value is an {@link ActionLocation}, for an action that answers with either a resource\n * or a URL. A materialised resource always has an `id`, which a location never has.\n */\nexport function isActionLocation(value: unknown): value is ActionLocation {\n if (typeof value !== 'object' || value === null || Array.isArray(value) || 'id' in value) {\n return false\n }\n const record = value as Record<string, unknown>\n return typeof record['url'] === 'string' && typeof record['type'] === 'string'\n}\n\n/** A link's `href` and the object it came from, whether written as a string or a link object. */\nfunction linkObject(link: unknown): { href: string; link: Record<string, unknown> } | undefined {\n if (typeof link === 'string') {\n return { href: link, link: {} }\n }\n if (typeof link === 'object' && link !== null && !Array.isArray(link)) {\n const object = link as Record<string, unknown>\n return typeof object['href'] === 'string' ? { href: object['href'], link: object } : undefined\n }\n return undefined\n}\n\n/**\n * The URL a location document carries, or `undefined` when the document is something else, such\n * as a resource document from an action that answers with either.\n */\nexport function readActionLocation(\n doc: Document,\n declared: ActionLocationDescriptor,\n): ActionLocation | undefined {\n if (doc.data !== undefined) {\n return undefined\n }\n const location = linkObject(doc.links?.['location'])\n if (location === undefined) {\n return undefined\n }\n const out: ActionLocation = {\n url: location.href,\n type: typeof location.link['type'] === 'string' ? location.link['type'] : declared.mediaType,\n }\n const meta = location.link['meta']\n const linkExpiry =\n typeof meta === 'object' && meta !== null\n ? (meta as Record<string, unknown>)['expiresAt']\n : undefined\n const expiresAt = linkExpiry ?? doc.meta?.['expiresAt']\n if (typeof expiresAt === 'string') {\n out.expiresAt = expiresAt\n }\n return out\n}\n","/**\n * A request body that is not text: the binary, multipart and URL-encoded payloads a custom action\n * can take.\n */\nexport type TransportRawBody =\n | Blob\n | ArrayBuffer\n | Uint8Array<ArrayBuffer>\n | FormData\n | URLSearchParams\n\n/** A single outbound request, already serialised. */\nexport interface TransportRequest {\n method: string\n url: string\n headers: Record<string, string>\n body?: string\n /**\n * A body that is not text, sent instead of {@link body}. Only a custom action with a binary,\n * multipart or URL-encoded request media type sets it, and a custom transport must send it as\n * is for those actions to work.\n */\n rawBody?: TransportRawBody\n /**\n * Read a successful response as binary into {@link TransportResponse.binary}. Absent means text,\n * which is every JSON:API response. Only a custom action answering with a binary media type\n * sets it; an error response is still read as text so the client can parse its JSON:API errors.\n */\n responseType?: 'blob' | 'arraybuffer'\n /**\n * Aborts the request when signalled. Optional: a transport that ignores it still works, the\n * caller just can't cancel an in-flight request through it.\n */\n signal?: AbortSignal\n}\n\n/** A single inbound response, body still a string for the runtime to parse. */\nexport interface TransportResponse {\n status: number\n headers: Record<string, string>\n /** The response body as text; empty when it was read into {@link binary} instead. */\n body: string\n /** The body of a successful response to a request that set `responseType`. */\n binary?: Blob | ArrayBuffer\n}\n\n/**\n * The transport seam: a tiny, `fetch`-shaped function (not a class), so any impl\n * (native `fetch`, undici, an axios adapter) drops in. Retries are deliberately out\n * of scope here — the transport (or the TanStack layer) owns them.\n */\nexport type JsonApiTransport = (req: TransportRequest) => Promise<TransportResponse>\n\n/** The default transport, backed by the global `fetch`. */\nexport const fetchTransport: JsonApiTransport = async (req) => {\n const init: RequestInit = { method: req.method, headers: req.headers }\n if (req.rawBody !== undefined) {\n init.body = req.rawBody\n } else if (req.body !== undefined) {\n init.body = req.body\n }\n if (req.signal !== undefined) {\n init.signal = req.signal\n }\n\n const res = await fetch(req.url, init)\n\n const headers: Record<string, string> = {}\n res.headers.forEach((value, key) => {\n headers[key] = value\n })\n\n if (req.responseType !== undefined && res.ok) {\n const binary = req.responseType === 'blob' ? await res.blob() : await res.arrayBuffer()\n return { status: res.status, headers, body: '', binary }\n }\n return { status: res.status, headers, body: await res.text() }\n}\n","import { type PollOptions, toAccepted } from './accepted'\nimport { type AtomicRecorder, runAtomic } from './atomic'\nimport {\n type AcceptedDescriptor,\n type ActionDescriptor,\n type ActionScope,\n type ApiDescriptor,\n type AtomicDescriptor,\n type InputMediaKind,\n isPolymorphic,\n type ResourceCountOperation,\n} from './descriptor'\nimport { JsonApiError } from './errors'\nimport { type FilterSpec, listFilterMatcher } from './filters'\nimport { fieldsOfUrl } from './nested-fieldset'\nimport { readActionLocation } from './location'\nimport { materialise, type MaterialiseContext, relatedPaginator } from './materialise'\nimport { stampFromDocument } from './request-stamp'\nimport { resolvePaginator } from './pagination'\nimport {\n type Document,\n execute,\n executeRaw,\n type ExecutedResponse,\n executeResponse,\n type JsonApiContext,\n type JsonApiRequest,\n type ReadQuery,\n} from './request'\nimport type {\n ActionCallOptions,\n ActionsAccessor,\n Client,\n DefaultActionTypes,\n DefaultAttributes,\n DefaultWriteAttributes,\n RelationReadQuery,\n RelationshipAccessor,\n ResourceHandle,\n SingletonAccessor,\n TypeAccessor,\n} from './result-types'\nimport {\n toDocument,\n toRelationshipDocument,\n withTopLevelMeta,\n withRemappedDocumentMetaPaths,\n withRemappedPaths,\n withRemappedRelationshipPaths,\n} from './serialize-write'\nimport { fetchTransport, type JsonApiTransport } from './transport'\nimport { JSON_API_MEDIA_TYPE } from './types'\nimport { resolveValidator, type ValidationOption } from './validate'\nimport { type InputSchemas, withInputCheck } from './input-validation'\n\n/**\n * The `fetch` headers init type. `@types/node` declares the global `RequestInit` (used\n * by the transport) but not `HeadersInit`; we derive it from `RequestInit.headers` to\n * stay dep-free and consistent with the rest of the runtime's web-globals usage.\n */\nexport type HeadersInit = NonNullable<RequestInit['headers']>\n\n/** Options for {@link createClient}. */\nexport interface ClientOptions {\n /** Base URL the generated path templates are resolved against. */\n baseUrl: string\n /** Transport seam; defaults to the `fetch` adapter when omitted. */\n transport?: JsonApiTransport\n /** Per-request header provider (e.g. bearer auth); may be async. */\n headers?: () => HeadersInit | Promise<HeadersInit>\n /**\n * Follow a server link (`$next()`, `$prev()`) that leaves `baseUrl`'s origin. Off by default, so\n * such a link rejects without sending a request. When on, the request goes out without\n * {@link headers}.\n */\n allowCrossOriginLinks?: boolean\n /**\n * The server-level Atomic Operations capability (the codegen's `atomic` constant): `{ path }`\n * when the server exposes the atomic endpoint, else `null`/omitted. When present, the client\n * exposes `client.atomic(tx => …)`; otherwise calling it throws.\n */\n atomic?: AtomicDescriptor | null\n /**\n * The opt-in per-field validation seam. Off by default — the client always runs\n * light structural guards (is this a JSON:API document? does each `data`/`included` member\n * carry `type`+`id`?) but otherwise trusts the wire. Supply either the schema-driven config\n * `{ schemas, validator }` — the codegen-emitted per-type `schemas` map plus a validation\n * engine adapter (each wire resource is validated against `schemas[type]`; a type with no\n * schema is skipped) — or a bare validator function that owns schema lookup itself. The\n * validation engine (e.g. ajv) is brought by the caller; the client never depends on one.\n */\n validate?: ValidationOption\n /**\n * Schemas to check each create's and update's input against before sending it, by wire type.\n * An input that fails rejects with an {@link InputValidationError} and sends nothing. Pass the\n * `inputSchemas` that `json-api-codegen --zod` generates, or your own Standard Schemas.\n */\n validateInput?: InputSchemas\n}\n\n/** The ambient runtime context every read shares: transport seam + descriptor + materialise glue. */\ninterface ClientContext {\n readonly request: JsonApiContext\n readonly materialise: MaterialiseContext\n readonly descriptor: ApiDescriptor\n readonly inputSchemas?: InputSchemas\n}\n\n/** Substitute `{key}` placeholders in a path template (`/albums/{id}/{rel}` -> `/albums/1/tracks`). */\nconst fill = (template: string, vars: Record<string, string>): string =>\n template.replace(/\\{(\\w+)\\}/g, (_, key: string) => vars[key] ?? `{${key}}`)\n\n/**\n * Fill a type's path template, putting a relation's URI segment (its `uriField`, else its name)\n * in place of `{rel}`. `vars.rel` stays the relation's name everywhere else.\n */\nfunction fillPath(\n ctx: ClientContext,\n type: string,\n template: string,\n vars: Record<string, string>,\n): string {\n const rel = vars['rel']\n const uriField = rel === undefined ? undefined : ctx.descriptor[type]?.relations[rel]?.uriField\n return fill(template, uriField === undefined ? vars : { ...vars, rel: uriField })\n}\n\n/**\n * Run an operation: resolve the path template from the type's descriptor, fill its\n * placeholders, execute, and materialise the resulting document. A no-body / 204 response\n * materialises to `undefined`; an operation the type does not declare (no path template) throws\n * a local `Error` before any request. `linkage` marks a relationship-endpoint read (primary\n * `data` is pure resource-identifier linkage) so an attribute-less, relation-less member is\n * still materialised as an identifier.\n */\nasync function run(\n ctx: ClientContext,\n type: string,\n operation: string,\n vars: Record<string, string>,\n query: ReadQuery | undefined,\n linkage = false,\n relationForCount?: string,\n): Promise<unknown> {\n const template = ctx.descriptor[type]?.paths[operation]\n if (template === undefined) {\n throw new Error(`No \"${operation}\" path declared for type \"${type}\"`)\n }\n const req: JsonApiRequest = { method: 'GET', path: fillPath(ctx, type, template, vars) }\n if (query !== undefined) {\n const { signal, ...params } = query\n req.query = params\n const listFilter = listFilterMatcher(filterSpec(ctx, type, operation, vars['rel']))\n if (listFilter !== undefined) {\n req.listFilter = listFilter\n }\n if (signal !== undefined) {\n req.signal = signal\n }\n negotiateProfiles(ctx, type, params, req, relationForCount, operation)\n applyRelatedQuery(ctx, renderedType(ctx, type, operation, vars['rel']), params, req)\n }\n const doc = await execute(ctx.request, req)\n // Resolve the strategy that answers from the endpoint's paginator and the `page` sent, so an\n // EMPTY page still reports the real `$page.kind` and a menu read reports the arm it picked.\n // A related/relationship read uses the RELATION's paginator, which may diverge from the related\n // type's collection (D6a).\n const relation =\n (operation === 'fetchRelated' || operation === 'fetchRelationship') && vars['rel'] !== undefined\n ? ctx.descriptor[type]?.relations[vars['rel']]\n : undefined\n const paginator =\n operation === 'fetchMany'\n ? ctx.descriptor[type]?.paginator\n : relation !== undefined\n ? relatedPaginator(relation, ctx.materialise)\n : undefined\n const primaryType = operation === 'fetchMany' ? type : undefined\n const paginatorOverride =\n paginator === undefined ? undefined : resolvePaginator(paginator, query?.page)\n return doc === undefined\n ? undefined\n : materialise(\n doc,\n withFields(ctx.materialise, query?.fields),\n linkage,\n primaryType,\n paginatorOverride,\n )\n}\n\n/** The materialise context for a response to a request that sent `fields`. */\nfunction withFields(\n ctx: MaterialiseContext,\n fields: Readonly<Record<string, readonly string[]>> | undefined,\n): MaterialiseContext {\n return fields === undefined ? ctx : { ...ctx, fields }\n}\n\n/**\n * The filter vocabulary a read's `filter` is matched against: the type's for its collection read.\n * A related or relationship read takes the relation's own when its descriptor declares one, even an\n * empty one, else the related type's when the relation has one related type.\n */\nfunction filterSpec(\n ctx: ClientContext,\n type: string,\n operation: string,\n rel: string | undefined,\n): FilterSpec | undefined {\n if (operation === 'fetchMany') {\n return ctx.descriptor[type]\n }\n const relation = rel === undefined ? undefined : ctx.descriptor[type]?.relations[rel]\n if (relation?.filterable !== undefined || relation?.filterFamilies !== undefined) {\n return relation\n }\n const types = relation?.types\n return types?.length === 1 ? ctx.descriptor[types[0]!] : undefined\n}\n\n/**\n * The type whose resources an operation answers with, which keys its `relatedQuery`: the type\n * itself, or a related read's related type when the relation is monomorphic. A relationship read\n * answers with linkage, so it has none.\n */\nfunction renderedType(\n ctx: ClientContext,\n type: string,\n operation: string,\n rel: string | undefined,\n): string | undefined {\n if (operation === 'fetchRelationship') {\n return undefined\n }\n if (operation !== 'fetchRelated') {\n return type\n }\n const relation = rel === undefined ? undefined : ctx.descriptor[type]?.relations[rel]\n return relation === undefined || isPolymorphic(relation) ? undefined : relation.types[0]\n}\n\n/** Whether a `relatedQuery` carries a filter or sort for any relation, so it reaches the wire. */\nfunction sendsRelatedQuery(relatedQuery: ReadQuery['relatedQuery']): boolean {\n return Object.values(relatedQuery ?? {}).some(\n (entry) =>\n Object.keys(entry?.filter ?? {}).length > 0 ||\n (entry?.sort !== undefined && entry.sort.length > 0),\n )\n}\n\n/**\n * Prepare a request's `relatedQuery` for resources of type `rendered`: match each entry's list\n * filters against its relation's related-read vocabulary, and negotiate the type's Relationship\n * Queries profile, after any Countable one, when the query sends an entry.\n */\nfunction applyRelatedQuery(\n ctx: ClientContext,\n rendered: string | undefined,\n query: ReadQuery,\n req: JsonApiRequest,\n): void {\n if (rendered === undefined || !sendsRelatedQuery(query.relatedQuery)) {\n return\n }\n const matchers = new Map<string, ((key: string) => boolean) | undefined>()\n req.relatedListFilter = (rel, key) => {\n if (!matchers.has(rel)) {\n matchers.set(rel, listFilterMatcher(filterSpec(ctx, rendered, 'fetchRelated', rel)))\n }\n return matchers.get(rel)?.(key) ?? false\n }\n const profile = ctx.descriptor[rendered]?.relatedQuery?.profile\n if (profile !== undefined && !(req.profiles ?? []).includes(profile)) {\n req.profiles = [...(req.profiles ?? []), profile]\n }\n}\n\n/**\n * Add the Countable profile a query's `withCount` requires to the request's negotiated\n * `profiles`. A `withCount` read or write needs it in `Accept`, else the server rejects it (400)\n * under strict query-param validation. The profile URI is read from the descriptor (never\n * hardcoded): the relation's `countable` for a related or relationship read, the operation's\n * `resourceCountable` entry for a single-resource read or a write, else the type's `countable`.\n */\nfunction negotiateProfiles(\n ctx: ClientContext,\n type: string,\n query: ReadQuery,\n req: JsonApiRequest,\n relationForCount?: string,\n operation?: string,\n): void {\n const profiles: string[] = []\n if (query.withCount !== undefined && query.withCount.length > 0) {\n const descriptor = ctx.descriptor[type]\n const profile =\n relationForCount !== undefined\n ? descriptor?.relations[relationForCount]?.countable?.profile\n : ((isResourceCountOperation(operation)\n ? descriptor?.resourceCountable?.[operation]?.profile\n : undefined) ?? descriptor?.countable?.profile)\n if (profile !== undefined) {\n profiles.push(profile)\n }\n }\n if (profiles.length > 0) {\n req.profiles = [...(req.profiles ?? []), ...profiles]\n }\n}\n\n/** Whether an operation is one answering with one resource that may take `withCount`. */\nfunction isResourceCountOperation(\n operation: string | undefined,\n): operation is ResourceCountOperation {\n return operation === 'fetchOne' || operation === 'create' || operation === 'update'\n}\n\n/**\n * A write opts object: an optional `include`/`fields` narrowing the materialised response, the\n * relations to count, a `relatedQuery` for its relationships, and `wait` to poll a\n * `202 Accepted` job until it's done.\n */\ninterface WriteOpts {\n include?: readonly string[]\n fields?: Record<string, readonly string[]>\n withCount?: readonly string[]\n relatedQuery?: ReadQuery['relatedQuery']\n wait?: boolean | PollOptions\n /** The request document's top-level `meta`. */\n meta?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Project a write's opts to the read-query families the response honours: `include`, `fields`,\n * `withCount` and `relatedQuery`.\n */\nfunction writeQuery(opts: WriteOpts | undefined): ReadQuery | undefined {\n if (opts === undefined) {\n return undefined\n }\n const query: ReadQuery = {}\n if (opts.include !== undefined) {\n query.include = [...opts.include]\n }\n if (opts.withCount !== undefined) {\n query.withCount = [...opts.withCount]\n }\n if (opts.relatedQuery !== undefined) {\n query.relatedQuery = opts.relatedQuery\n }\n if (opts.fields !== undefined) {\n const fields: Record<string, string[]> = {}\n for (const [k, v] of Object.entries(opts.fields)) {\n fields[k] = [...v]\n }\n query.fields = fields\n }\n return Object.keys(query).length > 0 ? query : undefined\n}\n\n/** A write's spec: how to address it, what to send, and how to shape the result + errors. */\ninterface WriteSpec {\n type: string\n operation: string\n vars: Record<string, string>\n method: string\n body: unknown\n query?: ReadQuery | undefined\n /** Materialise the primary `data` as identifier linkage (relationship endpoints) vs resources. */\n linkage?: boolean\n /** Remap a thrown error's pointers to flat input paths (resource-write vs relationship-write). */\n remap: (error: JsonApiError) => JsonApiError\n /** The `202 Accepted` the write declares, if any. */\n accepted?: AcceptedDescriptor | undefined\n /** Poll an accepted job until it's done, with these options. */\n wait?: PollOptions | undefined\n /** Resolve a meta-only document to its top-level `meta`, as a delete declaring it does. */\n metaOnly?: boolean\n}\n\n/** The poll options a call's `wait` asks for, or `undefined` when it doesn't wait. */\nconst waitOptions = (wait: boolean | PollOptions | undefined): PollOptions | undefined =>\n wait === true ? {} : wait === false ? undefined : wait\n\n/**\n * Answer a `202` the operation declares with an `Accepted`, or with its result when the caller\n * waits. The job is materialised, or is the top-level `meta` of a meta-only document; `complete`\n * shapes the document the job URL finally answers with, as the operation shapes its own.\n */\nfunction answerAccepted(\n ctx: ClientContext,\n accepted: AcceptedDescriptor,\n res: ExecutedResponse,\n complete: (doc: Document | undefined) => unknown,\n wait: PollOptions | undefined,\n): unknown {\n const value = toAccepted(\n {\n request: ctx.request,\n jobType: accepted.jobType,\n job: (doc) =>\n doc === undefined || !('data' in doc)\n ? (doc?.meta ?? {})\n : materialise(doc, ctx.materialise),\n complete,\n },\n res,\n )\n return wait === undefined ? value : value.$poll(wait)\n}\n\n/**\n * Drive a write: fill the path template, attach the body (and any `include`/`fields` query),\n * execute, and materialise the response (`undefined` for a `204`/no body — so create/update\n * return the resource and delete/`204` relationship mutations resolve `undefined`/`void`). A\n * `202` the write declares resolves to an `Accepted` job, or with `wait` to the polled result.\n * On a thrown {@link JsonApiError}, each error's flat `path` is populated (via `spec.remap`)\n * before it propagates, so a caller's `byPath()` keys are the flat input shape.\n */\nasync function runWrite(ctx: ClientContext, spec: WriteSpec): Promise<unknown> {\n const template = ctx.descriptor[spec.type]?.paths[spec.operation]\n if (template === undefined) {\n throw new Error(`No \"${spec.operation}\" path declared for type \"${spec.type}\"`)\n }\n const req: JsonApiRequest = {\n method: spec.method,\n path: fillPath(ctx, spec.type, template, spec.vars),\n body: spec.body,\n }\n if (spec.query !== undefined) {\n req.query = spec.query\n negotiateProfiles(ctx, spec.type, spec.query, req, undefined, spec.operation)\n applyRelatedQuery(ctx, spec.type, spec.query, req)\n if (req.profiles !== undefined) {\n // The profiles shape the response, not the body, so only `Accept` names them.\n req.contentType = JSON_API_MEDIA_TYPE\n }\n }\n if (spec.wait?.signal !== undefined) {\n req.signal = spec.wait.signal\n }\n let res\n try {\n res = await executeResponse(ctx.request, req)\n } catch (error) {\n if (error instanceof JsonApiError) {\n throw spec.remap(error)\n }\n throw error\n }\n // A meta-only result is not materialised, so it takes the document's stamp here.\n const complete = (doc: Document | undefined) =>\n stampFromDocument(\n doc,\n doc === undefined\n ? undefined\n : spec.metaOnly === true && !('data' in doc)\n ? doc.meta\n : materialise(\n doc,\n withFields(ctx.materialise, spec.query?.fields),\n spec.linkage ?? false,\n ),\n )\n if (res.status === 202 && spec.accepted !== undefined) {\n return answerAccepted(ctx, spec.accepted, res, complete, spec.wait)\n }\n return complete(res.document)\n}\n\n/**\n * Invoke a custom action over its declared HTTP method (`action.method`, default `POST`) at its\n * (filled) path, with a body shaped by the action's `input` mode:\n *\n * - `none` — no body;\n * - `document` — when the action names an `inputType`, FLAT input (the resource's attributes /\n * relationships) is built into the JSON:API envelope like `create`, and a `422`'s\n * `source.pointer`s are remapped to the flat paths; a bespoke command document (no `inputType`)\n * is sent verbatim;\n * - `raw` — the caller's payload, sent with the action's declared media type (e.g.\n * `application/octet-stream`), falling back to a wildcard when the spec declared none.\n *\n * An action listing several request media types (`inputMedia`) sends the one the caller picks\n * with `options.contentType`, or JSON:API when listed, else the first.\n *\n * The response is shaped by the action's `output`: `document` materialises into the resource /\n * collection view, `meta` returns the document's top-level `meta`, `none` resolves `undefined` (a\n * `204` / no body). A `metaResult` action returns the top-level `meta` of a document with no\n * `data`. An action declaring a `location` returns the URL of a location document as an\n * `ActionLocation` and never follows it. An action declaring `rawOutput` answers in the media type\n * the caller picks with `options.accept`: JSON:API as above, or a `string`, a `Blob` or\n * `ArrayBuffer`, or parsed JSON by the media type's kind. A collection action that takes filters\n * sends `options.filter` in the query string as a collection read does, and an action answering\n * with a resource sends `options.relatedQuery` as a read does. A `202` the action\n * declares resolves to an `Accepted` job, or with `options.wait` to the value its job URL ends at.\n */\nasync function runAction(\n ctx: ClientContext,\n action: ActionDescriptor,\n vars: Record<string, string>,\n input: unknown,\n options: ActionCallOptions = {},\n): Promise<unknown> {\n const req: JsonApiRequest = { method: action.method ?? 'POST', path: fill(action.path, vars) }\n if (options.signal !== undefined) {\n req.signal = options.signal\n }\n if (options.filter !== undefined) {\n req.query = { filter: options.filter }\n const listFilter = listFilterMatcher(action)\n if (listFilter !== undefined) {\n req.listFilter = listFilter\n }\n }\n if (options.relatedQuery !== undefined) {\n req.query = { ...req.query, relatedQuery: options.relatedQuery }\n applyRelatedQuery(ctx, action.outputType, req.query, req)\n }\n let remap: ((error: JsonApiError) => JsonApiError) | undefined\n const media = requestMedia(action, options.contentType)\n if (media !== undefined && media.kind !== 'document') {\n req.body = encodeFields(media.mediaType, media.kind, input)\n req.raw = true\n req.contentType = sentContentType(media.mediaType, media.kind, req.body)\n } else if (action.input === 'document') {\n if (action.inputType !== undefined) {\n // Flat input: build the envelope like create, and remap 422 pointers to the flat paths.\n const inputType = action.inputType\n req.body = withTopLevelMeta(\n toDocument(ctx.descriptor, inputType, (input ?? {}) as Record<string, unknown>),\n options.meta,\n )\n remap = (error) => withRemappedPaths(error, ctx.descriptor, inputType)\n } else {\n // A bespoke command document (no resolvable input type): pass the caller's envelope through.\n req.body =\n typeof input === 'object' && input !== null ? withTopLevelMeta(input, options.meta) : input\n remap = withRemappedDocumentMetaPaths\n }\n } else if (action.input === 'none' && options.meta !== undefined) {\n // An action taking no document may still declare its request `meta`, sent meta-only.\n req.body = { meta: options.meta }\n req.contentType = JSON_API_MEDIA_TYPE\n remap = withRemappedDocumentMetaPaths\n } else if (action.input === 'raw') {\n req.body = encodeFields(action.contentType ?? '*/*', undefined, input)\n // Send the action's declared media type (e.g. application/octet-stream); fall back to a\n // wildcard only when the spec declared none.\n req.contentType = sentContentType(action.contentType ?? '*/*', undefined, req.body)\n req.raw = true\n }\n if (req.profiles !== undefined && req.contentType === undefined) {\n // The Relationship Queries profile shapes the response, so only `Accept` names it.\n req.contentType = JSON_API_MEDIA_TYPE\n }\n\n const raw = responseMedia(action, options.accept)\n try {\n if (raw !== undefined) {\n req.accept = raw.mediaType\n if (raw.kind === 'binary') {\n return await executeRaw(\n ctx.request,\n req,\n options.responseType === 'arrayBuffer' ? 'arraybuffer' : 'blob',\n )\n }\n const text = await executeRaw(ctx.request, req, 'text')\n return raw.kind === 'json' && text !== undefined ? (JSON.parse(text) as unknown) : text\n }\n const res = await executeResponse(ctx.request, req)\n const complete = (doc: Document | undefined) =>\n stampFromDocument(doc, actionValue(ctx, action, doc))\n if (res.status === 202 && action.accepted !== undefined) {\n const wait = waitOptions(options.wait)\n const signal = wait?.signal ?? options.signal\n return answerAccepted(\n ctx,\n action.accepted,\n res,\n complete,\n wait === undefined || signal === undefined ? wait : { ...wait, signal },\n )\n }\n return complete(res.document)\n } catch (error) {\n if (remap !== undefined && error instanceof JsonApiError) {\n throw remap(error)\n }\n throw error\n }\n}\n\n/** Shape an action's JSON:API answer by its declared `output`, or its `location`. */\nfunction actionValue(\n ctx: ClientContext,\n action: ActionDescriptor,\n doc: Document | undefined,\n): unknown {\n if (action.location !== undefined) {\n const location = doc === undefined ? undefined : readActionLocation(doc, action.location)\n if (location !== undefined) {\n return location\n }\n if (action.output === 'location') {\n throw new Error('The action answered without the location document it declares.')\n }\n }\n if (action.output === 'none' || action.output === 'location' || doc === undefined) {\n return undefined\n }\n // A `metaResult` action's `200` is meta-only, while its `201` carries the resource it created.\n if (action.output === 'meta' || (action.metaResult === true && !('data' in doc))) {\n return doc.meta\n }\n return materialise(doc, ctx.materialise)\n}\n\n/**\n * The request media type an action with several (`inputMedia`) sends: the caller's pick, matched\n * exactly or through a declared wildcard such as `image/*`, else JSON:API when listed, else the\n * first. `undefined` for an action with a single request media type.\n */\nfunction requestMedia(\n action: ActionDescriptor,\n picked: string | undefined,\n): { mediaType: string; kind: InputMediaKind } | undefined {\n const listed = action.inputMedia\n if (listed === undefined || listed.length === 0) {\n if (picked !== undefined) {\n throw new Error(`This action declares no request media types to choose \"${picked}\" from.`)\n }\n return undefined\n }\n if (picked === undefined) {\n const media = listed.find((entry) => entry.mediaType === JSON_API_MEDIA_TYPE) ?? listed[0]!\n return { mediaType: media.mediaType, kind: media.kind }\n }\n const essence = picked.split(';')[0]!.trim().toLowerCase()\n const match =\n listed.find((entry) => entry.mediaType === essence) ??\n listed.find((entry) => entry.mediaType === `${essence.split('/')[0]}/*`) ??\n listed.find((entry) => entry.mediaType === '*/*')\n if (match === undefined) {\n throw new Error(\n `This action does not accept \"${picked}\"; it accepts ${listed.map((entry) => entry.mediaType).join(', ')}.`,\n )\n }\n return { mediaType: picked, kind: match.kind }\n}\n\n/**\n * A multipart or URL-encoded body given as a plain object of fields, encoded into a `FormData` or\n * `URLSearchParams`. Any other body, a ready `FormData` included, is sent as it is.\n */\nfunction encodeFields(mediaType: string, kind: InputMediaKind | undefined, body: unknown): unknown {\n const multipart = kind === 'multipart' || mediaType.startsWith('multipart/')\n const form = kind === 'form' || mediaType === 'application/x-www-form-urlencoded'\n if ((!multipart && !form) || !isPlainObject(body)) {\n return body\n }\n return multipart ? toFormData(body) : toSearchParams(body)\n}\n\n/** Whether a body is a plain object of fields rather than a ready payload. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false\n }\n const proto = Object.getPrototypeOf(value) as unknown\n return proto === Object.prototype || proto === null\n}\n\n/**\n * The entries a field contributes: nothing for `null` or `undefined`, one `name[]` entry per item\n * for an array (the bracket suffix is how PHP servers read a repeated field as a list), else one\n * `name` entry.\n */\nfunction fieldEntries(name: string, value: unknown): [string, unknown][] {\n if (value === null || value === undefined) {\n return []\n }\n if (Array.isArray(value)) {\n return value\n .filter((item) => item !== null && item !== undefined)\n .map((item): [string, unknown] => [`${name}[]`, item])\n }\n return [[name, value]]\n}\n\n/** A field's text value: booleans as `true` or `false`, everything else through `String`. */\nfunction fieldText(value: unknown): string {\n return typeof value === 'boolean' ? (value ? 'true' : 'false') : String(value)\n}\n\n/** A multipart body from fields. A `File` keeps its name; a bare `Blob` is named after its field. */\nfunction toFormData(fields: Record<string, unknown>): FormData {\n const data = new FormData()\n for (const [field, value] of Object.entries(fields)) {\n for (const [name, item] of fieldEntries(field, value)) {\n if (typeof Blob !== 'undefined' && item instanceof Blob) {\n const fileName =\n typeof File !== 'undefined' && item instanceof File && item.name !== ''\n ? item.name\n : field\n data.append(name, item, fileName)\n } else {\n data.append(name, fieldText(item))\n }\n }\n }\n return data\n}\n\n/** A URL-encoded body from fields. */\nfunction toSearchParams(fields: Record<string, unknown>): URLSearchParams {\n const params = new URLSearchParams()\n for (const [field, value] of Object.entries(fields)) {\n for (const [name, item] of fieldEntries(field, value)) {\n params.append(name, fieldText(item))\n }\n }\n return params\n}\n\n/**\n * The `Content-Type` for a non-JSON:API body. A multipart `FormData` body gets none, so the\n * transport writes the boundary. A wildcard media type takes a `Blob` body's own type.\n */\nfunction sentContentType(\n mediaType: string,\n kind: InputMediaKind | undefined,\n body: unknown,\n): string | null {\n if (\n (kind === 'multipart' || mediaType.startsWith('multipart/')) &&\n typeof FormData !== 'undefined' &&\n body instanceof FormData\n ) {\n return null\n }\n if (mediaType.includes('*') && typeof Blob !== 'undefined' && body instanceof Blob) {\n return body.type === '' ? mediaType : body.type\n }\n return mediaType\n}\n\n/**\n * The non-JSON:API media type an action is asked to answer in: the caller's `accept` when it isn't\n * JSON:API, else, with no `accept`, the first raw media type of an action that answers in no\n * JSON:API document. `undefined` means a JSON:API response.\n */\nfunction responseMedia(\n action: ActionDescriptor,\n accept: string | undefined,\n): { mediaType: string; kind: string } | undefined {\n const raw = action.rawOutput ?? []\n if (accept === undefined) {\n return action.output === 'none' ? raw[0] : undefined\n }\n if (accept === JSON_API_MEDIA_TYPE) {\n return undefined\n }\n const media = raw.find((entry) => entry.mediaType === accept)\n if (media === undefined) {\n throw new Error(\n `This action does not answer in \"${accept}\"; it answers in ${[...(action.output === 'none' ? [] : [JSON_API_MEDIA_TYPE]), ...raw.map((entry) => entry.mediaType)].join(', ')}.`,\n )\n }\n return media\n}\n\n/**\n * Build the typed `.actions` accessor at one scope: a plain object exposing exactly the\n * type's actions declared at `scope` (collection on the type accessor, resource on a handle),\n * each a function dispatching to {@link runAction} with the action descriptor + the scope's\n * path vars (resource scope supplies `{id}`). Names not declared at this scope are absent —\n * `client.albums.actions.reissue` (resource-scoped) is undefined; reach it via `.id(id)`.\n */\nfunction actionsAccessor(\n ctx: ClientContext,\n type: string,\n scope: ActionScope,\n vars: Record<string, string>,\n): ActionsAccessor<ApiDescriptor, unknown, unknown, string, ActionScope> {\n const actions = ctx.descriptor[type]?.actions ?? {}\n const out: Record<string, (...args: unknown[]) => Promise<unknown>> = {}\n for (const [name, action] of Object.entries(actions)) {\n if (action.scope === scope) {\n // An action without input takes only the options; any other takes the body first.\n out[name] = (...args: unknown[]) =>\n action.input === 'none'\n ? runAction(ctx, action, vars, undefined, args[0] as ActionCallOptions | undefined)\n : runAction(ctx, action, vars, args[0], args[1] as ActionCallOptions | undefined)\n }\n }\n return out as ActionsAccessor<ApiDescriptor, unknown, unknown, string, ActionScope>\n}\n\n/**\n * Build the relationship accessor for `client.<type>.id(id).<rel>`, or a singleton's\n * `client.<type>.<rel>` with no `id` in `vars`: reads\n * (`.get()` linkage / `.related()` collection) plus mutations — to-many `.add` (POST) /\n * `.remove` (DELETE) / `.replace` (PATCH) and to-one `.set` (PATCH). Every mutation posts\n * a `{ data: <linkage> }` body to `fetchRelationship` and materialises the response as\n * linkage (or `undefined`/`void` for a `204`). The cardinality is read off the descriptor\n * so the linkage is coerced correctly; the static types gate which verb is callable.\n */\nfunction relationshipAccessor(\n ctx: ClientContext,\n type: string,\n owner: Record<string, string>,\n rel: string,\n): RelationshipAccessor<ApiDescriptor, unknown, string, never> {\n const vars = { ...owner, rel }\n const relation = ctx.descriptor[type]?.relations[rel]\n const cardinality = relation?.cardinality ?? 'many'\n const hasPivot = relation?.pivot === true\n const mutate = (\n verb: 'add' | 'remove' | 'replace' | 'set',\n method: string,\n refs: unknown,\n opts: { meta?: Readonly<Record<string, unknown>> } | undefined,\n ): Promise<unknown> =>\n runWrite(ctx, {\n type,\n operation: 'fetchRelationship',\n vars,\n method,\n body: withTopLevelMeta(toRelationshipDocument(refs, cardinality), opts?.meta),\n linkage: true,\n remap: (error) => withRemappedRelationshipPaths(error, rel, hasPivot),\n metaOnly: relation?.mutationMeta?.[verb] !== undefined,\n })\n\n // Whether the relation advertises a mutation verb: the descriptor's `mutations` flags are\n // authoritative when present (mirrors the type-level `AdvertisesVerb`), so a verb the\n // bundle forbids (`cannotReplace` -> no PATCH) is absent at runtime, not just untyped. A\n // relation with no `mutations` block falls back to cardinality alone.\n const advertises = (verb: 'add' | 'remove' | 'replace' | 'set'): boolean => {\n const mutations = relation?.mutations\n return mutations === undefined ? true : mutations[verb] === true\n }\n\n // A read is present only when the relation exposes that endpoint (the descriptor's\n // `relationship`/`related` flags, from the bundle's `withoutRelationshipEndpoint()` /\n // `withoutRelatedEndpoint()`). A suppressed read is omitted (a JS caller gets \"not a function\"\n // rather than a 404); the static types gate it to `never` for a typed caller.\n // A write-only relation is never rendered, so it has neither read.\n const accessor: Record<string, unknown> = {}\n const readable = relation?.writeOnly !== true\n if (readable && relation?.relationship !== false) {\n accessor['get'] = (query?: RelationReadQuery) =>\n run(ctx, type, 'fetchRelationship', vars, query as ReadQuery | undefined, true, rel)\n }\n if (readable && relation?.related !== false) {\n accessor['related'] = (query?: RelationReadQuery) =>\n run(ctx, type, 'fetchRelated', vars, query as ReadQuery | undefined, false, rel)\n }\n type MutationOpts = { meta?: Readonly<Record<string, unknown>> } | undefined\n if (cardinality === 'many') {\n if (advertises('add')) {\n accessor['add'] = (refs: unknown, opts?: MutationOpts) => mutate('add', 'POST', refs, opts)\n }\n if (advertises('remove')) {\n accessor['remove'] = (refs: unknown, opts?: MutationOpts) =>\n mutate('remove', 'DELETE', refs, opts)\n }\n if (advertises('replace')) {\n accessor['replace'] = (refs: unknown, opts?: MutationOpts) =>\n mutate('replace', 'PATCH', refs, opts)\n }\n } else if (advertises('set')) {\n accessor['set'] = (ref: unknown, opts?: MutationOpts) => mutate('set', 'PATCH', ref, opts)\n }\n\n return accessor as unknown as RelationshipAccessor<ApiDescriptor, unknown, string, never>\n}\n\n/**\n * The reserved members on a {@link ResourceHandle} — names the Proxy resolves itself, so a\n * relation of the same name is shadowed and must route through `.rel(name)`. The codegen\n * imports this to warn at build time (keeping the runtime + the collision detector in sync).\n * `then` is reserved so a handle is never mistaken for a thenable.\n */\nexport const HANDLE_RESERVED: ReadonlySet<string> = new Set([\n 'type',\n 'id',\n 'get',\n 'update',\n 'delete',\n 'rel',\n 'actions',\n 'then',\n])\n\n/**\n * Run a type's update. `vars` fill its path (`{ id }`, or nothing for a singleton) and `id` is\n * the one the body carries.\n */\nfunction runUpdate(\n ctx: ClientContext,\n type: string,\n vars: Record<string, string>,\n id: string,\n patch: Record<string, unknown>,\n opts: WriteOpts | undefined,\n): Promise<unknown> {\n // The body is built inside `write`, so input the schema rejects never reaches toDocument().\n return withInputCheck(ctx.inputSchemas, { type, operation: 'update', input: patch }, () =>\n runWrite(ctx, {\n type,\n operation: 'update',\n vars,\n method: 'PATCH',\n body: withTopLevelMeta(toDocument(ctx.descriptor, type, patch, { id }), opts?.meta),\n query: writeQuery(opts),\n remap: (error) => withRemappedPaths(error, ctx.descriptor, type),\n accepted: ctx.descriptor[type]?.accepted?.update,\n wait: waitOptions(opts?.wait),\n }),\n )\n}\n\n/**\n * Wrap a handle's verbs in a Proxy resolving each relation not shadowed by a reserved member to\n * its relationship accessor, addressed by `vars`.\n */\nfunction withRelations<T extends object>(\n ctx: ClientContext,\n type: string,\n vars: Record<string, string>,\n base: T,\n): T {\n const relations = ctx.descriptor[type]?.relations ?? {}\n return new Proxy(base, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !HANDLE_RESERVED.has(prop) && prop in relations) {\n return relationshipAccessor(ctx, type, vars, prop)\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\n/** Build the id-scoped resource handle (a Proxy resolving relation accessors by name). */\nfunction resourceHandle(\n ctx: ClientContext,\n type: string,\n id: string,\n): ResourceHandle<ApiDescriptor, unknown, unknown, string> {\n const vars = { id }\n return withRelations(ctx, type, vars, {\n type,\n id,\n get: (query?: ReadQuery) => run(ctx, type, 'fetchOne', vars, query),\n update: (patch: Record<string, unknown>, opts?: WriteOpts) =>\n runUpdate(ctx, type, vars, id, patch, opts),\n delete: (opts?: { meta?: Readonly<Record<string, unknown>> }) =>\n runWrite(ctx, {\n type,\n operation: 'delete',\n vars,\n method: 'DELETE',\n // A delete declaring its request `meta` takes a meta-only document; any other, no body.\n body: opts?.meta === undefined ? undefined : { meta: opts.meta },\n remap: (error) => withRemappedPaths(error, ctx.descriptor, type),\n metaOnly: ctx.descriptor[type]?.documentMeta?.delete !== undefined,\n }) as never,\n rel: (name: string) => relationshipAccessor(ctx, type, vars, name),\n actions: actionsAccessor(ctx, type, 'resource', vars),\n }) as unknown as ResourceHandle<ApiDescriptor, unknown, unknown, string>\n}\n\n/**\n * Build the accessor of a singleton type (`client.inboxes`): a handle on the caller's one\n * resource, whose paths carry no id. Its update takes the resource's `id` in the input, since\n * the server reads it from the body.\n */\nfunction singletonAccessor(\n ctx: ClientContext,\n type: string,\n): SingletonAccessor<ApiDescriptor, unknown, unknown, string> {\n const vars = {}\n return withRelations(ctx, type, vars, {\n type,\n get: (query?: ReadQuery) => run(ctx, type, 'fetchOne', vars, query),\n update: (input: Record<string, unknown>, opts?: WriteOpts) => {\n const { id, ...patch } = input\n if (typeof id !== 'string' || id === '') {\n return Promise.reject(\n new Error(\n `Updating the \"${type}\" singleton needs its id in the input, such as the id of the resource its get() read.`,\n ),\n )\n }\n return runUpdate(ctx, type, vars, id, patch, opts)\n },\n rel: (name: string) => relationshipAccessor(ctx, type, vars, name),\n actions: actionsAccessor(ctx, type, 'resource', vars),\n }) as unknown as SingletonAccessor<ApiDescriptor, unknown, unknown, string>\n}\n\n/** Build the collection-scoped accessor for one wire type (`client.albums`). */\nfunction typeAccessor(\n ctx: ClientContext,\n type: string,\n): TypeAccessor<ApiDescriptor, unknown, unknown, string> {\n return {\n list: (query?: ReadQuery) => run(ctx, type, 'fetchMany', {}, query) as Promise<never>,\n get: (id: string, query?: ReadQuery) =>\n run(ctx, type, 'fetchOne', { id }, query) as Promise<never>,\n create: (input: Record<string, unknown>, opts?: WriteOpts) =>\n withInputCheck(ctx.inputSchemas, { type, operation: 'create', input }, () =>\n runWrite(ctx, {\n type,\n operation: 'create',\n vars: {},\n method: 'POST',\n body: withTopLevelMeta(toDocument(ctx.descriptor, type, input), opts?.meta),\n query: writeQuery(opts),\n remap: (error) => withRemappedPaths(error, ctx.descriptor, type),\n accepted: ctx.descriptor[type]?.accepted?.create,\n wait: waitOptions(opts?.wait),\n }),\n ) as Promise<never>,\n id: (id: string) => resourceHandle(ctx, type, id),\n actions: actionsAccessor(ctx, type, 'collection', {}),\n } as unknown as TypeAccessor<ApiDescriptor, unknown, unknown, string>\n}\n\n/**\n * Build a descriptor-driven read client. Generic at runtime (a Proxy over the descriptor),\n * not per-type codegen: `client.<type>` yields a {@link TypeAccessor}, or a\n * {@link SingletonAccessor} for a singleton type, `.id(id)` a handle,\n * and a handle's relation accessors drive the relationship/related endpoints. Navigation\n * (`$next()`/`$prev()`, related links) is wired through `materialise`'s `navigate` seam,\n * which resolves the server's link against `baseUrl`, executes it and re-materialises.\n */\nexport function createClient<\n D extends ApiDescriptor,\n A = DefaultAttributes<D>,\n W = DefaultWriteAttributes<D>,\n Act = DefaultActionTypes,\n E extends string = string,\n L = Record<never, never>,\n O = Record<never, never>,\n>(descriptor: D, options: ClientOptions): Client<D, A, W, Act, E, L, O> {\n const request: JsonApiContext = {\n baseUrl: options.baseUrl,\n transport: options.transport ?? fetchTransport,\n ...(options.headers !== undefined ? { headers: options.headers } : {}),\n ...(options.allowCrossOriginLinks !== undefined\n ? { allowCrossOriginLinks: options.allowCrossOriginLinks }\n : {}),\n }\n\n const validator = resolveValidator(options.validate)\n const ctx: ClientContext = {\n request,\n descriptor,\n ...(options.validateInput !== undefined ? { inputSchemas: options.validateInput } : {}),\n materialise: {\n descriptor,\n navigate: async (url, linkage = false, paginator, signal) => {\n const doc = await execute(request, {\n method: 'GET',\n path: url,\n link: true,\n ...(signal !== undefined ? { signal } : {}),\n })\n return doc === undefined\n ? undefined\n : materialise(\n doc,\n withFields(ctx.materialise, fieldsOfUrl(url)),\n linkage,\n undefined,\n paginator,\n )\n },\n ...(validator !== undefined ? { validate: validator } : {}),\n },\n }\n\n const atomicDescriptor = options.atomic ?? null\n // `client.atomic(tx => …)`: post the recorded batch to the atomic endpoint. Built once and\n // reused; throws when the server declares no atomic capability (`atomic` was null/omitted).\n // Typed via the single conditional-return `Client['atomic']` signature (tuple-of-handles ->\n // positional results; void -> loose results); the runtime forwards the callback to `runAtomic`.\n const atomic = (build: (tx: AtomicRecorder<D, W>) => unknown): Promise<unknown> => {\n if (atomicDescriptor === null) {\n throw new Error('This API does not expose an Atomic Operations endpoint')\n }\n return runAtomic(\n request,\n ctx.materialise,\n descriptor,\n atomicDescriptor.path,\n build as (tx: AtomicRecorder<D, W>) => void,\n ctx.inputSchemas,\n )\n }\n\n const accessors = new Map<\n string,\n | TypeAccessor<ApiDescriptor, unknown, unknown, string>\n | SingletonAccessor<ApiDescriptor, unknown, unknown, string>\n >()\n return new Proxy(Object.create(null) as object, {\n get(_target, prop) {\n if (prop === 'atomic') {\n return atomic\n }\n if (typeof prop !== 'string' || !(prop in descriptor)) {\n return undefined\n }\n let accessor = accessors.get(prop)\n if (accessor === undefined) {\n accessor =\n descriptor[prop]?.singleton === true\n ? singletonAccessor(ctx, prop)\n : typeAccessor(ctx, prop)\n accessors.set(prop, accessor)\n }\n return accessor\n },\n has(_target, prop) {\n return prop === 'atomic' || (typeof prop === 'string' && prop in descriptor)\n },\n }) as Client<D, A, W, Act, E, L, O>\n}\n","import { type CodesOf, errorText, type JsonApiErrorOf } from './error-shared'\nimport { JsonApiError, type JsonApiErrorObject } from './errors'\nimport { joinInputPath, splitInputPath } from './input-path'\nimport { InputValidationError, type StandardSchemaIssue } from './input-validation'\n\n/** One segment of a Standard Schema issue path: a key, or an array index. */\nexport type PathSegment = string | number\n\n/**\n * One error shaped as a Standard Schema issue (`message` plus `path` segments), so a form library\n * that takes Standard Schema issues takes it as is.\n */\nexport interface FieldError<C extends string = string> {\n /** The error's `detail`, else its `title`, else its `code`. */\n readonly message: string\n /** The input path as segments: `orderedTracks[0].$pivot.position` is `['orderedTracks', 0, '$pivot', 'position']`. Empty for a form-level error. */\n readonly path: readonly PathSegment[]\n /** The input path as the runtime keys it, `''` for a form-level error. */\n readonly key: string\n readonly code?: C | (string & {})\n /** The failing operation's index in an atomic batch. */\n readonly opIndex?: number\n /** The error object as the server sent it, with its remapped `path`. Absent for an {@link InputValidationError}'s issue. */\n readonly error?: JsonApiErrorObject<C>\n}\n\n/** A write's errors for a form, split into the inputs they point at and the rest. */\nexport interface FieldErrors<I = unknown, C extends string = string> {\n /** Errors on an input, grouped by its path. */\n readonly fields: Readonly<Record<string, readonly FieldError<C>[]>>\n /** Errors that point at no input: no `source`, a `source.parameter` or `source.header`, or a pointer the client owns, such as `/data/type`. */\n readonly form: readonly FieldError<C>[]\n /** Every error, in the order the server sent them. */\n readonly issues: readonly FieldError<C>[]\n /** The first message on the input at `path`. */\n first(path: InputPath<I>): string | undefined\n /** Every message on the input at `path`. */\n messages(path: InputPath<I>): string[]\n /** Only the errors of the atomic operation at `index`. */\n op(index: number): FieldErrors<unknown, C>\n}\n\ndeclare const writeInput: unique symbol\n\n/**\n * A {@link JsonApiError} tagged with the input of the write that raised it, at the type level\n * only, so {@link fieldErrors} types its paths without a type argument.\n */\nexport type WriteError<C extends string = string, I = unknown> = JsonApiError<C> & {\n readonly [writeInput]?: I\n}\n\ntype InputOf<E> = [JsonApiErrorOf<E>] extends [never]\n ? unknown\n : JsonApiErrorOf<E> extends { readonly [writeInput]?: infer I }\n ? I\n : unknown\n\ntype Scalar = string | number | boolean | bigint | symbol | Date\n\n/** The next depth down; the paths stop at four levels of nesting. */\ntype Deeper = [never, 0, 1, 2, 3]\n\n/**\n * Every path the runtime can key an error on for write input `I`: attribute keys, nested map\n * keys joined with `.`, to-many members as `[n]` with their `$pivot` fields, `$meta` members, and\n * `$documentMeta` members. A union-typed value contributes only the keys its members share. Any\n * string when `I` is unknown.\n */\nexport type InputPath<I> = unknown extends I ? string : KeyPaths<I, 4> | `$documentMeta.${string}`\n\ntype KeyPaths<T, D extends number> = [D] extends [never]\n ? never\n : [T] extends [object]\n ? { [K in keyof T & string]-?: K | `${K}${SubPaths<NonNullable<T[K]>, D>}` }[keyof T & string]\n : never\n\ntype SubPaths<V, D extends number> = [V] extends [never]\n ? never\n : [V] extends [readonly (infer M)[]]\n ? `[${number}]` | `[${number}]${MemberPaths<NonNullable<M>, D>}`\n : MemberPaths<V, D>\n\n// A linkage ref (it has `type`) contributes only its `$pivot` fields.\ntype MemberPaths<V, D extends number> = [V] extends [Scalar]\n ? never\n : 'type' extends keyof V\n ? [V] extends [{ $pivot?: infer P }]\n ? P extends object\n ? '.$pivot' | `.$pivot.${keyof P & string}`\n : never\n : never\n : `.${KeyPaths<V, Deeper[D]>}`\n\n/**\n * The 4xx `error`'s errors keyed by the write input they point at, or `undefined` when `error`\n * is not a 4xx {@link JsonApiError} or none of its errors points at an input. An\n * {@link InputValidationError} gives its issues the same way. Pass the input type when `error`\n * carries none: `fieldErrors<Parameters<typeof client.albums.create>[0]>(caught)`.\n */\nexport function fieldErrors<I = never, E = unknown>(\n error: E,\n): FieldErrors<[I] extends [never] ? InputOf<E> : I, CodesOf<E>> | undefined\nexport function fieldErrors(error: unknown): FieldErrors | undefined {\n if (error instanceof InputValidationError) {\n return group(error.issues.map((issue) => fromIssue(issue, error.opIndex)))\n }\n if (!(error instanceof JsonApiError) || !error.is4xx()) {\n return undefined\n }\n const issues = error.errors.map(toFieldError)\n return issues.some((issue) => issue.key !== '') ? group(issues) : undefined\n}\n\nfunction group<C extends string>(issues: readonly FieldError<C>[]): FieldErrors<unknown, C> {\n const fields: Record<string, FieldError<C>[]> = {}\n const form: FieldError<C>[] = []\n for (const issue of issues) {\n if (issue.key === '') {\n form.push(issue)\n } else {\n ;(fields[issue.key] ??= []).push(issue)\n }\n }\n return {\n fields,\n form,\n issues,\n first: (path) => fields[path]?.[0]?.message,\n messages: (path) => fields[path]?.map((issue) => issue.message) ?? [],\n op: (index) => group(issues.filter((issue) => issue.opIndex === index)),\n }\n}\n\nfunction toFieldError<C extends string>(error: JsonApiErrorObject<C>): FieldError<C> {\n // The runtime leaves a pointer it can't map to an input verbatim, so it still starts with `/`.\n const key = error.path === undefined || error.path.startsWith('/') ? '' : error.path\n return {\n message: errorText(error, true) ?? 'Invalid',\n path: splitInputPath(key),\n key,\n ...(error.code === undefined ? {} : { code: error.code }),\n ...(error.opIndex === undefined ? {} : { opIndex: error.opIndex }),\n error,\n }\n}\n\nfunction fromIssue(issue: StandardSchemaIssue, opIndex: number | undefined): FieldError {\n const path = (issue.path ?? []).map((segment) => {\n const key = typeof segment === 'object' ? segment.key : segment\n return typeof key === 'number' ? key : String(key)\n })\n const key = joinInputPath(path)\n return { message: issue.message, path, key, ...(opIndex === undefined ? {} : { opIndex }) }\n}\n","import type { Collection } from './result-types'\n\n/** Options for {@link loadAll}. */\nexport interface LoadAllOptions {\n /** Stops the walk, rejecting with the signal's reason. */\n signal?: AbortSignal\n /** Stop after this many pages, as a guard against an unexpectedly large collection. */\n maxPages?: number\n}\n\n/**\n * Follow `next` links from a first page until the last, and return every member in one plain\n * array. It takes any collection: a list, a related read, or a to-many relationship of a resource\n * you read, which holds only its first page of members when the server renders its linkage:\n *\n * ```ts\n * const album = await client.albums.get('1', { include: ['tracks'] })\n * const tracks = await loadAll(album.tracks)\n * ```\n */\nexport async function loadAll<T>(\n first: Collection<T> | PromiseLike<Collection<T>>,\n options: LoadAllOptions = {},\n): Promise<T[]> {\n const { signal, maxPages = Number.POSITIVE_INFINITY } = options\n let page: Collection<T> | undefined = await first\n const all: T[] = []\n let count = 0\n while (page !== undefined && count < maxPages) {\n all.push(...page)\n count++\n if (count >= maxPages) {\n break\n }\n signal?.throwIfAborted()\n page = await page.$next(signal !== undefined ? { signal } : undefined)\n }\n return all\n}\n","import type { ApiDescriptor } from './descriptor'\nimport { materialise, type MaterialiseContext } from './materialise'\nimport type { Document } from './request'\n\n/** One resource as plain data: `type`, `id`, attributes, and relation values by name. */\nexport interface MockData {\n readonly type: string\n readonly id: string\n}\n\ntype DataObject = MockData & Readonly<Record<string, unknown>>\n\n/** The members a linkage member carries beside its identity, which never become attributes. */\nconst MEMBER_KEYS = new Set(['type', 'id', 'meta', '$pivot'])\n\n/**\n * Build a materialised resource from its plain data, as a read returns it: the relations the data\n * nests hydrate, the identifiers stay identifiers, and each member's `$pivot` lands on its linkage\n * `meta.pivot`, so `$pivot`, `$edge`, `$rel` and `$count` all work. For tests and stories; the\n * generated client binds it to its descriptor and types it.\n */\nexport function mockResource(descriptor: ApiDescriptor, data: MockData): object {\n return materialise(mockDocument(descriptor, data), mockContext(descriptor)) as object\n}\n\n/** {@link mockResource} for a collection of type `type`, as a list read returns it. */\nexport function mockCollection(\n descriptor: ApiDescriptor,\n type: string,\n data: readonly MockData[],\n): object {\n return materialise(mockDocument(descriptor, data), mockContext(descriptor), false, type) as object\n}\n\nfunction mockContext(descriptor: ApiDescriptor): MaterialiseContext {\n return {\n descriptor,\n navigate: () =>\n Promise.reject(new Error('A mock resource has no server to follow its links to.')),\n }\n}\n\n/** The JSON:API document plain data stands for: the primary data, and every nested resource in `included`. */\nexport function mockDocument(\n descriptor: ApiDescriptor,\n data: MockData | readonly MockData[],\n): Document {\n const primary = new Set<string>()\n const included = new Map<string, Record<string, unknown>>()\n const toResource = (value: DataObject): Record<string, unknown> => {\n const relations = descriptor[value.type]?.relations ?? {}\n const attributes: Record<string, unknown> = {}\n const relationships: Record<string, unknown> = {}\n for (const [key, member] of Object.entries(value)) {\n if (key === 'type' || key === 'id') {\n continue\n }\n if (key in relations) {\n if (member !== undefined) {\n relationships[key] = { data: linkageOf(member) }\n }\n } else if (key !== 'meta' && key !== '$pivot') {\n attributes[key] = member\n }\n }\n return {\n type: value.type,\n id: value.id,\n ...(Object.keys(attributes).length > 0 ? { attributes } : {}),\n ...(Object.keys(relationships).length > 0 ? { relationships } : {}),\n ...(value['meta'] !== undefined ? { meta: value['meta'] } : {}),\n }\n }\n const linkageOf = (value: unknown): unknown => {\n if (value === null) {\n return null\n }\n if (Array.isArray(value)) {\n return value.map((member: DataObject) => identifierOf(member))\n }\n return identifierOf(value as DataObject)\n }\n const identifierOf = (member: DataObject): Record<string, unknown> => {\n const id = `${member.type}:${member.id}`\n if (isFullResource(member) && !primary.has(id) && !included.has(id)) {\n // Reserve the slot first so a nested cycle back to this member stops here.\n included.set(id, {})\n included.set(id, toResource(member))\n }\n const pivot = (member as { $pivot?: unknown }).$pivot\n const meta = member['meta'] as Record<string, unknown> | undefined\n const linkageMeta = pivot === undefined ? meta : { ...meta, pivot }\n return {\n type: member.type,\n id: member.id,\n ...(linkageMeta !== undefined ? { meta: linkageMeta } : {}),\n }\n }\n const list = (Array.isArray(data) ? data : [data]) as readonly DataObject[]\n for (const value of list) {\n primary.add(`${value.type}:${value.id}`)\n }\n const resources = list.map(toResource)\n return {\n data: Array.isArray(data) ? resources : resources[0],\n ...(included.size > 0 ? { included: [...included.values()] } : {}),\n }\n}\n\n/** Whether a relation member carries more than its identity, so it stands for an included resource. */\nfunction isFullResource(member: DataObject): boolean {\n return Object.keys(member).some((key) => !MEMBER_KEYS.has(key))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,IAAI,QAAQ;;;;;;AAOZ,SAAgB,mBAA2B;CACzC,SAAS;CACT,OAAO;AACT;AAEA,MAAM,yBAAS,IAAI,QAAwB;;;;;;AAO3C,SAAgB,aAAgB,OAAU,OAAkB;CAC1D,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO,IAAI,OAAO,KAAK;CAEzB,OAAO;AACT;AAEA,MAAM,iCAAiB,IAAI,QAAwB;;;;;;AAOnD,SAAgB,cAAc,KAAyB,OAAqB;CAC1E,IAAI,QAAQ,KAAA,GACV,eAAe,IAAI,KAAK,KAAK;AAEjC;;;;;AAMA,SAAgB,kBAAqB,KAAyB,OAAa;CACzE,MAAM,QAAQ,QAAQ,KAAA,IAAY,KAAA,IAAY,eAAe,IAAI,GAAG;CACpE,OAAO,UAAU,KAAA,IAAY,QAAQ,aAAa,OAAO,KAAK;AAChE;;;;;;;AAQA,SAAgB,eAAe,OAAoC;CACjE,OAAO,OAAO,UAAU,YAAY,UAAU,OAAO,OAAO,IAAI,KAAK,IAAI,KAAA;AAC3E;;;;AC3EA,MAAa,sBAAsB;;AAGnC,MAAa,aAAa;;;;;;;;AAmB1B,SAAgB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