@prismicio/client 6.1.1 → 6.4.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/src/client.ts CHANGED
@@ -2,20 +2,24 @@ import * as prismicT from "@prismicio/types";
2
2
  import * as prismicH from "@prismicio/helpers";
3
3
 
4
4
  import { appendPredicates } from "./lib/appendPredicates";
5
+ import { castArray } from "./lib/castArray";
5
6
  import { castThunk } from "./lib/castThunk";
6
7
  import { findMasterRef } from "./lib/findMasterRef";
7
8
  import { findRefByID } from "./lib/findRefByID";
8
9
  import { findRefByLabel } from "./lib/findRefByLabel";
9
10
  import { getCookie } from "./lib/getCookie";
11
+ import { minifyGraphQLQuery } from "./lib/minifyGraphQLQuery";
10
12
 
11
- import { FetchLike, HttpRequestLike } from "./types";
12
- import { buildQueryURL, BuildQueryURLArgs } from "./buildQueryURL";
13
+ import * as cookie from "./cookie";
14
+ import { AbortSignalLike, FetchLike, HttpRequestLike } from "./types";
13
15
  import { ForbiddenError } from "./ForbiddenError";
16
+ import { NotFoundError } from "./NotFoundError";
14
17
  import { ParsingError } from "./ParsingError";
15
18
  import { PrismicError } from "./PrismicError";
19
+ import { buildQueryURL, BuildQueryURLArgs } from "./buildQueryURL";
20
+ import { getRepositoryEndpoint } from "./getRepositoryEndpoint";
21
+ import { isRepositoryEndpoint } from "./isRepositoryEndpoint";
16
22
  import { predicate } from "./predicate";
17
- import * as cookie from "./cookie";
18
- import { NotFoundError } from "./NotFoundError";
19
23
 
20
24
  /**
21
25
  * The largest page size allowed by the Prismic REST API V2. This value is used
@@ -148,6 +152,20 @@ export type ClientConfig = {
148
152
  fetch?: FetchLike;
149
153
  };
150
154
 
155
+ /**
156
+ * Parameters for any client method that use `fetch()`. Only a subset of
157
+ * `fetch()` parameters are exposed.
158
+ */
159
+ type FetchParams = {
160
+ /**
161
+ * An `AbortSignal` provided by an `AbortController`. This allows the network
162
+ * request to be cancelled if necessary.
163
+ *
164
+ * {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal}
165
+ */
166
+ signal?: AbortSignalLike;
167
+ };
168
+
151
169
  /**
152
170
  * Parameters specific to client methods that fetch all documents. These methods
153
171
  * start with `getAll` (for example, `getAllByType`).
@@ -163,11 +181,11 @@ type GetAllParams = {
163
181
  /**
164
182
  * Arguments to determine how the URL for a preview session is resolved.
165
183
  */
