@prismicio/client 7.0.0-alpha.3 → 7.0.0-alpha.4

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.
Files changed (45) hide show
  1. package/dist/createClient.cjs +57 -76
  2. package/dist/createClient.cjs.map +1 -1
  3. package/dist/createClient.d.ts +61 -69
  4. package/dist/createClient.js +57 -76
  5. package/dist/createClient.js.map +1 -1
  6. package/dist/helpers/asHTML.cjs +17 -4
  7. package/dist/helpers/asHTML.cjs.map +1 -1
  8. package/dist/helpers/asHTML.d.ts +55 -13
  9. package/dist/helpers/asHTML.js +17 -4
  10. package/dist/helpers/asHTML.js.map +1 -1
  11. package/dist/helpers/asImagePixelDensitySrcSet.cjs +2 -2
  12. package/dist/helpers/asImagePixelDensitySrcSet.cjs.map +1 -1
  13. package/dist/helpers/asImagePixelDensitySrcSet.d.ts +2 -2
  14. package/dist/helpers/asImagePixelDensitySrcSet.js +2 -2
  15. package/dist/helpers/asImagePixelDensitySrcSet.js.map +1 -1
  16. package/dist/helpers/asImageSrc.cjs +2 -2
  17. package/dist/helpers/asImageSrc.cjs.map +1 -1
  18. package/dist/helpers/asImageSrc.d.ts +2 -2
  19. package/dist/helpers/asImageSrc.js +2 -2
  20. package/dist/helpers/asImageSrc.js.map +1 -1
  21. package/dist/helpers/asImageWidthSrcSet.cjs +2 -2
  22. package/dist/helpers/asImageWidthSrcSet.cjs.map +1 -1
  23. package/dist/helpers/asImageWidthSrcSet.d.ts +2 -2
  24. package/dist/helpers/asImageWidthSrcSet.js +2 -2
  25. package/dist/helpers/asImageWidthSrcSet.js.map +1 -1
  26. package/dist/helpers/asLink.cjs +12 -3
  27. package/dist/helpers/asLink.cjs.map +1 -1
  28. package/dist/helpers/asLink.d.ts +55 -15
  29. package/dist/helpers/asLink.js +12 -3
  30. package/dist/helpers/asLink.js.map +1 -1
  31. package/dist/helpers/asText.cjs +11 -2
  32. package/dist/helpers/asText.cjs.map +1 -1
  33. package/dist/helpers/asText.d.ts +44 -10
  34. package/dist/helpers/asText.js +11 -2
  35. package/dist/helpers/asText.js.map +1 -1
  36. package/dist/package.json.cjs +1 -1
  37. package/dist/package.json.js +1 -1
  38. package/package.json +1 -1
  39. package/src/createClient.ts +176 -251
  40. package/src/helpers/asHTML.ts +99 -25
  41. package/src/helpers/asImagePixelDensitySrcSet.ts +3 -3
  42. package/src/helpers/asImageSrc.ts +3 -3
  43. package/src/helpers/asImageWidthSrcSet.ts +3 -3
  44. package/src/helpers/asLink.ts +102 -18
  45. package/src/helpers/asText.ts +71 -12
@@ -1,5 +1,6 @@
1
1
  import { appendFilters } from "./lib/appendFilters";
2
2
  import { castThunk } from "./lib/castThunk";
3
+ import { devMsg } from "./lib/devMsg";
3
4
  import { everyTagFilter } from "./lib/everyTagFilter";
4
5
  import { findMasterRef } from "./lib/findMasterRef";
5
6
  import { findRefByID } from "./lib/findRefByID";
@@ -24,6 +25,7 @@ import { LinkResolverFunction, asLink } from "./helpers/asLink";
24
25
  import { BuildQueryURLArgs, buildQueryURL } from "./buildQueryURL";
25
26
  import { filter } from "./filter";
26
27
  import { getRepositoryEndpoint } from "./getRepositoryEndpoint";
28
+ import { getRepositoryName } from "./getRepositoryName";
27
29
  import { isRepositoryEndpoint } from "./isRepositoryEndpoint";
28
30
 
29
31
  /**
@@ -49,13 +51,6 @@ export const REPOSITORY_CACHE_TTL = 5000;
49
51
  */
50
52
  export const GET_ALL_QUERY_DELAY = 500;
51
53
 
