@haddowg/json-api-client 1.29.0 → 1.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ajv.cjs +1 -1
- package/dist/ajv.d.cts +1 -1
- package/dist/ajv.d.mts +1 -1
- package/dist/ajv.mjs +1 -1
- package/dist/index.cjs +156 -19
- package/dist/index.d.cts +91 -7
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +91 -7
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +153 -20
- package/dist/index.mjs.map +1 -1
- package/dist/{validate-B2Dtn9dI.cjs → validate-B9cyfO3p.cjs} +20 -4
- package/dist/{validate-CtXB1MGk.mjs → validate-BuPAPJMi.mjs} +16 -6
- package/dist/validate-BuPAPJMi.mjs.map +1 -0
- package/dist/{validate-DF5kzZp9.d.mts → validate-CCLqE_2J.d.cts} +257 -38
- package/dist/validate-CCLqE_2J.d.cts.map +1 -0
- package/dist/{validate-DF5kzZp9.d.cts → validate-CCLqE_2J.d.mts} +257 -38
- package/dist/validate-CCLqE_2J.d.mts.map +1 -0
- package/package.json +1 -1
- package/dist/validate-CtXB1MGk.mjs.map +0 -1
- package/dist/validate-DF5kzZp9.d.cts.map +0 -1
- package/dist/validate-DF5kzZp9.d.mts.map +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
|
-
import { $ as DeleteResult, $n as
|
|
1
|
+
import { $ as DeleteResult, $n as InputValidationError, $r as PollOptions, $t as RelationSortQuery, A as TransportResponse, Ai as PivotDescriptor, An as WriteOptions, Ar as ATOMIC_MEDIA_TYPE, At as OptionsArg, B as Client, Bi as ResourceExamples, Bn as AtomicOperationArgs, Br as Page, Bt as RelatedMeta, C as ClientOptions, Ci as MenuDescriptor, Cn as UpdateMethod, Cr as identifierViewOf, Ct as MetaOption, D as JsonApiTransport, Di as PaginatorKind, Dn as WithDocumentMeta, Dr as relatedPaginatorKind, Dt as OperationCodes, E as createClient, Ei as PaginatorDescriptor, En as WaitedWriteResult, Er as relatedPaginator, Et as NestedFieldsetMember, F as ActionCallOptions, Fi as RelationDescriptor, Fn as readActionLocation, Fr as mediaType, Ft as ReadAttributesOf, G as CountedRelationName, Gn as AtomicRelationshipRecorder, Gr as PageParams, Gt as RelatedReadRelatedQuery, H as CollectionMeta, Hi as SortFamilyDescriptor, Hn as AtomicRef, Hr as PageLinks, Ht as RelatedQueryEntry, I as ActionsAccessor, Ii as RelationMutations, In as AtomicCreateHandle, Ir as NestedFieldset, It as ReadResult, J as CreateMethod, Jn as AtomicUpdateHandle, Jr as TypedPage, Jt as RelationName, K as CreateAttributesOf, Kn as AtomicResult, Kr as PageParamsOf, Kt as RelationCollection, L as AtomicResultOf, Li as RequestMetaOperation, Ln as AtomicCreateInput, Lr as nestedFieldset, Lt as ReadableRelationName, M as AcceptedJob, Mi as RawOutputMedia, Mn as WriteResult, Mr as LocalIdentifier, Mt as PendingPivotOf, N as AcceptedMeta, Ni as RelatedQueryDescriptor, Nn as ActionLocation, Nr as MediaTypeParams, Nt as PivotFieldsOf, O as TransportRawBody, Oi as PaginatorRole, On as WithLinks, Or as setMaterialisedOverlay, Ot as OperationErrorCodeOf, P as AcceptedOf, Pi as RelatedQueryOperation, Pn as isActionLocation, Pr as ResourceIdentifier, Pt as PivotInput, Q as DeleteArgs, Qn as InputSchemas, Qr as Accepted, Qt as RelationRequestMetaOf, R as BinaryBody, Ri as ResourceCountOperation, Rn as AtomicDeleteHandle, Rr as CANONICAL_PAGE_KEYS, Rt as RelatedIncludedResource, S as serializeQuery, Si as MediaExamples, Sn as UpdateInput, Sr as edgeViewOf, St as MetaObject, T as HeadersInit, Ti as OperationExamples, Tn as WaitValue, Tr as materialise, Tt as MutationVerb, U as CountAccessor, Ui as StrategyDescriptor, Un as AtomicRelationshipArgs, Ur as PageMeta, Ut as RelatedQueryParam, V as Collection, Vi as ResourceMetaDescriptor, Vn as AtomicRecorder, Vr as PageKeys, Vt as RelatedQuery, W as CountToken, Wi as isPolymorphic, Wn as AtomicRelationshipHandle, Wr as PageOf, Wt as RelatedQueryRelation, X as DefaultAttributes, Xn as runAtomic, Xr as prevPageParams, Xt as RelationPaginator, Y as DefaultActionTypes, Yn as AtomicUpdateInput, Yr as nextPageParams, Yt as RelationPageParams, Z as DefaultWriteAttributes, Zn as InputCheck, Zr as resolvePaginator, Zt as RelationReadQuery, _ as RawResponseType, _i as DocumentMetaDescriptor, _n as TypeAccessor, _r as PendingPlacement, _t as ListPageParams, a as ValidationOption, ai as ActionDescriptor, an as ResourceCountToken, ar as ArrayEnvelope, at as FieldsMap, b as executeRaw, bi as InputMedia, bn as TypedRelatedReadQuery, br as ResourceEnvelope, bt as MemberName, c as assertJsonApiDocument, ci as ActionOutput, cn as ResourceObjectView, cr as EdgeEnvelope, ct as HydratedMember, d as sparseSchemas, di as ApiDescriptor, dn as SingleReadQuery, dr as LinkObject, dt as IncludedRelations, ei as PollTimeoutError, en as RelationshipAccessor, er as StandardSchema, et as DocumentMeta, f as validateDocument, fi as ApiExamples, fn as SingletonAccessor, fr as MaterialiseContext, ft as IncludedResource, g as JsonApiRequest, gi as CountableDescriptor, gn as TakesVerb, gr as PendingMember, gt as ListFilterMember, h as JsonApiContext, hi as ClientIdPolicy, hn as SortToken, hr as PendingCreate, ht as LinkageRef, i as ValidationContext, ii as AcceptedOperation, in as ResourceAccessors, ir as withInputCheck, it as FieldSelectionMap, j as fetchTransport, ji as RawMediaKind, jn as WritePivotOf, jr as JSON_API_MEDIA_TYPE, jt as PendingEdge, k as TransportRequest, ki as PaginatorStrategy, kn as WritableRelationName, kr as ATOMIC_EXT, kt as OperationMeta, l as resolveValidator, li as ActionScope, ln as ResourceWriteMeta, lr as EdgeMember, lt as IdentifierMember, m as ExecutedResponse, mi as Cardinality, mn as SortQuery, mr as NavigateOptions, mt as IsSingleton, n as SchemaMap, ni as parseRetryAfter, nn as RequestMetaOf, nr as StandardSchemaResult, nt as ErrorCodeCarrier, o as Validator, oi as ActionInput, on as ResourceHandle, or as DocumentEnvelope, ot as FilterKey, p as Document, pi as AtomicDescriptor, pn as SingletonUpdateInput, pr as MaterialisedOverlay, pt as IncludedType, q as CreateInput, qn as AtomicResults, qr as ResolvedPaginator, qt as RelationFilterQuery, r as ValidationConfig, ri as AcceptedDescriptor, rn as RequiresRequestMeta, rr as inputFailure, rt as ErrorCodeOf, s as WireResource, si as ActionLocationDescriptor, sn as ResourceMetaOf, sr as Edge, st as FilterQuery, t as ResolvedValidator, ti as isAccepted, tn as RelationshipMembers, tr as StandardSchemaIssue, tt as EdgeMembers, u as sparseSchema, ui as AdditionalMembersDescriptor, un as ResourceWriteOperation, ur as Link, ut as IncludePath, v as ReadQuery, vi as DocumentMetaOperation, vn as TypeName, vr as RelationArrayEnvelope, vt as LooseRelatedQuery, w as HANDLE_RESERVED, wi as MetaLiteral, wn as WaitOptions, wr as isMaterialised, wt as MutationMetaOf, x as executeResponse, xi as InputMediaKind, xn as TypedRelationReadQuery, xr as ResourceLinks, xt as MemberTypeOf, y as execute, yi as FilterFamilyDescriptor, yn as TypedReadQuery, yr as RelationView, yt as LooseRelatedQueryEntry, z as BinaryResponseType, zi as ResourceDescriptor, zn as AtomicHandle, zr as ExactPageParams, zt as RelatedIncludedType } from "./validate-CCLqE_2J.mjs";
|
|
2
2
|
|
|
3
|
+
//#region src/error-shared.d.ts
|
|
4
|
+
/** The {@link JsonApiError} members of `E`, read without distributing over a union such as a query's error. */
|
|
5
|
+
type JsonApiErrorOf<E> = Extract<NonNullable<E>, JsonApiError<string>>;
|
|
6
|
+
/** The codes `E`'s {@link JsonApiError} carries, else `Fallback`. */
|
|
7
|
+
type CodesOf<E, Fallback extends string = string> = [JsonApiErrorOf<E>] extends [never] ? Fallback : JsonApiErrorOf<E> extends JsonApiError<infer C> ? C : Fallback;
|
|
8
|
+
//#endregion
|
|
3
9
|
//#region src/errors.d.ts
|
|
4
10
|
/**
|
|
5
11
|
* A single JSON:API error object (spec: error objects).
|
|
@@ -83,11 +89,20 @@ declare class JsonApiError<C extends string = string> extends Error {
|
|
|
83
89
|
*/
|
|
84
90
|
declare function hasErrorCode(err: unknown, code: string): err is JsonApiError;
|
|
85
91
|
/**
|
|
86
|
-
*
|
|
92
|
+
* The codes `hasErrorCode` and `findError` take for an error typed `E`: the codes of the
|
|
93
|
+
* {@link JsonApiError} it holds, such as a query's `error` typed by the operation that raised it,
|
|
94
|
+
* else `C`, every code the server documents.
|
|
95
|
+
*/
|
|
96
|
+
type ErrorCodesFor<E, C extends string> = string extends CodesOf<E, C> ? C : CodesOf<E, C>;
|
|
97
|
+
/**
|
|
98
|
+
* {@link hasErrorCode} restricted to one server's documented codes, or to the codes `err`'s type
|
|
99
|
+
* carries. A generated client binds it:
|
|
87
100
|
* `export const hasErrorCode = hasErrorCodeRuntime as ErrorCodeGuard<ErrorCode>`. The cast is
|
|
88
101
|
* needed because `JsonApiError<string>` doesn't assign to `JsonApiError<ErrorCode>`.
|
|
89
102
|
*/
|
|
90
|
-
type ErrorCodeGuard<C extends string> = (err:
|
|
103
|
+
type ErrorCodeGuard<C extends string> = <E>(err: E, code: ErrorCodesFor<E, C>) => err is E & GuardedError<E, ErrorCodesFor<E, C>>;
|
|
104
|
+
/** What a matched guard narrows `E` to: its {@link JsonApiError} members, or one carrying `K`. */
|
|
105
|
+
type GuardedError<E, K extends string> = [JsonApiErrorOf<E>] extends [never] ? JsonApiError<K> : JsonApiErrorOf<E>;
|
|
91
106
|
/**
|
|
92
107
|
* An error object carrying the documented code `K`, its `meta` typed when the server declares
|
|
93
108
|
* one for the code. `M` is a generated client's `ErrorMetaByCode`; a code it does not list
|
|
@@ -105,11 +120,80 @@ type CodedErrorObject<K extends string, M = {}> = JsonApiErrorObject<K> & {
|
|
|
105
120
|
*/
|
|
106
121
|
declare function findError(err: unknown, code: string): JsonApiErrorObject | undefined;
|
|
107
122
|
/**
|
|
108
|
-
* {@link findError} restricted to one server's documented codes
|
|
109
|
-
* `
|
|
123
|
+
* {@link findError} restricted to one server's documented codes and their declared `meta`, or to
|
|
124
|
+
* the codes `err`'s type carries. A generated client binds it:
|
|
110
125
|
* `export const findError = findErrorRuntime as ErrorFinder<ErrorCode, ErrorMetaByCode>`.
|
|
111
126
|
*/
|
|
112
|
-
type ErrorFinder<C extends string, M = {}> = <K extends C
|
|
127
|
+
type ErrorFinder<C extends string, M = {}> = <E, K extends ErrorCodesFor<E, C>>(err: E, code: K) => CodedErrorObject<K, M> | undefined;
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/field-errors.d.ts
|
|
130
|
+
/** One segment of a Standard Schema issue path: a key, or an array index. */
|
|
131
|
+
type PathSegment = string | number;
|
|
132
|
+
/**
|
|
133
|
+
* One error shaped as a Standard Schema issue (`message` plus `path` segments), so a form library
|
|
134
|
+
* that takes Standard Schema issues takes it as is.
|
|
135
|
+
*/
|
|
136
|
+
interface FieldError<C extends string = string> {
|
|
137
|
+
/** The error's `detail`, else its `title`, else its `code`. */
|
|
138
|
+
readonly message: string;
|
|
139
|
+
/** The input path as segments: `orderedTracks[0].$pivot.position` is `['orderedTracks', 0, '$pivot', 'position']`. Empty for a form-level error. */
|
|
140
|
+
readonly path: readonly PathSegment[];
|
|
141
|
+
/** The input path as the runtime keys it, `''` for a form-level error. */
|
|
142
|
+
readonly key: string;
|
|
143
|
+
readonly code?: C | (string & {});
|
|
144
|
+
/** The failing operation's index in an atomic batch. */
|
|
145
|
+
readonly opIndex?: number;
|
|
146
|
+
/** The error object as the server sent it, with its remapped `path`. Absent for an {@link InputValidationError}'s issue. */
|
|
147
|
+
readonly error?: JsonApiErrorObject<C>;
|
|
148
|
+
}
|
|
149
|
+
/** A write's errors for a form, split into the inputs they point at and the rest. */
|
|
150
|
+
interface FieldErrors<I = unknown, C extends string = string> {
|
|
151
|
+
/** Errors on an input, grouped by its path. */
|
|
152
|
+
readonly fields: Readonly<Record<string, readonly FieldError<C>[]>>;
|
|
153
|
+
/** Errors that point at no input: no `source`, a `source.parameter` or `source.header`, or a pointer the client owns, such as `/data/type`. */
|
|
154
|
+
readonly form: readonly FieldError<C>[];
|
|
155
|
+
/** Every error, in the order the server sent them. */
|
|
156
|
+
readonly issues: readonly FieldError<C>[];
|
|
157
|
+
/** The first message on the input at `path`. */
|
|
158
|
+
first(path: InputPath<I>): string | undefined;
|
|
159
|
+
/** Every message on the input at `path`. */
|
|
160
|
+
messages(path: InputPath<I>): string[];
|
|
161
|
+
/** Only the errors of the atomic operation at `index`. */
|
|
162
|
+
op(index: number): FieldErrors<unknown, C>;
|
|
163
|
+
}
|
|
164
|
+
declare const writeInput: unique symbol;
|
|
165
|
+
/**
|
|
166
|
+
* A {@link JsonApiError} tagged with the input of the write that raised it, at the type level
|
|
167
|
+
* only, so {@link fieldErrors} types its paths without a type argument.
|
|
168
|
+
*/
|
|
169
|
+
type WriteError<C extends string = string, I = unknown> = JsonApiError<C> & {
|
|
170
|
+
readonly [writeInput]?: I;
|
|
171
|
+
};
|
|
172
|
+
type InputOf<E> = [JsonApiErrorOf<E>] extends [never] ? unknown : JsonApiErrorOf<E> extends {
|
|
173
|
+
readonly [writeInput]?: infer I;
|
|
174
|
+
} ? I : unknown;
|
|
175
|
+
type Scalar = string | number | boolean | bigint | symbol | Date;
|
|
176
|
+
/** The next depth down; the paths stop at four levels of nesting. */
|
|
177
|
+
type Deeper = [never, 0, 1, 2, 3];
|
|
178
|
+
/**
|
|
179
|
+
* Every path the runtime can key an error on for write input `I`: attribute keys, nested map
|
|
180
|
+
* keys joined with `.`, to-many members as `[n]` with their `$pivot` fields, `$meta` members, and
|
|
181
|
+
* `$documentMeta` members. A union-typed value contributes only the keys its members share. Any
|
|
182
|
+
* string when `I` is unknown.
|
|
183
|
+
*/
|
|
184
|
+
type InputPath<I> = unknown extends I ? string : KeyPaths<I, 4> | `$documentMeta.${string}`;
|
|
185
|
+
type KeyPaths<T, D extends number> = [D] extends [never] ? never : [T] extends [object] ? { [K in keyof T & string]-?: K | `${K}${SubPaths<NonNullable<T[K]>, D>}` }[keyof T & string] : never;
|
|
186
|
+
type SubPaths<V, D extends number> = [V] extends [never] ? never : [V] extends [readonly (infer M)[]] ? `[${number}]` | `[${number}]${MemberPaths<NonNullable<M>, D>}` : MemberPaths<V, D>;
|
|
187
|
+
type MemberPaths<V, D extends number> = [V] extends [Scalar] ? never : 'type' extends keyof V ? [V] extends [{
|
|
188
|
+
$pivot?: infer P;
|
|
189
|
+
}] ? P extends object ? '.$pivot' | `.$pivot.${keyof P & string}` : never : never : `.${KeyPaths<V, Deeper[D]>}`;
|
|
190
|
+
/**
|
|
191
|
+
* The 4xx `error`'s errors keyed by the write input they point at, or `undefined` when `error`
|
|
192
|
+
* is not a 4xx {@link JsonApiError} or none of its errors points at an input. An
|
|
193
|
+
* {@link InputValidationError} gives its issues the same way. Pass the input type when `error`
|
|
194
|
+
* carries none: `fieldErrors<Parameters<typeof client.albums.create>[0]>(caught)`.
|
|
195
|
+
*/
|
|
196
|
+
declare function fieldErrors<I = never, E = unknown>(error: E): FieldErrors<[I] extends [never] ? InputOf<E> : I, CodesOf<E>> | undefined;
|
|
113
197
|
//#endregion
|
|
114
198
|
//#region src/filters.d.ts
|
|
115
199
|
/** The filter vocabulary {@link listFilterMatcher} reads: a type's, or a collection action's. */
|
|
@@ -332,5 +416,5 @@ declare function withRemappedAtomicPaths(error: JsonApiError, descriptor: ApiDes
|
|
|
332
416
|
hasPivot: boolean;
|
|
333
417
|
} | undefined): JsonApiError;
|
|
334
418
|
//#endregion
|
|
335
|
-
export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, type Accepted, AcceptedDescriptor, AcceptedJob, AcceptedMeta, AcceptedOf, AcceptedOperation, ActionCallOptions, ActionDescriptor, ActionInput, ActionLocation, ActionLocationDescriptor, ActionOutput, ActionScope, ActionsAccessor, AdditionalMembersDescriptor, ApiDescriptor, ApiExamples, ArrayEnvelope, AtomicCreateHandle, AtomicCreateInput, AtomicDeleteHandle, AtomicDescriptor, AtomicHandle, AtomicOperationArgs, AtomicRecorder, AtomicRef, AtomicRelationshipArgs, AtomicRelationshipHandle, AtomicRelationshipRecorder, AtomicResult, AtomicResultOf, AtomicResults, AtomicUpdateHandle, AtomicUpdateInput, BinaryBody, BinaryResponseType, CANONICAL_PAGE_KEYS, Cardinality, Client, ClientIdPolicy, ClientOptions, CodedErrorObject, Collection, CollectionMeta, CountAccessor, CountToken, CountableDescriptor, CountedRelationName, CreateAttributesOf, CreateInput, CreateMethod, DefaultActionTypes, DefaultAttributes, DefaultWriteAttributes, DeleteArgs, DeleteResult, Document, DocumentEnvelope, DocumentMeta, DocumentMetaDescriptor, DocumentMetaOperation, Edge, EdgeEnvelope, EdgeMember, EdgeMembers, ErrorCodeGuard, ErrorCodeOf, ErrorFinder, ExactPageParams, ExecutedResponse, FieldSelectionMap, FieldsMap, FilterFamilyDescriptor, FilterKey, FilterQuery, FilterSpec, HANDLE_RESERVED, HeadersInit, HydratedMember, IdentifierMember, IncludePath, IncludedRelations, IncludedResource, IncludedType, InputMedia, InputMediaKind, IsSingleton, JSON_API_MEDIA_TYPE, JsonApiContext, JsonApiError, JsonApiErrorObject, JsonApiRequest, JsonApiTransport, Link, LinkObject, LinkageRef, ListFilterMember, ListPageParams, LoadAllOptions, LocalIdentifier, LooseRelatedQuery, LooseRelatedQueryEntry, MaterialiseContext, MaterialisedOverlay, MediaExamples, MediaTypeParams, MemberName, MemberTypeOf, MenuDescriptor, MetaLiteral, MetaObject, MetaOption, MutationMetaOf, MutationVerb, NavigateOptions, type NestedFieldset, NestedFieldsetMember, OperationExamples, OperationMeta, OptionsArg, Page, PageKeys, PageLinks, PageMeta, PageOf, PageParams, PageParamsOf, PaginatorDescriptor, PaginatorKind, PaginatorRole, PaginatorStrategy, PendingCreate, PendingMember, PendingPlacement, PivotDescriptor, PivotFieldsOf, PivotInput, type PollOptions, PollTimeoutError, RawMediaKind, RawOutputMedia, RawResponseType, ReadAttributesOf, ReadQuery, ReadResult, ReadableRelationName, RelatedIncludedResource, RelatedIncludedType, RelatedMeta, RelatedQuery, RelatedQueryDescriptor, RelatedQueryEntry, RelatedQueryOperation, RelatedQueryParam, RelatedQueryRelation, RelatedReadRelatedQuery, RelationArrayEnvelope, RelationCollection, RelationDescriptor, RelationFilterQuery, RelationMutations, RelationName, RelationPageParams, RelationPaginator, RelationReadQuery, RelationRequestMetaOf, RelationSortQuery, RelationView, RelationshipAccessor, RelationshipDocument, RelationshipMembers, RequestMetaOf, RequestMetaOperation, RequiresRequestMeta, ResolvedPaginator, ResolvedValidator, ResourceAccessors, ResourceCountOperation, ResourceCountToken, ResourceDescriptor, ResourceEnvelope, ResourceExamples, ResourceHandle, ResourceIdentifier, ResourceLinks, ResourceMetaDescriptor, ResourceMetaOf, ResourceObjectView, ResourceWriteMeta, ResourceWriteOperation, SchemaMap, SingleReadQuery, SingletonAccessor, SingletonUpdateInput, SortFamilyDescriptor, SortQuery, SortToken, StrategyDescriptor, StructuralGuardError, TakesVerb, ToDocumentOptions, TransportRawBody, TransportRequest, TransportResponse, TypeAccessor, TypeName, TypedPage, TypedReadQuery, TypedRelatedReadQuery, TypedRelationReadQuery, UpdateInput, UpdateMethod, ValidationConfig, ValidationContext, ValidationOption, Validator, WaitOptions, WaitValue, WaitedWriteResult, WireResource, WithDocumentMeta, WithLinks, WritableRelationName, WriteDocument, WriteOptions, WritePivotOf, WriteResult, assertJsonApiDocument, createClient, edgeViewOf, execute, executeRaw, executeResponse, fetchTransport, findError, hasErrorCode, identifierViewOf, isAccepted, isActionLocation, isMaterialised, isPolymorphic, listFilterMatcher, loadAll, materialise, mediaType, nestedFieldset, nextPageParams, nextRequestStamp, parseRetryAfter, prevPageParams, readActionLocation, relatedPaginator, relatedPaginatorKind, remapPointer, remapRelationshipPointer, requestStampOf, resolvePaginator, resolveValidator, runAtomic, serializeQuery, setMaterialisedOverlay, sparseSchema, sparseSchemas, toDocument, toRelationshipDocument, validateDocument, withRemappedAtomicPaths, withRemappedDocumentMetaPaths, withRemappedPaths, withRemappedRelationshipPaths, withTopLevelMeta };
|
|
419
|
+
export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, type Accepted, AcceptedDescriptor, AcceptedJob, AcceptedMeta, AcceptedOf, AcceptedOperation, ActionCallOptions, ActionDescriptor, ActionInput, ActionLocation, ActionLocationDescriptor, ActionOutput, ActionScope, ActionsAccessor, AdditionalMembersDescriptor, ApiDescriptor, ApiExamples, ArrayEnvelope, AtomicCreateHandle, AtomicCreateInput, AtomicDeleteHandle, AtomicDescriptor, AtomicHandle, AtomicOperationArgs, AtomicRecorder, AtomicRef, AtomicRelationshipArgs, AtomicRelationshipHandle, AtomicRelationshipRecorder, AtomicResult, AtomicResultOf, AtomicResults, AtomicUpdateHandle, AtomicUpdateInput, BinaryBody, BinaryResponseType, CANONICAL_PAGE_KEYS, Cardinality, Client, ClientIdPolicy, ClientOptions, CodedErrorObject, Collection, CollectionMeta, CountAccessor, CountToken, CountableDescriptor, CountedRelationName, CreateAttributesOf, CreateInput, CreateMethod, DefaultActionTypes, DefaultAttributes, DefaultWriteAttributes, DeleteArgs, DeleteResult, Document, DocumentEnvelope, DocumentMeta, DocumentMetaDescriptor, DocumentMetaOperation, Edge, EdgeEnvelope, EdgeMember, EdgeMembers, ErrorCodeCarrier, ErrorCodeGuard, ErrorCodeOf, ErrorCodesFor, ErrorFinder, ExactPageParams, ExecutedResponse, FieldError, FieldErrors, FieldSelectionMap, FieldsMap, FilterFamilyDescriptor, FilterKey, FilterQuery, FilterSpec, HANDLE_RESERVED, HeadersInit, HydratedMember, IdentifierMember, IncludePath, IncludedRelations, IncludedResource, IncludedType, InputCheck, InputMedia, InputMediaKind, InputPath, InputSchemas, InputValidationError, IsSingleton, JSON_API_MEDIA_TYPE, JsonApiContext, JsonApiError, JsonApiErrorObject, JsonApiRequest, JsonApiTransport, Link, LinkObject, LinkageRef, ListFilterMember, ListPageParams, LoadAllOptions, LocalIdentifier, LooseRelatedQuery, LooseRelatedQueryEntry, MaterialiseContext, MaterialisedOverlay, MediaExamples, MediaTypeParams, MemberName, MemberTypeOf, MenuDescriptor, MetaLiteral, MetaObject, MetaOption, MutationMetaOf, MutationVerb, NavigateOptions, type NestedFieldset, NestedFieldsetMember, OperationCodes, OperationErrorCodeOf, OperationExamples, OperationMeta, OptionsArg, Page, PageKeys, PageLinks, PageMeta, PageOf, PageParams, PageParamsOf, PaginatorDescriptor, PaginatorKind, PaginatorRole, PaginatorStrategy, PathSegment, PendingCreate, PendingEdge, PendingMember, PendingPivotOf, PendingPlacement, PivotDescriptor, PivotFieldsOf, PivotInput, type PollOptions, PollTimeoutError, RawMediaKind, RawOutputMedia, RawResponseType, ReadAttributesOf, ReadQuery, ReadResult, ReadableRelationName, RelatedIncludedResource, RelatedIncludedType, RelatedMeta, RelatedQuery, RelatedQueryDescriptor, RelatedQueryEntry, RelatedQueryOperation, RelatedQueryParam, RelatedQueryRelation, RelatedReadRelatedQuery, RelationArrayEnvelope, RelationCollection, RelationDescriptor, RelationFilterQuery, RelationMutations, RelationName, RelationPageParams, RelationPaginator, RelationReadQuery, RelationRequestMetaOf, RelationSortQuery, RelationView, RelationshipAccessor, RelationshipDocument, RelationshipMembers, RequestMetaOf, RequestMetaOperation, RequiresRequestMeta, ResolvedPaginator, ResolvedValidator, ResourceAccessors, ResourceCountOperation, ResourceCountToken, ResourceDescriptor, ResourceEnvelope, ResourceExamples, ResourceHandle, ResourceIdentifier, ResourceLinks, ResourceMetaDescriptor, ResourceMetaOf, ResourceObjectView, ResourceWriteMeta, ResourceWriteOperation, SchemaMap, SingleReadQuery, SingletonAccessor, SingletonUpdateInput, SortFamilyDescriptor, SortQuery, SortToken, StandardSchema, StandardSchemaIssue, StandardSchemaResult, StrategyDescriptor, StructuralGuardError, TakesVerb, ToDocumentOptions, TransportRawBody, TransportRequest, TransportResponse, TypeAccessor, TypeName, TypedPage, TypedReadQuery, TypedRelatedReadQuery, TypedRelationReadQuery, UpdateInput, UpdateMethod, ValidationConfig, ValidationContext, ValidationOption, Validator, WaitOptions, WaitValue, WaitedWriteResult, WireResource, WithDocumentMeta, WithLinks, WritableRelationName, WriteDocument, WriteError, WriteOptions, WritePivotOf, WriteResult, assertJsonApiDocument, createClient, edgeViewOf, execute, executeRaw, executeResponse, fetchTransport, fieldErrors, findError, hasErrorCode, identifierViewOf, inputFailure, isAccepted, isActionLocation, isMaterialised, isPolymorphic, listFilterMatcher, loadAll, materialise, mediaType, nestedFieldset, nextPageParams, nextRequestStamp, parseRetryAfter, prevPageParams, readActionLocation, relatedPaginator, relatedPaginatorKind, remapPointer, remapRelationshipPointer, requestStampOf, resolvePaginator, resolveValidator, runAtomic, serializeQuery, setMaterialisedOverlay, sparseSchema, sparseSchemas, toDocument, toRelationshipDocument, validateDocument, withInputCheck, withRemappedAtomicPaths, withRemappedDocumentMetaPaths, withRemappedPaths, withRemappedRelationshipPaths, withTopLevelMeta };
|
|
336
420
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/errors.ts","../src/filters.ts","../src/load-all.ts","../src/request-stamp.ts","../src/serialize-write.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/error-shared.ts","../src/errors.ts","../src/field-errors.ts","../src/filters.ts","../src/load-all.ts","../src/request-stamp.ts","../src/serialize-write.ts"],"mappings":";;;;KAGY,cAAA,MAAoB,OAAA,CAAQ,WAAA,CAAY,CAAA,GAAI,YAAA;AAAxD;AAAA,KAGY,OAAA,yCAAgD,cAAA,CAAe,CAAA,qBACvE,QAAA,GACA,cAAA,CAAe,CAAA,UAAW,YAAA,YACxB,CAAA,GACA,QAAA;;;;;AAPN;;;;;UCMiB,kBAAA;EACf,EAAA;EACA,MAAA;EACA,IAAA,GAAO,CAAA;EACP,KAAA;EACA,MAAA;EACA,MAAA;IAAW,OAAA;IAAkB,SAAA;IAAoB,MAAA;EAAA;EACjD,IAAA,GAAO,MAAM;EDVI;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AAA;;UAID,iBAAA;;;;ALjEjB;;EKuEE,EAAE;AAAA;;;;;;;;;;;;;;;;iBAkBY,UAAA,CACd,UAAA,EAAY,aAAA,EACZ,IAAA,UACA,KAAA,EAAO,MAAA,mBACP,IAAA,GAAO,iBAAA,GACN,aAAA;AL3EM;AAUT;;;AAVS,iBKyHO,gBAAA,qBACd,GAAA,EAAK,GAAA,EACL,IAAA,EAAM,QAAA,CAAS,MAAA,iCACd,GAAA;EAAQ,IAAA,GAAO,QAAA,CAAS,MAAA;AAAA;;;ALjHE;AA+B7B;;;;;;;;;iBKkGgB,sBAAA,CACd,IAAA,WACA,WAAA,mBACC,oBAAoB;;;;;;;;;;;;;;;;;;;;;iBA6FP,YAAA,CAAa,UAAA,EAAY,aAAa,EAAE,IAAA,UAAc,OAAA;;;;;;;;;;;;;;AL7HvB;AAgB/C;;;;iBK4LgB,wBAAA,CAAyB,GAAA,UAAa,QAAA,WAAmB,OAAA;;;;;AL5LI;AAS7E;iBKqMgB,iBAAA,CACd,KAAA,EAAO,YAAA,EACP,UAAA,EAAY,aAAA,EACZ,IAAA,WACC,YAAA;;;;;;;;iBAWa,6BAAA,CACd,KAAA,EAAO,YAAA,EACP,GAAA,UACA,QAAA,YACC,YAAY;;;;;;;iBAUC,6BAAA,CAA8B,KAAA,EAAO,YAAA,GAAe,YAAY;;;;;;ALlOgB;AAQhG;;;;;iBKgPgB,uBAAA,CACd,KAAA,EAAO,YAAA,EACP,UAAA,EAAY,aAAA,EACZ,SAAA,GAAY,OAAA,iCACZ,aAAA,IAAiB,OAAA;EAAsB,GAAA;EAAa,QAAA;AAAA,gBACnD,YAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as validateDocument, c as JsonApiError, d as hasErrorCode, i as sparseSchemas, l as StructuralGuardError, n as resolveValidator, o as fieldsOfUrl, r as sparseSchema, s as nestedFieldset, t as assertJsonApiDocument, u as findError } from "./validate-
|
|
1
|
+
import { a as validateDocument, c as JsonApiError, d as hasErrorCode, f as errorText, i as sparseSchemas, l as StructuralGuardError, n as resolveValidator, o as fieldsOfUrl, r as sparseSchema, s as nestedFieldset, t as assertJsonApiDocument, u as findError } from "./validate-BuPAPJMi.mjs";
|
|
2
2
|
//#region src/request-stamp.ts
|
|
3
3
|
/**
|
|
4
4
|
* Request stamps: when the request behind a result started, relative to every other request made in
|
|
@@ -943,6 +943,63 @@ function relatedPaginatorKind(relation, ctx) {
|
|
|
943
943
|
return resolvePaginator(relatedPaginator(relation, ctx)).kind;
|
|
944
944
|
}
|
|
945
945
|
//#endregion
|
|
946
|
+
//#region src/input-validation.ts
|
|
947
|
+
/**
|
|
948
|
+
* Thrown by a create or update whose input fails the schema `validateInput` holds for it, before
|
|
949
|
+
* any request is sent. `fieldErrors(error)` takes it as it takes a server's 422.
|
|
950
|
+
*/
|
|
951
|
+
var InputValidationError = class extends Error {
|
|
952
|
+
type;
|
|
953
|
+
operation;
|
|
954
|
+
issues;
|
|
955
|
+
/** The failing operation's index in an atomic batch. */
|
|
956
|
+
opIndex;
|
|
957
|
+
constructor(type, operation, issues, opIndex) {
|
|
958
|
+
const first = issues[0]?.message;
|
|
959
|
+
super(`The ${type} ${operation} input${opIndex === void 0 ? "" : ` of atomic operation ${opIndex}`} is invalid` + (first === void 0 ? "" : `: ${first}`) + (issues.length > 1 ? ` (and ${issues.length - 1} more)` : ""));
|
|
960
|
+
this.name = "InputValidationError";
|
|
961
|
+
this.type = type;
|
|
962
|
+
this.operation = operation;
|
|
963
|
+
this.issues = issues;
|
|
964
|
+
if (opIndex !== void 0) this.opIndex = opIndex;
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
/**
|
|
968
|
+
* The {@link InputValidationError} `check`'s input fails its schema in `schemas` with, or
|
|
969
|
+
* `undefined` when it passes or has no schema. A Promise only for a schema that validates
|
|
970
|
+
* asynchronously.
|
|
971
|
+
*/
|
|
972
|
+
function inputFailure(schemas, check) {
|
|
973
|
+
const schema = schemas?.[check.type]?.[check.operation];
|
|
974
|
+
if (schema === void 0) return;
|
|
975
|
+
const failure = (result) => result.issues === void 0 ? void 0 : new InputValidationError(check.type, check.operation, result.issues, check.opIndex);
|
|
976
|
+
const result = schema["~standard"].validate(check.input);
|
|
977
|
+
return result instanceof Promise ? result.then(failure) : failure(result);
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* Run `write` once `check`'s input passes its schema, else reject with the
|
|
981
|
+
* {@link InputValidationError}. A write with no schema, or a schema that validates synchronously,
|
|
982
|
+
* starts in this tick.
|
|
983
|
+
*/
|
|
984
|
+
function withInputCheck(schemas, check, write) {
|
|
985
|
+
const proceed = (failure) => failure === void 0 ? write() : Promise.reject(failure);
|
|
986
|
+
const failure = inputFailure(schemas, check);
|
|
987
|
+
return failure instanceof Promise ? failure.then(proceed) : proceed(failure);
|
|
988
|
+
}
|
|
989
|
+
//#endregion
|
|
990
|
+
//#region src/input-path.ts
|
|
991
|
+
/**
|
|
992
|
+
* The flat input-path key format: `.` between names, `[n]` for a to-many member's index, as in
|
|
993
|
+
* `orderedTracks[0].$pivot.position`. `byPath()` and `fieldErrors()` key errors by it.
|
|
994
|
+
*/
|
|
995
|
+
function joinInputPath(segments) {
|
|
996
|
+
return segments.map((segment, i) => typeof segment === "number" ? `[${segment}]` : i === 0 ? segment : `.${segment}`).join("");
|
|
997
|
+
}
|
|
998
|
+
/** The segments of a flat input-path key: `a[0].b` is `['a', 0, 'b']`. */
|
|
999
|
+
function splitInputPath(key) {
|
|
1000
|
+
return Array.from(key.matchAll(/([^.[\]]+)|\[(\d+)\]/g), ([, name, index]) => index === void 0 ? name : Number(index));
|
|
1001
|
+
}
|
|
1002
|
+
//#endregion
|
|
946
1003
|
//#region src/serialize-write.ts
|
|
947
1004
|
/** Per-edge writable pivot data, supplied on a to-many member as the `$pivot` key. */
|
|
948
1005
|
const PIVOT_KEY = "$pivot";
|
|
@@ -955,7 +1012,11 @@ const META_KEY = "$meta";
|
|
|
955
1012
|
const DOCUMENT_META_KEY = "$documentMeta";
|
|
956
1013
|
/** The flat path of a pointer into the request document's top-level `meta`, else `undefined`. */
|
|
957
1014
|
function documentMetaPath(segments) {
|
|
958
|
-
return segments[0] === "meta" ? [DOCUMENT_META_KEY, ...segments.slice(1)]
|
|
1015
|
+
return segments[0] === "meta" ? pointerPath([DOCUMENT_META_KEY, ...segments.slice(1)]) : void 0;
|
|
1016
|
+
}
|
|
1017
|
+
/** Pointer segments as a flat input path, a numeric segment indexing an array: `tags[0]`. */
|
|
1018
|
+
function pointerPath(segments) {
|
|
1019
|
+
return joinInputPath(segments.map((s) => /^\d+$/.test(s) ? Number(s) : s));
|
|
959
1020
|
}
|
|
960
1021
|
/** The reserved input keys never routed to attributes/relationships. */
|
|
961
1022
|
const RESERVED_INPUT = /* @__PURE__ */ new Set(["type", "id"]);
|
|
@@ -1083,16 +1144,12 @@ const describe = (value) => value === null ? "null" : Array.isArray(value) ? "an
|
|
|
1083
1144
|
function remapPointer(descriptor, type, pointer) {
|
|
1084
1145
|
const segments = pointer.split("/").filter((s) => s !== "");
|
|
1085
1146
|
if (segments[0] !== "data") return documentMetaPath(segments) ?? pointer;
|
|
1086
|
-
if (segments[1] === "meta") return [META_KEY, ...segments.slice(2)]
|
|
1087
|
-
if (segments[1] === "attributes") return
|
|
1147
|
+
if (segments[1] === "meta") return pointerPath([META_KEY, ...segments.slice(2)]);
|
|
1148
|
+
if (segments[1] === "attributes") return pointerPath(segments.slice(2));
|
|
1088
1149
|
if (segments[1] === "id") return "id";
|
|
1089
1150
|
if (segments[1] === "relationships") return remapRelationship(descriptor[type]?.relations ?? {}, segments.slice(2));
|
|
1090
1151
|
return pointer;
|
|
1091
1152
|
}
|
|
1092
|
-
/** `[releaseInfo, label]` -> `releaseInfo.label`; a bare `[title]` -> `title`. */
|
|
1093
|
-
function remapAttribute(rest) {
|
|
1094
|
-
return rest.join(".");
|
|
1095
|
-
}
|
|
1096
1153
|
/**
|
|
1097
1154
|
* Remap a relationship pointer's tail (everything after `relationships/`, or — for a
|
|
1098
1155
|
* relationship-endpoint document — the relation name spliced ahead of the `data` tail). The
|
|
@@ -1105,17 +1162,17 @@ function remapRelationship(relations, rest) {
|
|
|
1105
1162
|
const name = rest[0];
|
|
1106
1163
|
if (name === void 0) return "data/relationships";
|
|
1107
1164
|
const hasPivot = relations[name]?.pivot === true;
|
|
1108
|
-
|
|
1165
|
+
const path = [name];
|
|
1109
1166
|
for (let i = 1; i < rest.length; i++) {
|
|
1110
1167
|
const seg = rest[i];
|
|
1111
1168
|
if (seg === "data") continue;
|
|
1112
|
-
if (/^\d+$/.test(seg)) path
|
|
1169
|
+
if (/^\d+$/.test(seg)) path.push(Number(seg));
|
|
1113
1170
|
else if (seg === "meta" && hasPivot && rest[i + 1] === "pivot") {
|
|
1114
|
-
path
|
|
1171
|
+
path.push("$pivot");
|
|
1115
1172
|
i++;
|
|
1116
|
-
} else path
|
|
1173
|
+
} else path.push(seg);
|
|
1117
1174
|
}
|
|
1118
|
-
return path;
|
|
1175
|
+
return joinInputPath(path);
|
|
1119
1176
|
}
|
|
1120
1177
|
/**
|
|
1121
1178
|
* Invert a relationship-MUTATION error's `source.pointer` to the caller's flat path, for the
|
|
@@ -1236,8 +1293,10 @@ const withOperationMeta = (operation, opts) => opts?.meta === void 0 ? operation
|
|
|
1236
1293
|
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1237
1294
|
/** The deterministic local id for the create at `opIndex` (stable + human-readable). */
|
|
1238
1295
|
const lidFor = (opIndex) => `atomic-${opIndex}`;
|
|
1239
|
-
async function runAtomic(request, materialiseCtx, descriptor, path, build) {
|
|
1296
|
+
async function runAtomic(request, materialiseCtx, descriptor, path, build, inputSchemas) {
|
|
1240
1297
|
const operations = [];
|
|
1298
|
+
/** Each create and update input, checked against `inputSchemas` before the batch is sent. */
|
|
1299
|
+
const checks = [];
|
|
1241
1300
|
/** The wire type of each op, by index — drives the error-pointer remap. */
|
|
1242
1301
|
const typeByOp = [];
|
|
1243
1302
|
/** The relation each relationship op writes, by index, which its pointers are remapped under. */
|
|
@@ -1271,6 +1330,13 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
|
|
|
1271
1330
|
const opIndex = operations.length;
|
|
1272
1331
|
const lid = lidFor(opIndex);
|
|
1273
1332
|
const data = atomicResourceData(descriptor, input, { lid });
|
|
1333
|
+
const { type: _type, ...fields } = input;
|
|
1334
|
+
checks.push({
|
|
1335
|
+
type: input.type,
|
|
1336
|
+
operation: "create",
|
|
1337
|
+
input: fields,
|
|
1338
|
+
opIndex
|
|
1339
|
+
});
|
|
1274
1340
|
operations.push(withOperationMeta({
|
|
1275
1341
|
op: "add",
|
|
1276
1342
|
data
|
|
@@ -1287,6 +1353,14 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
|
|
|
1287
1353
|
const opIndex = operations.length;
|
|
1288
1354
|
const identity = input.id !== void 0 ? { id: input.id } : { lid: input.lid };
|
|
1289
1355
|
const data = atomicResourceData(descriptor, input, identity);
|
|
1356
|
+
const { type: _type, lid: _lid, ...fields } = input;
|
|
1357
|
+
const { id: _id, ...patch } = fields;
|
|
1358
|
+
checks.push({
|
|
1359
|
+
type: input.type,
|
|
1360
|
+
operation: "update",
|
|
1361
|
+
input: descriptor[input.type]?.singleton === true ? fields : patch,
|
|
1362
|
+
opIndex
|
|
1363
|
+
});
|
|
1290
1364
|
operations.push(withOperationMeta({
|
|
1291
1365
|
op: "update",
|
|
1292
1366
|
ref: {
|
|
@@ -1330,6 +1404,10 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
|
|
|
1330
1404
|
};
|
|
1331
1405
|
}
|
|
1332
1406
|
});
|
|
1407
|
+
for (const check of checks) {
|
|
1408
|
+
const failure = await inputFailure(inputSchemas, check);
|
|
1409
|
+
if (failure !== void 0) throw failure;
|
|
1410
|
+
}
|
|
1333
1411
|
const req = {
|
|
1334
1412
|
method: "POST",
|
|
1335
1413
|
path,
|
|
@@ -1961,7 +2039,11 @@ const HANDLE_RESERVED = /* @__PURE__ */ new Set([
|
|
|
1961
2039
|
* the one the body carries.
|
|
1962
2040
|
*/
|
|
1963
2041
|
function runUpdate(ctx, type, vars, id, patch, opts) {
|
|
1964
|
-
return
|
|
2042
|
+
return withInputCheck(ctx.inputSchemas, {
|
|
2043
|
+
type,
|
|
2044
|
+
operation: "update",
|
|
2045
|
+
input: patch
|
|
2046
|
+
}, () => runWrite(ctx, {
|
|
1965
2047
|
type,
|
|
1966
2048
|
operation: "update",
|
|
1967
2049
|
vars,
|
|
@@ -1971,7 +2053,7 @@ function runUpdate(ctx, type, vars, id, patch, opts) {
|
|
|
1971
2053
|
remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
|
|
1972
2054
|
accepted: ctx.descriptor[type]?.accepted?.update,
|
|
1973
2055
|
wait: waitOptions(opts?.wait)
|
|
1974
|
-
});
|
|
2056
|
+
}));
|
|
1975
2057
|
}
|
|
1976
2058
|
/**
|
|
1977
2059
|
* Wrap a handle's verbs in a Proxy resolving each relation not shadowed by a reserved member to
|
|
@@ -2029,7 +2111,11 @@ function typeAccessor(ctx, type) {
|
|
|
2029
2111
|
return {
|
|
2030
2112
|
list: (query) => run(ctx, type, "fetchMany", {}, query),
|
|
2031
2113
|
get: (id, query) => run(ctx, type, "fetchOne", { id }, query),
|
|
2032
|
-
create: (input, opts) =>
|
|
2114
|
+
create: (input, opts) => withInputCheck(ctx.inputSchemas, {
|
|
2115
|
+
type,
|
|
2116
|
+
operation: "create",
|
|
2117
|
+
input
|
|
2118
|
+
}, () => runWrite(ctx, {
|
|
2033
2119
|
type,
|
|
2034
2120
|
operation: "create",
|
|
2035
2121
|
vars: {},
|
|
@@ -2039,7 +2125,7 @@ function typeAccessor(ctx, type) {
|
|
|
2039
2125
|
remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
|
|
2040
2126
|
accepted: ctx.descriptor[type]?.accepted?.create,
|
|
2041
2127
|
wait: waitOptions(opts?.wait)
|
|
2042
|
-
}),
|
|
2128
|
+
})),
|
|
2043
2129
|
id: (id) => resourceHandle(ctx, type, id),
|
|
2044
2130
|
actions: actionsAccessor(ctx, type, "collection", {})
|
|
2045
2131
|
};
|
|
@@ -2063,6 +2149,7 @@ function createClient(descriptor, options) {
|
|
|
2063
2149
|
const ctx = {
|
|
2064
2150
|
request,
|
|
2065
2151
|
descriptor,
|
|
2152
|
+
...options.validateInput !== void 0 ? { inputSchemas: options.validateInput } : {},
|
|
2066
2153
|
materialise: {
|
|
2067
2154
|
descriptor,
|
|
2068
2155
|
navigate: async (url, linkage = false, paginator, signal) => {
|
|
@@ -2080,7 +2167,7 @@ function createClient(descriptor, options) {
|
|
|
2080
2167
|
const atomicDescriptor = options.atomic ?? null;
|
|
2081
2168
|
const atomic = (build) => {
|
|
2082
2169
|
if (atomicDescriptor === null) throw new Error("This API does not expose an Atomic Operations endpoint");
|
|
2083
|
-
return runAtomic(request, ctx.materialise, descriptor, atomicDescriptor.path, build);
|
|
2170
|
+
return runAtomic(request, ctx.materialise, descriptor, atomicDescriptor.path, build, ctx.inputSchemas);
|
|
2084
2171
|
};
|
|
2085
2172
|
const accessors = /* @__PURE__ */ new Map();
|
|
2086
2173
|
return new Proxy(Object.create(null), {
|
|
@@ -2100,6 +2187,52 @@ function createClient(descriptor, options) {
|
|
|
2100
2187
|
});
|
|
2101
2188
|
}
|
|
2102
2189
|
//#endregion
|
|
2190
|
+
//#region src/field-errors.ts
|
|
2191
|
+
function fieldErrors(error) {
|
|
2192
|
+
if (error instanceof InputValidationError) return group(error.issues.map((issue) => fromIssue(issue, error.opIndex)));
|
|
2193
|
+
if (!(error instanceof JsonApiError) || !error.is4xx()) return;
|
|
2194
|
+
const issues = error.errors.map(toFieldError);
|
|
2195
|
+
return issues.some((issue) => issue.key !== "") ? group(issues) : void 0;
|
|
2196
|
+
}
|
|
2197
|
+
function group(issues) {
|
|
2198
|
+
const fields = {};
|
|
2199
|
+
const form = [];
|
|
2200
|
+
for (const issue of issues) if (issue.key === "") form.push(issue);
|
|
2201
|
+
else (fields[issue.key] ??= []).push(issue);
|
|
2202
|
+
return {
|
|
2203
|
+
fields,
|
|
2204
|
+
form,
|
|
2205
|
+
issues,
|
|
2206
|
+
first: (path) => fields[path]?.[0]?.message,
|
|
2207
|
+
messages: (path) => fields[path]?.map((issue) => issue.message) ?? [],
|
|
2208
|
+
op: (index) => group(issues.filter((issue) => issue.opIndex === index))
|
|
2209
|
+
};
|
|
2210
|
+
}
|
|
2211
|
+
function toFieldError(error) {
|
|
2212
|
+
const key = error.path === void 0 || error.path.startsWith("/") ? "" : error.path;
|
|
2213
|
+
return {
|
|
2214
|
+
message: errorText(error, true) ?? "Invalid",
|
|
2215
|
+
path: splitInputPath(key),
|
|
2216
|
+
key,
|
|
2217
|
+
...error.code === void 0 ? {} : { code: error.code },
|
|
2218
|
+
...error.opIndex === void 0 ? {} : { opIndex: error.opIndex },
|
|
2219
|
+
error
|
|
2220
|
+
};
|
|
2221
|
+
}
|
|
2222
|
+
function fromIssue(issue, opIndex) {
|
|
2223
|
+
const path = (issue.path ?? []).map((segment) => {
|
|
2224
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
2225
|
+
return typeof key === "number" ? key : String(key);
|
|
2226
|
+
});
|
|
2227
|
+
const key = joinInputPath(path);
|
|
2228
|
+
return {
|
|
2229
|
+
message: issue.message,
|
|
2230
|
+
path,
|
|
2231
|
+
key,
|
|
2232
|
+
...opIndex === void 0 ? {} : { opIndex }
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
2235
|
+
//#endregion
|
|
2103
2236
|
//#region src/load-all.ts
|
|
2104
2237
|
/**
|
|
2105
2238
|
* Follow `next` links from a first page until the last, and return every member in one plain
|
|
@@ -2126,6 +2259,6 @@ async function loadAll(first, options = {}) {
|
|
|
2126
2259
|
return all;
|
|
2127
2260
|
}
|
|
2128
2261
|
//#endregion
|
|
2129
|
-
export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, CANONICAL_PAGE_KEYS, HANDLE_RESERVED, JSON_API_MEDIA_TYPE, JsonApiError, PollTimeoutError, StructuralGuardError, assertJsonApiDocument, createClient, edgeViewOf, execute, executeRaw, executeResponse, fetchTransport, findError, hasErrorCode, identifierViewOf, isAccepted, isActionLocation, isMaterialised, isPolymorphic, listFilterMatcher, loadAll, materialise, mediaType, nestedFieldset, nextPageParams, nextRequestStamp, parseRetryAfter, prevPageParams, readActionLocation, relatedPaginator, relatedPaginatorKind, remapPointer, remapRelationshipPointer, requestStampOf, resolvePaginator, resolveValidator, runAtomic, serializeQuery, setMaterialisedOverlay, sparseSchema, sparseSchemas, toDocument, toRelationshipDocument, validateDocument, withRemappedAtomicPaths, withRemappedDocumentMetaPaths, withRemappedPaths, withRemappedRelationshipPaths, withTopLevelMeta };
|
|
2262
|
+
export { ATOMIC_EXT, ATOMIC_MEDIA_TYPE, CANONICAL_PAGE_KEYS, HANDLE_RESERVED, InputValidationError, JSON_API_MEDIA_TYPE, JsonApiError, PollTimeoutError, StructuralGuardError, assertJsonApiDocument, createClient, edgeViewOf, execute, executeRaw, executeResponse, fetchTransport, fieldErrors, findError, hasErrorCode, identifierViewOf, inputFailure, isAccepted, isActionLocation, isMaterialised, isPolymorphic, listFilterMatcher, loadAll, materialise, mediaType, nestedFieldset, nextPageParams, nextRequestStamp, parseRetryAfter, prevPageParams, readActionLocation, relatedPaginator, relatedPaginatorKind, remapPointer, remapRelationshipPointer, requestStampOf, resolvePaginator, resolveValidator, runAtomic, serializeQuery, setMaterialisedOverlay, sparseSchema, sparseSchemas, toDocument, toRelationshipDocument, validateDocument, withInputCheck, withRemappedAtomicPaths, withRemappedDocumentMetaPaths, withRemappedPaths, withRemappedRelationshipPaths, withTopLevelMeta };
|
|
2130
2263
|
|
|
2131
2264
|
//# sourceMappingURL=index.mjs.map
|