166
- type ResolvePreviewArgs = {
184
+ type ResolvePreviewArgs<LinkResolverReturnType> = {
167
185
  /**
168
186
  * A function that maps a Prismic document to a URL within your app.
169
187
  */
170
- linkResolver?: prismicH.LinkResolverFunction;
188
+ linkResolver?: prismicH.LinkResolverFunction<LinkResolverReturnType>;
171
189
 
172
190
  /**
173
191
  * A fallback URL if the Link Resolver does not return a value.
@@ -205,7 +223,7 @@ const typePredicate = (documentType: string): string =>
205
223
  * @returns A predicate that can be used in a Prismic REST API V2 request.
206
224
  */
207
225
  const everyTagPredicate = (tags: string | string[]): string =>
208
- predicate.at("document.tags", tags);
226
+ predicate.at("document.tags", castArray(tags));
209
227
 
210
228
  /**
211
229
  * Creates a predicate to filter content by document tags. At least one matching
@@ -216,13 +234,23 @@ const everyTagPredicate = (tags: string | string[]): string =>
216
234
  * @returns A predicate that can be used in a Prismic REST API V2 request.
217
235
  */
218
236
  const someTagsPredicate = (tags: string | string[]): string =>
219
- predicate.any("document.tags", tags);
237
+ predicate.any("document.tags", castArray(tags));
220
238
 
221
239
  /**
222
240
  * Creates a Prismic client that can be used to query a repository.
223
241
  *
224
- * @param endpoint - The Prismic REST API V2 endpoint for the repository (use
225
- * `prismic.getEndpoint` for the default endpoint).
242
+ * @example
243
+ *
244
+ * ```ts
245
+ * // With a repository name.
246
+ * createClient("qwerty");
247
+ *
248
+ * // Or with a full Prismic Rest API V2 endpoint.
249
+ * createClient("https://qwerty.cdn.prismic.io/api/v2");
250
+ * ```
251
+ *
252
+ * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
253
+ * API V2 endpoint for the repository.
226
254
  * @param options - Configuration that determines how content will be queried
227
255
  * from the Prismic repository.
228
256
  *
@@ -242,7 +270,7 @@ export const createClient = (
242
270
  export class Client {
243
271
  /**
244
272
  * The Prismic REST API V2 endpoint for the repository (use
245
- * `prismic.getEndpoint` for the default endpoint).
273
+ * `prismic.getRepositoryEndpoint` for the default endpoint).
246
274
  */
247
275
  endpoint: string;
248
276
 
@@ -303,26 +331,31 @@ export class Client {
303
331
  * such as Node.js, the `fetch` option must be provided as part of the
304
332
  * `options` parameter.
305
333
  *
306
- * @param endpoint - The Prismic REST API V2 endpoint for the repository (use
307
- * `prismic.getEndpoint` to get the default endpoint).
334
+ * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
335
+ * API V2 endpoint for the repository.
308
336
  * @param options - Configuration that determines how content will be queried
309
337
  * from the Prismic repository.
310
338
  *
311
339
  * @returns A client that can query content from the repository.
312
340
  */
313
- constructor(endpoint: string, options: ClientConfig = {}) {
314
- if (
315
- process.env.NODE_ENV === "development" &&
316
- /\.prismic\.io\/(?!api\/v2\/?)/.test(endpoint)
317
- ) {
318
- throw new PrismicError(
319
- "@prismicio/client only supports Prismic Rest API V2. Please use the getEndpoint helper to generate a valid Rest API V2 endpoint URL.",
320
- undefined,
321
- undefined,
322
- );
341
+ constructor(repositoryNameOrEndpoint: string, options: ClientConfig = {}) {
342
+ if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
343
+ if (
344
+ process.env.NODE_ENV === "development" &&
345
+ /\.prismic\.io\/(?!api\/v2\/?)/.test(repositoryNameOrEndpoint)
346
+ ) {
347
+ throw new PrismicError(
348
+ "@prismicio/client only supports Prismic Rest API V2. Please provide only the repository name to the first createClient() parameter or use the getRepositoryEndpoint() helper to generate a valid Rest API V2 endpoint URL.",
349
+ undefined,
350
+ undefined,
351
+ );
352
+ }
353
+
354
+ this.endpoint = repositoryNameOrEndpoint;
355
+ } else {
356
+ this.endpoint = getRepositoryEndpoint(repositoryNameOrEndpoint);
323
357
  }
324
358
 
325
- this.endpoint = endpoint;
326
359
  this.accessToken = options.accessToken;
327
360
  this.routes = options.routes;
328
361
  this.defaultParams = options.defaultParams;
@@ -348,7 +381,7 @@ export class Client {
348
381
  this.fetchFn = this.fetchFn.bind(globalThis);
349
382
  }
350
383
 
351
- this.graphqlFetch = this.graphqlFetch.bind(this);
384
+ this.graphQLFetch = this.graphQLFetch.bind(this);
352
385
  }
353
386
 
354
387
  /**
@@ -427,7 +460,7 @@ export class Client {
427
460
  */
428
461
  async query<TDocument extends prismicT.PrismicDocument>(
429
462
  predicates: NonNullable<BuildQueryURLArgs["predicates"]>,
430
- params?: Partial<Omit<BuildQueryURLArgs, "predicates">>,
463
+ params?: Partial<Omit<BuildQueryURLArgs, "predicates">> & FetchParams,
431
464
  ): Promise<prismicT.Query<TDocument>> {
432
465
  const url = await this.buildQueryURL({ ...params, predicates });
433
466
 
@@ -449,7 +482,7 @@ export class Client {
449
482
  * @returns A paginated response containing the result of the query.
450
483
  */
451
484
  async get<TDocument extends prismicT.PrismicDocument>(
452
- params?: Partial<BuildQueryURLArgs>,
485
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
453
486
  ): Promise<prismicT.Query<TDocument>> {
454
487
  const url = await this.buildQueryURL(params);
455
488
 
@@ -471,7 +504,7 @@ export class Client {
471
504
  * The first result of the query, if any.
472
505
  */
473
506
  async getFirst<TDocument extends prismicT.PrismicDocument>(
474
- params?: Partial<BuildQueryURLArgs>,
507
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
475
508
  ): Promise<TDocument> {
476
509
  const url = await this.buildQueryURL(params);
477
510
  const result = await this.fetch<prismicT.Query<TDocument>>(url, params);
@@ -507,12 +540,15 @@ export class Client {
507
540
  * @returns A list of documents matching the query.
508
541
  */
509
542
  async dangerouslyGetAll<TDocument extends prismicT.PrismicDocument>(
510
- params: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams = {},
543
+ params: Partial<Omit<BuildQueryURLArgs, "page">> &
544
+ GetAllParams &
545
+ FetchParams = {},
511
546
  ): Promise<TDocument[]> {
512
547
  const { limit = Infinity, ...actualParams } = params;
513
548
  const resolvedParams = {
514
549
  ...actualParams,
515
- pageSize: actualParams.pageSize || MAX_PAGE_SIZE,
550
+ pageSize:
551
+ actualParams.pageSize || this.defaultParams?.pageSize || MAX_PAGE_SIZE,
516
552
  };
517
553
 
518
554
  const documents: TDocument[] = [];
@@ -557,7 +593,7 @@ export class Client {
557
593
  */
558
594
  async getByID<TDocument extends prismicT.PrismicDocument>(
559
595
  id: string,
560
- params?: Partial<BuildQueryURLArgs>,
596
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
561
597
  ): Promise<TDocument> {
562
598
  return await this.getFirst<TDocument>(
563
599
  appendPredicates(params, predicate.at("document.id", id)),
@@ -589,7 +625,7 @@ export class Client {
589
625
  */
590
626
  async getByIDs<TDocument extends prismicT.PrismicDocument>(
591
627
  ids: string[],
592
- params?: Partial<BuildQueryURLArgs>,
628
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
593
629
  ): Promise<prismicT.Query<TDocument>> {
594
630
  return await this.get<TDocument>(
595
631
  appendPredicates(params, predicate.in("document.id", ids)),
@@ -622,7 +658,7 @@ export class Client {
622
658
  */
623
659
  async getAllByIDs<TDocument extends prismicT.PrismicDocument>(
624
660
  ids: string[],
625
- params?: Partial<BuildQueryURLArgs>,
661
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
626
662
  ): Promise<TDocument[]> {
627
663
  return await this.dangerouslyGetAll<TDocument>(
628
664
  appendPredicates(params, predicate.in("document.id", ids)),
@@ -653,7 +689,7 @@ export class Client {
653
689
  async getByUID<TDocument extends prismicT.PrismicDocument>(
654
690
  documentType: string,
655
691
  uid: string,
656
- params?: Partial<BuildQueryURLArgs>,
692
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
657
693
  ): Promise<TDocument> {
658
694
  return await this.getFirst<TDocument>(
659
695
  appendPredicates(params, [
@@ -690,7 +726,7 @@ export class Client {
690
726
  async getByUIDs<TDocument extends prismicT.PrismicDocument>(
691
727
  documentType: string,
692
728
  uids: string[],
693
- params?: Partial<BuildQueryURLArgs>,
729
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
694
730
  ): Promise<prismicT.Query<TDocument>> {
695
731
  return await this.get<TDocument>(
696
732
  appendPredicates(params, [
@@ -728,7 +764,7 @@ export class Client {
728
764
  async getAllByUIDs<TDocument extends prismicT.PrismicDocument>(
729
765
  documentType: string,
730
766
  uids: string[],
731
- params?: Partial<BuildQueryURLArgs>,
767
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
732
768
  ): Promise<TDocument[]> {
733
769
  return await this.dangerouslyGetAll<TDocument>(
734
770
  appendPredicates(params, [
@@ -760,7 +796,7 @@ export class Client {
760
796
  */
761
797
  async getSingle<TDocument extends prismicT.PrismicDocument>(
762
798
  documentType: string,
763
- params?: Partial<BuildQueryURLArgs>,
799
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
764
800
  ): Promise<TDocument> {
765
801
  return await this.getFirst<TDocument>(
766
802
  appendPredicates(params, typePredicate(documentType)),
@@ -787,7 +823,7 @@ export class Client {
787
823
  */
788
824
  async getByType<TDocument extends prismicT.PrismicDocument>(
789
825
  documentType: string,
790
- params?: Partial<BuildQueryURLArgs>,
826
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
791
827
  ): Promise<prismicT.Query<TDocument>> {
792
828
  return await this.get<TDocument>(
793
829
  appendPredicates(params, typePredicate(documentType)),
@@ -813,7 +849,7 @@ export class Client {
813
849
  */
814
850
  async getAllByType<TDocument extends prismicT.PrismicDocument>(
815
851
  documentType: string,
816
- params?: Partial<Omit<BuildQueryURLArgs, "page">>,
852
+ params?: Partial<Omit<BuildQueryURLArgs, "page">> & FetchParams,
817
853
  ): Promise<TDocument[]> {
818
854
  return await this.dangerouslyGetAll<TDocument>(
819
855
  appendPredicates(params, typePredicate(documentType)),
@@ -839,10 +875,10 @@ export class Client {
839
875
  */
840
876
  async getByTag<TDocument extends prismicT.PrismicDocument>(
841
877
  tag: string,
842
- params?: Partial<BuildQueryURLArgs>,
878
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
843
879
  ): Promise<prismicT.Query<TDocument>> {
844
880
  return await this.get<TDocument>(
845
- appendPredicates(params, everyTagPredicate(tag)),
881
+ appendPredicates(params, someTagsPredicate(tag)),
846
882
  );
847
883
  }
848
884
 
@@ -865,10 +901,10 @@ export class Client {
865
901
  */
866
902
  async getAllByTag<TDocument extends prismicT.PrismicDocument>(
867
903
  tag: string,
868
- params?: Partial<Omit<BuildQueryURLArgs, "page">>,
904
+ params?: Partial<Omit<BuildQueryURLArgs, "page">> & FetchParams,
869
905
  ): Promise<TDocument[]> {
870
906
  return await this.dangerouslyGetAll<TDocument>(
871
- appendPredicates(params, everyTagPredicate(tag)),
907
+ appendPredicates(params, someTagsPredicate(tag)),
872
908
  );
873
909
  }
874
910
 
@@ -890,7 +926,7 @@ export class Client {
890
926
  */
891
927
  async getByEveryTag<TDocument extends prismicT.PrismicDocument>(
892
928
  tags: string[],
893
- params?: Partial<BuildQueryURLArgs>,
929
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
894
930
  ): Promise<prismicT.Query<TDocument>> {
895
931
  return await this.get<TDocument>(
896
932
  appendPredicates(params, everyTagPredicate(tags)),
@@ -917,7 +953,7 @@ export class Client {
917
953
  */
918
954
  async getAllByEveryTag<TDocument extends prismicT.PrismicDocument>(
919
955
  tags: string[],
920
- params?: Partial<Omit<BuildQueryURLArgs, "page">>,
956
+ params?: Partial<Omit<BuildQueryURLArgs, "page">> & FetchParams,
921
957
  ): Promise<TDocument[]> {
922
958
  return await this.dangerouslyGetAll<TDocument>(
923
959
  appendPredicates(params, everyTagPredicate(tags)),
@@ -942,7 +978,7 @@ export class Client {
942
978
  */
943
979
  async getBySomeTags<TDocument extends prismicT.PrismicDocument>(
944
980
  tags: string[],
945
- params?: Partial<BuildQueryURLArgs>,
981
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
946
982
  ): Promise<prismicT.Query<TDocument>> {
947
983
  return await this.get<TDocument>(
948
984
  appendPredicates(params, someTagsPredicate(tags)),
@@ -969,7 +1005,7 @@ export class Client {
969
1005
  */
970
1006
  async getAllBySomeTags<TDocument extends prismicT.PrismicDocument>(
971
1007
  tags: string[],
972
- params?: Partial<Omit<BuildQueryURLArgs, "page">>,
1008
+ params?: Partial<Omit<BuildQueryURLArgs, "page">> & FetchParams,
973
1009
  ): Promise<TDocument[]> {
974
1010
  return await this.dangerouslyGetAll<TDocument>(
975
1011
  appendPredicates(params, someTagsPredicate(tags)),
@@ -982,7 +1018,7 @@ export class Client {
982
1018
  *
983
1019
  * @returns Repository metadata.
984
1020
  */
985
- async getRepository(): Promise<prismicT.Repository> {
1021
+ async getRepository(params?: FetchParams): Promise<prismicT.Repository> {
986
1022
  // TODO: Restore when Authorization header support works in browsers with CORS.
987
1023
  // return await this.fetch<prismicT.Repository>(this.endpoint);
988
1024
 
@@ -992,7 +1028,7 @@ export class Client {
992
1028
  url.searchParams.set("access_token", this.accessToken);
993
1029
  }
994
1030
 
995
- return await this.fetch<prismicT.Repository>(url.toString());
1031
+ return await this.fetch<prismicT.Repository>(url.toString(), params);
996
1032
  }
997
1033
 
998
1034
  /**
@@ -1004,8 +1040,8 @@ export class Client {
1004
1040
  *
1005
1041
  * @returns A list of all refs for the Prismic repository.
1006
1042
  */
1007
- async getRefs(): Promise<prismicT.Ref[]> {
1008
- const repository = await this.getRepository();
1043
+ async getRefs(params?: FetchParams): Promise<prismicT.Ref[]> {
1044
+ const repository = await this.getRepository(params);
1009
1045
 
1010
1046
  return repository.refs;
1011
1047
  }
@@ -1017,8 +1053,8 @@ export class Client {
1017
1053
  *
1018
1054
  * @returns The ref with a matching ID, if it exists.
1019
1055
  */
1020
- async getRefByID(id: string): Promise<prismicT.Ref> {
1021
- const refs = await this.getRefs();
1056
+ async getRefByID(id: string, params?: FetchParams): Promise<prismicT.Ref> {
1057
+ const refs = await this.getRefs(params);
1022
1058
 
1023
1059
  return findRefByID(refs, id);
1024
1060
  }
@@ -1030,8 +1066,11 @@ export class Client {
1030
1066
  *
1031
1067
  * @returns The ref with a matching label, if it exists.
1032
1068
  */
1033
- async getRefByLabel(label: string): Promise<prismicT.Ref> {
1034
- const refs = await this.getRefs();
1069
+ async getRefByLabel(
1070
+ label: string,
1071
+ params?: FetchParams,
1072
+ ): Promise<prismicT.Ref> {
1073
+ const refs = await this.getRefs(params);
1035
1074
 
1036
1075
  return findRefByLabel(refs, label);
1037
1076
  }
@@ -1042,8 +1081,8 @@ export class Client {
1042
1081
  *
1043
1082
  * @returns The repository's master ref.
1044
1083
  */
1045
- async getMasterRef(): Promise<prismicT.Ref> {
1046
- const refs = await this.getRefs();
1084
+ async getMasterRef(params?: FetchParams): Promise<prismicT.Ref> {
1085
+ const refs = await this.getRefs(params);
1047
1086
 
1048
1087
  return findMasterRef(refs);
1049
1088
  }
@@ -1054,8 +1093,8 @@ export class Client {
1054
1093
  *
1055
1094
  * @returns A list of all Releases for the Prismic repository.
1056
1095
  */
1057
- async getReleases(): Promise<prismicT.Ref[]> {
1058
- const refs = await this.getRefs();
1096
+ async getReleases(params?: FetchParams): Promise<prismicT.Ref[]> {
1097
+ const refs = await this.getRefs(params);
1059
1098
 
1060
1099
  return refs.filter((ref) => !ref.isMasterRef);
1061
1100
  }
@@ -1067,8 +1106,11 @@ export class Client {
1067
1106
  *
1068
1107
  * @returns The Release with a matching ID, if it exists.
1069
1108
  */
1070
- async getReleaseByID(id: string): Promise<prismicT.Ref> {
1071
- const releases = await this.getReleases();
1109
+ async getReleaseByID(
1110
+ id: string,
1111
+ params?: FetchParams,
1112
+ ): Promise<prismicT.Ref> {
1113
+ const releases = await this.getReleases(params);
1072
1114
 
1073
1115
  return findRefByID(releases, id);
1074
1116
  }
@@ -1080,8 +1122,11 @@ export class Client {
1080
1122
  *
1081
1123
  * @returns The ref with a matching label, if it exists.
1082
1124
  */
1083
- async getReleaseByLabel(label: string): Promise<prismicT.Ref> {
1084
- const releases = await this.getReleases();
1125
+ async getReleaseByLabel(
1126
+ label: string,
1127
+ params?: FetchParams,
1128
+ ): Promise<prismicT.Ref> {
1129
+ const releases = await this.getReleases(params);
1085
1130
 
1086
1131
  return findRefByLabel(releases, label);
1087
1132
  }
@@ -1091,13 +1136,13 @@ export class Client {
1091
1136
  *
1092
1137
  * @returns A list of all tags used in the repository.
1093
1138
  */
1094
- async getTags(): Promise<string[]> {
1139
+ async getTags(params?: FetchParams): Promise<string[]> {
1095
1140
  try {
1096
- const tagsForm = await this.getCachedRepositoryForm("tags");
1141
+ const tagsForm = await this.getCachedRepositoryForm("tags", params);
1097
1142
 
1098
1143
  return await this.fetch<string[]>(tagsForm.action);
1099
1144
  } catch {
1100
- const repository = await this.getRepository();
1145
+ const repository = await this.getRepository(params);
1101
1146
 
1102
1147
  return repository.tags;
1103
1148
  }
@@ -1110,13 +1155,14 @@ export class Client {
1110
1155
  *
1111
1156
  * @returns A URL string that can be requested to query content.
1112
1157
  */
1113
- async buildQueryURL(
1114
- params: Partial<BuildQueryURLArgs> = {},
1115
- ): Promise<string> {
1158
+ async buildQueryURL({
1159
+ signal,
1160
+ ...params
1161
+ }: Partial<BuildQueryURLArgs> & FetchParams = {}): Promise<string> {
1116
1162
  const ref = params.ref || (await this.getResolvedRefString());
1117
1163
  const integrationFieldsRef =
1118
1164
  params.integrationFieldsRef ||
1119
- (await this.getCachedRepository()).integrationFieldsRef ||
1165
+ (await this.getCachedRepository({ signal })).integrationFieldsRef ||
1120
1166
  undefined;
1121
1167
 
1122
1168
  return buildQueryURL(this.endpoint, {
@@ -1148,7 +1194,9 @@ export class Client {
1148
1194
  * @returns The URL for the previewed document during an active preview
1149
1195
  * session. The user should be redirected to this URL.
1150
1196
  */
1151
- async resolvePreviewURL(args: ResolvePreviewArgs): Promise<string> {
1197
+ async resolvePreviewURL<LinkResolverReturnType>(
1198
+ args: ResolvePreviewArgs<LinkResolverReturnType> & FetchParams,
1199
+ ): Promise<string> {
1152
1200
  let documentID = args.documentID;
1153
1201
  let previewToken = args.previewToken;
1154
1202
 
@@ -1164,18 +1212,21 @@ export class Client {
1164
1212
  previewToken || (this.refState.httpRequest.query.token as string);
1165
1213
  }
1166
1214
 
1167
- if (documentID != null) {
1215
+ if (documentID != null && previewToken != null) {
1168
1216
  const document = await this.getByID(documentID, {
1217
+ signal: args.signal,
1169
1218
  ref: previewToken,
1170
1219
  lang: "*",
1171
1220
  });
1172
1221
 
1173
- // We know we have a valid field to resolve since we are using prismicH.documentToLinkField
1174
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1175
- return prismicH.asLink(document, args.linkResolver)!;
1176
- } else {
1177
- return args.defaultURL;
1222
+ const url = prismicH.asLink(document, args.linkResolver);
1223
+
1224
+ if (typeof url === "string") {
1225
+ return url;
1226
+ }
1178
1227
  }
1228
+
1229
+ return args.defaultURL;
1179
1230
  }
1180
1231
 
1181
1232
  /**
@@ -1264,10 +1315,17 @@ export class Client {
1264
1315
  };
1265
1316
  }
1266
1317
 
1318
+ /**
1319
+ * @deprecated Renamed to `graphQLFetch()` (note the capitalization of "QL").
1320
+ */
1321
+ // TODO: Remove in v3
1322
+ graphqlFetch = this.graphQLFetch;
1323
+
1267
1324
  /**
1268
1325
  * A `fetch()` function to be used with GraphQL clients configured for
1269
1326
  * Prismic's GraphQL API. It automatically applies the necessary `prismic-ref`
1270
- * and Authorization headers.
1327
+ * and Authorization headers. Queries will automatically be minified by
1328
+ * removing whitespace where possible.
1271
1329
  *
1272
1330
  * @example
1273
1331
  *
@@ -1290,7 +1348,7 @@ export class Client {
1290
1348
  * @returns The `fetch()` Response for the request.
1291
1349
  * @experimental
1292
1350
  */
1293
- async graphqlFetch(
1351
+ async graphQLFetch(
1294
1352
  input: RequestInfo,
1295
1353
  init?: RequestInit,
1296
1354
  ): Promise<Response> {
@@ -1308,6 +1366,9 @@ export class Client {
1308
1366
  ...(init ? (init.headers as Record<string, string>) : {}),
1309
1367
  };
1310
1368
 
1369
+ // Normalize header keys to lowercase. This prevents header
1370
+ // conflicts between the Prismic client and the GraphQL
1371
+ // client.
1311
1372
  const headers: Record<string, string> = {};
1312
1373
  for (const key in unsanitizedHeaders) {
1313
1374
  if (unsanitizedHeaders[key]) {
@@ -1316,16 +1377,24 @@ export class Client {
1316
1377
  }
1317
1378
  }
1318
1379
 
1319
- return (await this.fetchFn(
1380
+ // Compress the GraphQL query (if it exists) by removing
1381
+ // whitespace. This is done to optimize the query size and avoid hitting the
1382
+ // upper limit of GET requests (2048 characters).
1383
+ const url = new URL(
1320
1384
  // Asserting `input` is a string since popular GraphQL
1321
1385
  // libraries pass this as a string. Request objects as
1322
1386
  // input are unsupported.
1323
1387
  input as string,
1324
- {
1325
- ...init,
1326
- headers,
1327
- },
1328
- )) as Response;
1388
+ );
1389
+ const query = url.searchParams.get("query");
1390
+ if (query) {
1391
+ url.searchParams.set("query", minifyGraphQLQuery(query));
1392
+ }
1393
+
1394
+ return (await this.fetchFn(url.toString(), {
1395
+ ...init,
1396
+ headers,
1397
+ })) as Response;
1329
1398
  }
1330
1399
 
1331
1400
  /**
@@ -1333,13 +1402,15 @@ export class Client {
1333
1402
  *
1334
1403
  * @returns Cached repository metadata.
1335
1404
  */
1336
- private async getCachedRepository(): Promise<prismicT.Repository> {
1405
+ private async getCachedRepository(
1406
+ params?: FetchParams,
1407
+ ): Promise<prismicT.Repository> {
1337
1408
  if (
1338
1409
  !this.cachedRepository ||
1339
1410
  Date.now() >= this.cachedRepositoryExpiration
1340
1411
  ) {
1341
1412
  this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1342
- this.cachedRepository = await this.getRepository();
1413
+ this.cachedRepository = await this.getRepository(params);
1343
1414
  }
1344
1415
 
1345
1416
  return this.cachedRepository;
@@ -1354,8 +1425,11 @@ export class Client {
1354
1425
  * @returns The repository form.
1355
1426
  * @throws If a matching form cannot be found.
1356
1427
  */
1357
- private async getCachedRepositoryForm(name: string): Promise<prismicT.Form> {
1358
- const cachedRepository = await this.getCachedRepository();
1428
+ private async getCachedRepositoryForm(
1429
+ name: string,
1430
+ params?: FetchParams,
1431
+ ): Promise<prismicT.Form> {
1432
+ const cachedRepository = await this.getCachedRepository(params);
1359
1433
  const form = cachedRepository.forms[name];
1360
1434
 
1361
1435
  if (!form) {
@@ -1390,7 +1464,7 @@ export class Client {
1390
1464
  *
1391
1465
  * @returns The ref to use during a query.
1392
1466
  */
1393
- private async getResolvedRefString(): Promise<string> {
1467
+ private async getResolvedRefString(params?: FetchParams): Promise<string> {
1394
1468
  if (this.refState.autoPreviewsEnabled) {
1395
1469
  let previewRef: string | undefined = undefined;
1396
1470
 
@@ -1408,7 +1482,7 @@ export class Client {
1408
1482
  }
1409
1483
  }
1410
1484
 
1411
- const cachedRepository = await this.getCachedRepository();
1485
+ const cachedRepository = await this.getCachedRepository(params);
1412
1486
 
1413
1487
  const refModeType = this.refState.mode;
1414
1488
  if (refModeType === RefStateMode.ReleaseID) {
@@ -1441,7 +1515,8 @@ export class Client {
1441
1515
  private async fetch<T = unknown>(
1442
1516
  url: string,
1443
1517
  // TODO: Change to `params` when Authorization header support works in browsers with CORS.
1444
- _params?: Partial<BuildQueryURLArgs>,
1518
+ // _params?: Partial<BuildQueryURLArgs>,
1519
+ params: FetchParams = {},
1445
1520
  ): Promise<T> {
1446
1521
  // TODO: Restore when Authorization header support works in browsers with CORS.
1447
1522
  // const accessToken = (params && params.accessToken) || this.accessToken;
@@ -1449,7 +1524,9 @@ export class Client {
1449
1524
  // ? { headers: { Authorization: `Token ${accessToken}` } }
1450
1525
  // : {};
1451
1526
 
1452
- const res = await this.fetchFn(url);
1527
+ const res = await this.fetchFn(url, {
1528
+ signal: params.signal,
1529
+ });
1453
1530
 
1454
1531
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1455
1532
  let json: any;
@@ -1,3 +1,6 @@
1
+ import { isRepositoryName } from "./isRepositoryName";
2
+ import { PrismicError } from "./PrismicError";
3
+
1
4
  /**
2
5
  * Get a repository's Prismic GraphQL endpoint.
3
6
  *
@@ -8,5 +11,14 @@
8
11
  */
9
12
  export const getGraphQLEndpoint = <RepositoryName extends string>(
10
13
  repositoryName: RepositoryName,
11
- ): `https://${RepositoryName}.cdn.prismic.io/graphql` =>
12
- `https://${repositoryName}.cdn.prismic.io/graphql` as const;
14
+ ): `https://${RepositoryName}.cdn.prismic.io/graphql` => {
15
+ if (isRepositoryName(repositoryName)) {
16
+ return `https://${repositoryName}.cdn.prismic.io/graphql` as const;
17
+ } else {
18
+ throw new PrismicError(
19
+ `An invalid Prismic repository name was given: ${repositoryName}`,
20
+ undefined,
21
+ undefined,
22
+ );
23
+ }
24
+ };