52
- /**
53
- * The URL search parameter name used for optimizing `/api/v2` requests. The
54
- * value of the parameter effectively forcibly cache-busts `/api/v2` requests
55
- * after REPOSITORY_CACHE_TTL milliseconds have elapsed.
56
- */
57
- const OPTIMIZE_REPOSITORY_REQUESTS_VALID_UNTIL_PARAMETER_NAME = "x-valid-until";
58
-
59
54
  /**
60
55
  * Extracts one or more Prismic document types that match a given Prismic
61
56
  * document type. If no matches are found, no extraction is performed and the
@@ -95,16 +90,23 @@ export type FetchLike = (
95
90
  export type AbortSignalLike = any;
96
91
 
97
92
  /**
98
- * The minimum required properties from RequestInit.
93
+ * A subset of RequestInit properties to configure a `fetch()` request.
99
94
  */
100
- export interface RequestInitLike {
95
+ // Only options relevant to the client are included. Extending from the full
96
+ // RequestInit would cause issues, such as accepting Header objects.
97
+ //
98
+ // An interface is used to allow other libraries to augment the type with
99
+ // environment-specific types.
100
+ export interface RequestInitLike extends Pick<RequestInit, "cache"> {
101
+ /**
102
+ * An object literal to set the `fetch()` request's headers.
103
+ */
101
104
  headers?: Record<string, string>;
102
105
 
103
106
  /**
104
- * An object that allows you to abort a `fetch()` request if needed via an
105
- * `AbortController` object
107
+ * An AbortSignal to set the `fetch()` request's signal.
106
108
  *
107
- * {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal}
109
+ * See: \<https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\>
108
110
  */
109
111
  // NOTE: `AbortSignalLike` is `any`! It is left as `AbortSignalLike`
110
112
  // for backwards compatibility (the type is exported) and to signal to
@@ -264,52 +266,45 @@ export type ClientConfig = {
264
266
  * Node.js, this function must be provided.
265
267
  */
266
268
  fetch?: FetchLike;
267
- } & OptimizeParams;
269
+
270
+ /**
271
+ * Options provided to the client's `fetch()` on all network requests.
272
+ * These options will be merged with internally required options. They
273
+ * can also be overriden on a per-query basis using the query's
274
+ * `fetchOptions` parameter.
275
+ */
276
+ fetchOptions?: RequestInitLike;
277
+ };
268
278
 
269
279
  /**
270
- * Parameters for any client method that use `fetch()`. Only a subset of
271
- * `fetch()` parameters are exposed.
280
+ * Parameters for any client method that use `fetch()`.
272
281
  */
273
282
  type FetchParams = {
283
+ /**
284
+ * Options provided to the client's `fetch()` on all network requests.
285
+ * These options will be merged with internally required options. They
286
+ * can also be overriden on a per-query basis using the query's
287
+ * `fetchOptions` parameter.
288
+ */
289
+ fetchOptions?: RequestInitLike;
290
+
274
291
  /**
275
292
  * An `AbortSignal` provided by an `AbortController`. This allows the network
276
293
  * request to be cancelled if necessary.
277
294
  *
278
295
  * {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal}
296
+ *
297
+ * @deprecated Move the `signal` parameter into `fetchOptions.signal`:
298
+ *
299
+ * ```typescript
300
+ * client.getByUID("page", "home",{
301
+ * fetchOptions: { signal }
302
+ * });
303
+ * ```
279
304
  */
280
305
  signal?: AbortSignalLike;
281
306
  };
282
307
 
283
- /**
284
- * Parameters that determine if or how the client is optimized.
285
- */
286
- type OptimizeParams = {
287
- /**
288
- * Options that determine if or how the client is optimized.
289
- */
290
- optimize?: {
291
- /**
292
- * Determines if fetching repository metadata should be optimized. The
293
- * optimizations result in faster queries, less network requests, and more
294
- * accurate cache-busting.
295
- *
296
- * Only opt out of this optimization if you know what you are doing.
297
- *
298
- * @defaultValue `true`
299
- */
300
- repositoryRequests?: boolean;
301
-
302
- /**
303
- * Determines if concurrent requests to the same URL should be optimized. The optimizations result in less network requests and quicker responses.
304
- *
305
- * Only opt out of this optimization if you know what you are doing.
306
- *
307
- * @defaultValue `true`
308
- */
309
- concurrentRequests?: boolean;
310
- };
311
- };
312
-
313
308
  /**
314
309
  * Parameters specific to client methods that fetch all documents. These methods
315
310
  * start with `getAll` (for example, `getAllByType`).
@@ -444,6 +439,8 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
444
439
  */
445
440
  fetchFn: FetchLike;
446
441
 
442
+ fetchOptions?: RequestInitLike;
443
+
447
444
  /**
448
445
  * Default parameters that will be sent with each query. These parameters can
449
446
  * be overridden on each query if needed.
@@ -453,11 +450,6 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
453
450
  "ref" | "integrationFieldsRef" | "accessToken" | "routes"
454
451
  >;
455
452
 
456
- /**
457
- * Options that determine if or how the client is optimized.
458
- */
459
- optimize: NonNullable<OptimizeParams["optimize"]>;
460
-
461
453
  /**
462
454
  * The client's ref mode state. This determines which ref is used during
463
455
  * queries.
@@ -501,15 +493,33 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
501
493
  */
502
494
  constructor(repositoryNameOrEndpoint: string, options: ClientConfig = {}) {
503
495
  if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
504
- if (
505
- process.env.NODE_ENV === "development" &&
506
- /\.prismic\.io\/(?!api\/v2\/?)/.test(repositoryNameOrEndpoint)
507
- ) {
508
- throw new PrismicError(
509
- "@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.",
510
- undefined,
511
- undefined,
512
- );
496
+ if (process.env.NODE_ENV === "development") {
497
+ // Matches non-API v2 `.prismic.io` endpoints, see: https://regex101.com/r/xRsavu/1
498
+ if (/\.prismic\.io\/(?!api\/v2\/?)/i.test(repositoryNameOrEndpoint)) {
499
+ throw new PrismicError(
500
+ "@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.",
501
+ undefined,
502
+ undefined,
503
+ );
504
+ }
505
+
506
+ const hostname = new URL(
507
+ repositoryNameOrEndpoint,
508
+ ).hostname.toLowerCase();
509
+
510
+ // Matches non-.cdn `.prismic.io` endpoints
511
+ if (
512
+ hostname.endsWith(".prismic.io") &&
513
+ !hostname.endsWith(".cdn.prismic.io")
514
+ ) {
515
+ const repositoryName = getRepositoryName(repositoryNameOrEndpoint);
516
+ const dotCDNEndpoint = getRepositoryEndpoint(repositoryName);
517
+ console.warn(
518
+ `[@prismicio/client] A non-.cdn endpoint was provided to create a client with (\`${repositoryNameOrEndpoint}\`). Non-.cdn endpoints can have unexpected side-effects and cause performance issues when querying Prismic. Please convert it to the \`.cdn\` alternative (\`${dotCDNEndpoint}\`) or use the repository name directly instead (\`${repositoryName}\`). For more details, see ${devMsg(
519
+ "endpoint-must-use-cdn",
520
+ )}`,
521
+ );
522
+ }
513
523
  }
514
524
 
515
525
  this.endpoint = repositoryNameOrEndpoint;
@@ -520,11 +530,8 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
520
530
  this.accessToken = options.accessToken;
521
531
  this.routes = options.routes;
522
532
  this.brokenRoute = options.brokenRoute;
533
+ this.fetchOptions = options.fetchOptions;
523
534
  this.defaultParams = options.defaultParams;
524
- this.optimize = {
525
- repositoryRequests: options.optimize?.repositoryRequests ?? true,
526
- concurrentRequests: options.optimize?.concurrentRequests ?? true,
527
- };
528
535
 
529
536
  if (options.ref) {
530
537
  this.queryContentFromRef(options.ref);
@@ -625,7 +632,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
625
632
  * @returns A paginated response containing the result of the query.
626
633
  */
627
634
  async get<TDocument extends TDocuments>(
628
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
635
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
629
636
  ): Promise<Query<TDocument>> {
630
637
  const url = await this.buildQueryURL(params);
631
638
 
@@ -647,7 +654,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
647
654
  * The first result of the query, if any.
648
655
  */
649
656
  async getFirst<TDocument extends TDocuments>(
650
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
657
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
651
658
  ): Promise<TDocument> {
652
659
  const actualParams = { ...params };
653
660
  if (!(params && params.page) && !params?.pageSize) {
@@ -690,8 +697,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
690
697
  async dangerouslyGetAll<TDocument extends TDocuments>(
691
698
  params: Partial<Omit<BuildQueryURLArgs, "page">> &
692
699
  GetAllParams &
693
- FetchParams &
694
- OptimizeParams = {},
700
+ FetchParams = {},
695
701
  ): Promise<TDocument[]> {
696
702
  const { limit = Infinity, ...actualParams } = params;
697
703
  const resolvedParams = {
@@ -745,7 +751,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
745
751
  */
746
752
  async getByID<TDocument extends TDocuments>(
747
753
  id: string,
748
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
754
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
749
755
  ): Promise<TDocument> {
750
756
  return await this.getFirst<TDocument>(
751
757
  appendFilters(params, filter.at("document.id", id)),
@@ -778,7 +784,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
778
784
  */
779
785
  async getByIDs<TDocument extends TDocuments>(
780
786
  ids: string[],
781
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
787
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
782
788
  ): Promise<Query<TDocument>> {
783
789
  return await this.get<TDocument>(
784
790
  appendFilters(params, filter.in("document.id", ids)),
@@ -813,10 +819,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
813
819
  */
814
820
  async getAllByIDs<TDocument extends TDocuments>(
815
821
  ids: string[],
816
- params?: Partial<BuildQueryURLArgs> &
817
- GetAllParams &
818
- FetchParams &
819
- OptimizeParams,
822
+ params?: Partial<BuildQueryURLArgs> & GetAllParams & FetchParams,
820
823
  ): Promise<TDocument[]> {
821
824
  return await this.dangerouslyGetAll<TDocument>(
822
825
  appendFilters(params, filter.in("document.id", ids)),
@@ -852,7 +855,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
852
855
  >(
853
856
  documentType: TDocumentType,
854
857
  uid: string,
855
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
858
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
856
859
  ): Promise<ExtractDocumentType<TDocument, TDocumentType>> {
857
860
  return await this.getFirst<ExtractDocumentType<TDocument, TDocumentType>>(
858
861
  appendFilters(params, [
@@ -894,7 +897,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
894
897
  >(
895
898
  documentType: TDocumentType,
896
899
  uids: string[],
897
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
900
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
898
901
  ): Promise<Query<ExtractDocumentType<TDocument, TDocumentType>>> {
899
902
  return await this.get<ExtractDocumentType<TDocument, TDocumentType>>(
900
903
  appendFilters(params, [
@@ -938,10 +941,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
938
941
  >(
939
942
  documentType: TDocumentType,
940
943
  uids: string[],
941
- params?: Partial<BuildQueryURLArgs> &
942
- GetAllParams &
943
- FetchParams &
944
- OptimizeParams,
944
+ params?: Partial<BuildQueryURLArgs> & GetAllParams & FetchParams,
945
945
  ): Promise<ExtractDocumentType<TDocument, TDocumentType>[]> {
946
946
  return await this.dangerouslyGetAll<
947
947
  ExtractDocumentType<TDocument, TDocumentType>
@@ -980,7 +980,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
980
980
  TDocumentType extends TDocument["type"] = TDocument["type"],
981
981
  >(
982
982
  documentType: TDocumentType,
983
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
983
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
984
984
  ): Promise<ExtractDocumentType<TDocument, TDocumentType>> {
985
985
  return await this.getFirst<ExtractDocumentType<TDocument, TDocumentType>>(
986
986
  appendFilters(params, typeFilter(documentType)),
@@ -1010,7 +1010,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1010
1010
  TDocumentType extends TDocument["type"] = TDocument["type"],
1011
1011
  >(
1012
1012
  documentType: TDocumentType,
1013
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
1013
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
1014
1014
  ): Promise<Query<ExtractDocumentType<TDocument, TDocumentType>>> {
1015
1015
  return await this.get<ExtractDocumentType<TDocument, TDocumentType>>(
1016
1016
  appendFilters(params, typeFilter(documentType)),
@@ -1043,8 +1043,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1043
1043
  documentType: TDocumentType,
1044
1044
  params?: Partial<Omit<BuildQueryURLArgs, "page">> &
1045
1045
  GetAllParams &
1046
- FetchParams &
1047
- OptimizeParams,
1046
+ FetchParams,
1048
1047
  ): Promise<ExtractDocumentType<TDocument, TDocumentType>[]> {
1049
1048
  return await this.dangerouslyGetAll<
1050
1049
  ExtractDocumentType<TDocument, TDocumentType>
@@ -1071,7 +1070,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1071
1070
  */
1072
1071
  async getByTag<TDocument extends TDocuments>(
1073
1072
  tag: string,
1074
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
1073
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
1075
1074
  ): Promise<Query<TDocument>> {
1076
1075
  return await this.get<TDocument>(
1077
1076
  appendFilters(params, someTagsFilter(tag)),
@@ -1100,8 +1099,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1100
1099
  tag: string,
1101
1100
  params?: Partial<Omit<BuildQueryURLArgs, "page">> &
1102
1101
  GetAllParams &
1103
- FetchParams &
1104
- OptimizeParams,
1102
+ FetchParams,
1105
1103
  ): Promise<TDocument[]> {
1106
1104
  return await this.dangerouslyGetAll<TDocument>(
1107
1105
  appendFilters(params, someTagsFilter(tag)),
@@ -1126,7 +1124,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1126
1124
  */
1127
1125
  async getByEveryTag<TDocument extends TDocuments>(
1128
1126
  tags: string[],
1129
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
1127
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
1130
1128
  ): Promise<Query<TDocument>> {
1131
1129
  return await this.get<TDocument>(
1132
1130
  appendFilters(params, everyTagFilter(tags)),
@@ -1156,8 +1154,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1156
1154
  tags: string[],
1157
1155
  params?: Partial<Omit<BuildQueryURLArgs, "page">> &
1158
1156
  GetAllParams &
1159
- FetchParams &
1160
- OptimizeParams,
1157
+ FetchParams,
1161
1158
  ): Promise<TDocument[]> {
1162
1159
  return await this.dangerouslyGetAll<TDocument>(
1163
1160
  appendFilters(params, everyTagFilter(tags)),
@@ -1184,7 +1181,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1184
1181
  */
1185
1182
  async getBySomeTags<TDocument extends TDocuments>(
1186
1183
  tags: string[],
1187
- params?: Partial<BuildQueryURLArgs> & FetchParams & OptimizeParams,
1184
+ params?: Partial<BuildQueryURLArgs> & FetchParams,
1188
1185
  ): Promise<Query<TDocument>> {
1189
1186
  return await this.get<TDocument>(
1190
1187
  appendFilters(params, someTagsFilter(tags)),
@@ -1215,8 +1212,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1215
1212
  tags: string[],
1216
1213
  params?: Partial<Omit<BuildQueryURLArgs, "page">> &
1217
1214
  GetAllParams &
1218
- FetchParams &
1219
- OptimizeParams,
1215
+ FetchParams,
1220
1216
  ): Promise<TDocument[]> {
1221
1217
  return await this.dangerouslyGetAll<TDocument>(
1222
1218
  appendFilters(params, someTagsFilter(tags)),
@@ -1229,9 +1225,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1229
1225
  *
1230
1226
  * @returns Repository metadata.
1231
1227
  */
1232
- async getRepository(
1233
- params?: FetchParams & OptimizeParams,
1234
- ): Promise<Repository> {
1228
+ async getRepository(params?: FetchParams): Promise<Repository> {
1235
1229
  // TODO: Restore when Authorization header support works in browsers with CORS.
1236
1230
  // return await this.fetch<Repository>(this.endpoint);
1237
1231
 
@@ -1241,28 +1235,6 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1241
1235
  url.searchParams.set("access_token", this.accessToken);
1242
1236
  }
1243
1237
 
1244
- if (
1245
- params?.optimize?.repositoryRequests ??
1246
- this.optimize.repositoryRequests
1247
- ) {
1248
- // Add a URL parameter to fingerprint the URL. The URL
1249
- // should be valid for the duration of
1250
- // REPOSITORY_CACHE_TTL.
1251
- //
1252
- // This fingerprint works as a second "cache" that
1253
- // works outside `getRepositoryCache()`. This is useful
1254
- // when multiple client instances exist with an
1255
- // external cache; all clients can share the same URL
1256
- // cache key for the duration of REPOSITORY_CACHE_TTL.
1257
- url.searchParams.set(
1258
- OPTIMIZE_REPOSITORY_REQUESTS_VALID_UNTIL_PARAMETER_NAME,
1259
- (
1260
- Math.floor(Date.now() / REPOSITORY_CACHE_TTL) * REPOSITORY_CACHE_TTL +
1261
- REPOSITORY_CACHE_TTL
1262
- ).toString(),
1263
- );
1264
- }
1265
-
1266
1238
  return await this.fetch<Repository>(url.toString(), params);
1267
1239
  }
1268
1240
 
@@ -1275,7 +1247,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1275
1247
  *
1276
1248
  * @returns A list of all refs for the Prismic repository.
1277
1249
  */
1278
- async getRefs(params?: FetchParams & OptimizeParams): Promise<Ref[]> {
1250
+ async getRefs(params?: FetchParams): Promise<Ref[]> {
1279
1251
  const repository = await this.getRepository(params);
1280
1252
 
1281
1253
  return repository.refs;
@@ -1288,10 +1260,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1288
1260
  *
1289
1261
  * @returns The ref with a matching ID, if it exists.
1290
1262
  */
1291
- async getRefByID(
1292
- id: string,
1293
- params?: FetchParams & OptimizeParams,
1294
- ): Promise<Ref> {
1263
+ async getRefByID(id: string, params?: FetchParams): Promise<Ref> {
1295
1264
  const refs = await this.getRefs(params);
1296
1265
 
1297
1266
  return findRefByID(refs, id);
@@ -1304,10 +1273,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1304
1273
  *
1305
1274
  * @returns The ref with a matching label, if it exists.
1306
1275
  */
1307
- async getRefByLabel(
1308
- label: string,
1309
- params?: FetchParams & OptimizeParams,
1310
- ): Promise<Ref> {
1276
+ async getRefByLabel(label: string, params?: FetchParams): Promise<Ref> {
1311
1277
  const refs = await this.getRefs(params);
1312
1278
 
1313
1279
  return findRefByLabel(refs, label);
@@ -1319,7 +1285,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1319
1285
  *
1320
1286
  * @returns The repository's master ref.
1321
1287
  */
1322
- async getMasterRef(params?: FetchParams & OptimizeParams): Promise<Ref> {
1288
+ async getMasterRef(params?: FetchParams): Promise<Ref> {
1323
1289
  const refs = await this.getRefs(params);
1324
1290
 
1325
1291
  return findMasterRef(refs);
@@ -1331,7 +1297,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1331
1297
  *
1332
1298
  * @returns A list of all Releases for the Prismic repository.
1333
1299
  */
1334
- async getReleases(params?: FetchParams & OptimizeParams): Promise<Ref[]> {
1300
+ async getReleases(params?: FetchParams): Promise<Ref[]> {
1335
1301
  const refs = await this.getRefs(params);
1336
1302
 
1337
1303
  return refs.filter((ref) => !ref.isMasterRef);
@@ -1344,10 +1310,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1344
1310
  *
1345
1311
  * @returns The Release with a matching ID, if it exists.
1346
1312
  */
1347
- async getReleaseByID(
1348
- id: string,
1349
- params?: FetchParams & OptimizeParams,
1350
- ): Promise<Ref> {
1313
+ async getReleaseByID(id: string, params?: FetchParams): Promise<Ref> {
1351
1314
  const releases = await this.getReleases(params);
1352
1315
 
1353
1316
  return findRefByID(releases, id);
@@ -1360,10 +1323,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1360
1323
  *
1361
1324
  * @returns The ref with a matching label, if it exists.
1362
1325
  */
1363
- async getReleaseByLabel(
1364
- label: string,
1365
- params?: FetchParams & OptimizeParams,
1366
- ): Promise<Ref> {
1326
+ async getReleaseByLabel(label: string, params?: FetchParams): Promise<Ref> {
1367
1327
  const releases = await this.getReleases(params);
1368
1328
 
1369
1329
  return findRefByLabel(releases, label);
@@ -1374,7 +1334,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1374
1334
  *
1375
1335
  * @returns A list of all tags used in the repository.
1376
1336
  */
1377
- async getTags(params?: FetchParams & OptimizeParams): Promise<string[]> {
1337
+ async getTags(params?: FetchParams): Promise<string[]> {
1378
1338
  try {
1379
1339
  const tagsForm = await this.getCachedRepositoryForm("tags", params);
1380
1340
 
@@ -1401,16 +1361,14 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1401
1361
  */
1402
1362
  async buildQueryURL({
1403
1363
  signal,
1404
- optimize,
1364
+ fetchOptions,
1405
1365
  ...params
1406
- }: Partial<BuildQueryURLArgs> &
1407
- FetchParams &
1408
- OptimizeParams = {}): Promise<string> {
1366
+ }: Partial<BuildQueryURLArgs> & FetchParams = {}): Promise<string> {
1409
1367
  const ref =
1410
- params.ref || (await this.getResolvedRefString({ signal, optimize }));
1368
+ params.ref || (await this.getResolvedRefString({ signal, fetchOptions }));
1411
1369
  const integrationFieldsRef =
1412
1370
  params.integrationFieldsRef ||
1413
- (await this.getCachedRepository({ signal, optimize }))
1371
+ (await this.getCachedRepository({ signal, fetchOptions }))
1414
1372
  .integrationFieldsRef ||
1415
1373
  undefined;
1416
1374
 
@@ -1445,9 +1403,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1445
1403
  * session. The user should be redirected to this URL.
1446
1404
  */
1447
1405
  async resolvePreviewURL<LinkResolverReturnType>(
1448
- args: ResolvePreviewArgs<LinkResolverReturnType> &
1449
- FetchParams &
1450
- OptimizeParams,
1406
+ args: ResolvePreviewArgs<LinkResolverReturnType> & FetchParams,
1451
1407
  ): Promise<string> {
1452
1408
  let documentID: string | undefined | null = args.documentID;
1453
1409
  let previewToken: string | undefined | null = args.previewToken;
@@ -1467,8 +1423,15 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1467
1423
  "url" in this.refState.httpRequest &&
1468
1424
  this.refState.httpRequest.url
1469
1425
  ) {
1470
- const searchParams = new URL(this.refState.httpRequest.url)
1471
- .searchParams;
1426
+ // Including "missing-host://" by default
1427
+ // handles a case where Next.js Route Handlers
1428
+ // only provide the pathname and search
1429
+ // parameters in the `url` property
1430
+ // (e.g. `/api/preview?foo=bar`).
1431
+ const searchParams = new URL(
1432
+ this.refState.httpRequest.url,
1433
+ "missing-host://",
1434
+ ).searchParams;
1472
1435
 
1473
1436
  documentID = documentID || searchParams.get("documentId");
1474
1437
  previewToken = previewToken || searchParams.get("token");
@@ -1477,13 +1440,13 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1477
1440
 
1478
1441
  if (documentID != null && previewToken != null) {
1479
1442
  const document = await this.getByID(documentID, {
1480
- optimize: args.optimize,
1481
- signal: args.signal,
1482
1443
  ref: previewToken,
1483
1444
  lang: "*",
1445
+ signal: args.signal,
1446
+ fetchOptions: args.fetchOptions,
1484
1447
  });
1485
1448
 
1486
- const url = asLink(document, args.linkResolver);
1449
+ const url = asLink(document, { linkResolver: args.linkResolver });
1487
1450
 
1488
1451
  if (typeof url === "string") {
1489
1452
  return url;
@@ -1685,25 +1648,16 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1685
1648
  *
1686
1649
  * @returns Cached repository metadata.
1687
1650
  */
1688
- private async getCachedRepository(
1689
- params?: FetchParams & OptimizeParams,
1690
- ): Promise<Repository> {
1651
+ private async getCachedRepository(params?: FetchParams): Promise<Repository> {
1691
1652
  if (
1692
- params?.optimize?.repositoryRequests ??
1693
- this.optimize.repositoryRequests
1653
+ !this.cachedRepository ||
1654
+ Date.now() >= this.cachedRepositoryExpiration
1694
1655
  ) {
1695
- if (
1696
- !this.cachedRepository ||
1697
- Date.now() >= this.cachedRepositoryExpiration
1698
- ) {
1699
- this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1700
- this.cachedRepository = await this.getRepository(params);
1701
- }
1702
-
1703
- return this.cachedRepository;
1704
- } else {
1705
- return await this.getRepository(params);
1656
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1657
+ this.cachedRepository = await this.getRepository(params);
1706
1658
  }
1659
+
1660
+ return this.cachedRepository;
1707
1661
  }
1708
1662
 
1709
1663
  /**
@@ -1717,7 +1671,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1717
1671
  */
1718
1672
  private async getCachedRepositoryForm(
1719
1673
  name: string,
1720
- params?: FetchParams & OptimizeParams,
1674
+ params?: FetchParams,
1721
1675
  ): Promise<Form> {
1722
1676
  const cachedRepository = await this.getCachedRepository(params);
1723
1677
  const form = cachedRepository.forms[name];
@@ -1756,9 +1710,7 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1756
1710
  *
1757
1711
  * @returns The ref to use during a query.
1758
1712
  */
1759
- private async getResolvedRefString(
1760
- params?: FetchParams & OptimizeParams,
1761
- ): Promise<string> {
1713
+ private async getResolvedRefString(params?: FetchParams): Promise<string> {
1762
1714
  if (this.refState.autoPreviewsEnabled) {
1763
1715
  let previewRef: string | undefined;
1764
1716
 
@@ -1820,94 +1772,67 @@ export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
1820
1772
  */
1821
1773
  private async fetch<T = unknown>(
1822
1774
  url: string,
1823
- params: FetchParams & OptimizeParams = {},
1775
+ params: FetchParams = {},
1824
1776
  ): Promise<T> {
1825
- let res: FetchJobResult;
1826
-
1827
- if (
1828
- params.optimize?.concurrentRequests ??
1829
- this.optimize.concurrentRequests
1830
- ) {
1831
- let job: Promise<FetchJobResult>;
1777
+ const requestInit: RequestInitLike = {
1778
+ ...this.fetchOptions,
1779
+ ...params.fetchOptions,
1780
+ headers: {
1781
+ ...this.fetchOptions?.headers,
1782
+ ...params.fetchOptions?.headers,
1783
+ },
1784
+ signal:
1785
+ params.fetchOptions?.signal ||
1786
+ params.signal ||
1787
+ this.fetchOptions?.signal,
1788
+ };
1832
1789
 
1833
- const fetchJobKeyInstance = new URL(url);
1834
- fetchJobKeyInstance.searchParams.delete(
1835
- OPTIMIZE_REPOSITORY_REQUESTS_VALID_UNTIL_PARAMETER_NAME,
1836
- );
1837
- const fetchJobKey = fetchJobKeyInstance.toString();
1838
-
1839
- // `fetchJobs` is keyed twice: first by the URL and again by is
1840
- // signal, if one exists.
1841
- //
1842
- // Using two keys allows us to reuse fetch requests for
1843
- // equivalent URLs, but eject when we detect unique signals.
1844
- if (
1845
- this.fetchJobs[fetchJobKey] &&
1846
- this.fetchJobs[fetchJobKey].has(params.signal)
1847
- ) {
1848
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1849
- job = this.fetchJobs[fetchJobKey].get(params.signal)!;
1850
- } else {
1851
- this.fetchJobs[fetchJobKey] = this.fetchJobs[fetchJobKey] || new Map();
1790
+ let job: Promise<FetchJobResult>;
1852
1791
 
1853
- job = this.fetchFn(url, {
1854
- signal: params.signal,
1855
- })
1856
- .then(async (res) => {
1857
- // We can assume Prismic REST API responses
1858
- // will have a `application/json`
1859
- // Content Type. If not, this will
1860
- // throw, signaling an invalid
1861
- // response.
1862
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1863
- let json: any = undefined;
1864
- try {
1865
- json = await res.json();
1866
- } catch {
1867
- // noop
1868
- }
1869
-
1870
- return {
1871
- status: res.status,
1872
- json,
1873
- };
1874
- })
1875
- .finally(() => {
1876
- this.fetchJobs[fetchJobKey].delete(params.signal);
1877
-
1878
- if (this.fetchJobs[fetchJobKey].size === 0) {
1879
- delete this.fetchJobs[fetchJobKey];
1880
- }
1881
- });
1882
-
1883
- this.fetchJobs[fetchJobKey].set(params.signal, job);
1884
- }
1885
-
1886
- res = await job;
1792
+ // `fetchJobs` is keyed twice: first by the URL and again by is
1793
+ // signal, if one exists.
1794
+ //
1795
+ // Using two keys allows us to reuse fetch requests for
1796
+ // equivalent URLs, but eject when we detect unique signals.
1797
+ if (this.fetchJobs[url] && this.fetchJobs[url].has(requestInit.signal)) {
1798
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1799
+ job = this.fetchJobs[url].get(requestInit.signal)!;
1887
1800
  } else {
1888
- const job = await this.fetchFn(url, {
1889
- signal: params.signal,
1890
- });
1801
+ this.fetchJobs[url] = this.fetchJobs[url] || new Map();
1802
+
1803
+ job = this.fetchFn(url, requestInit)
1804
+ .then(async (res) => {
1805
+ // We can assume Prismic REST API responses
1806
+ // will have a `application/json`
1807
+ // Content Type. If not, this will
1808
+ // throw, signaling an invalid
1809
+ // response.
1810
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1811
+ let json: any = undefined;
1812
+ try {
1813
+ json = await res.json();
1814
+ } catch {
1815
+ // noop
1816
+ }
1817
+
1818
+ return {
1819
+ status: res.status,
1820
+ json,
1821
+ };
1822
+ })
1823
+ .finally(() => {
1824
+ this.fetchJobs[url].delete(requestInit.signal);
1891
1825
 
1892
- // We can assume Prismic REST API responses
1893
- // will have a `application/json`
1894
- // Content Type. If not, this will
1895
- // throw, signaling an invalid
1896
- // response.
1897
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1898
- let json: any = undefined;
1899
- try {
1900
- json = await job.json();
1901
- } catch {
1902
- // noop
1903
- }
1826
+ if (this.fetchJobs[url].size === 0) {
1827
+ delete this.fetchJobs[url];
1828
+ }
1829
+ });
1904
1830
 
1905
- res = {
1906
- status: job.status,
1907
- json,
1908
- };
1831
+ this.fetchJobs[url].set(requestInit.signal, job);
1909
1832
  }
1910
1833
 
1834
+ const res = await job;
1835
+
1911
1836
  if (res.status !== 404 && res.json == null) {
1912
1837
  throw new PrismicError(undefined, url, res.json);
1913
1838
  }