@prismicio/client 6.0.0-alpha.7 → 6.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts CHANGED
@@ -2,178 +2,150 @@ 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 { castThunk } from "./lib/castThunk";
6
+ import { findMasterRef } from "./lib/findMasterRef";
7
+ import { findRefByID } from "./lib/findRefByID";
8
+ import { findRefByLabel } from "./lib/findRefByLabel";
5
9
  import { getCookie } from "./lib/getCookie";
6
10
 
7
- import {
8
- FetchLike,
9
- Form,
10
- HttpRequestLike,
11
- Query,
12
- Ref,
13
- Repository,
14
- RequestInitLike
15
- } from "./types";
11
+ import { FetchLike, HttpRequestLike } from "./types";
16
12
  import { buildQueryURL, BuildQueryURLArgs } from "./buildQueryURL";
17
- import { ForbiddenError, isForbiddenErrorAPIResponse } from "./ForbiddenError";
18
- import { ParsingError, isParsingErrorAPIResponse } from "./ParsingError";
13
+ import { ForbiddenError } from "./ForbiddenError";
14
+ import { ParsingError } from "./ParsingError";
19
15
  import { PrismicError } from "./PrismicError";
16
+ import { predicate } from "./predicate";
20
17
  import * as cookie from "./cookie";
21
- import * as predicate from "./predicate";
22
18
 
23
19
  /**
24
- * A container for items in a SimpleTTLCache.
25
- */
26
- type SimpleTTLCacheValueContainer<T = unknown> = {
27
- expiresAt: number;
28
- value: T;
29
- };
30
-
31
- /**
32
- * A simple time-to-live cache where items are only valid for a given number of milliseconds.
33
- */
34
- interface SimpleTTLCache {
35
- get<T>(key: string): T | undefined;
36
- set<T>(key: string, value: T, ttl?: number): void;
37
- }
38
-
39
- /**
40
- * Creates a simple cache where each element has a given time to live (TTL). After the TTL has ellapsed, the value is considered stale and will not be returned if requested.
41
- */
42
- const createSimpleTTLCache = (): SimpleTTLCache => {
43
- const cache = new Map<string, SimpleTTLCacheValueContainer>();
44
-
45
- return {
46
- /**
47
- * Get a value from the cache. If the item's TTL has ellapsed, `undefined` will be returned.
48
- *
49
- * @param key Key for the item.
50
- *
51
- * @return The value for the key, if a value exists.
52
- */
53
- get<T>(key: string): T | undefined {
54
- const cacheValue = cache.get(key);
55
-
56
- if (cacheValue) {
57
- if (new Date().getTime() < cacheValue.expiresAt) {
58
- return cacheValue.value as T;
59
- }
60
- }
61
- },
62
-
63
- /**
64
- * Set a value in the cache for a given key and TTL.
65
- *
66
- * @param key Key to identify the item.
67
- * @param value Value for the key.
68
- * @param ttl Number of milliseconds to consider the value fresh.
69
- */
70
- set<T>(key: string, value: T, ttl: number): void {
71
- cache.set(key, { expiresAt: new Date().getTime() + ttl, value });
72
- }
73
- };
74
- };
75
-
76
- /**
77
- * The largest page size allowed by the Prismic REST API V2. This value is used to minimize the number of requests required to query content.
20
+ * The largest page size allowed by the Prismic REST API V2. This value is used
21
+ * to minimize the number of requests required to query content.
78
22
  */
79
23
  const MAX_PAGE_SIZE = 100;
80
24
 
81
25
  /**
82
- * The number of milliseconds in which repository metadata is considered valid. A ref can be invalidated quickly depending on how frequently content is updated in the Prismic repository. As such, repository's metadata can only be considered valid for a short amount of time.
26
+ * The number of milliseconds in which repository metadata is considered valid.
27
+ * A ref can be invalidated quickly depending on how frequently content is
28
+ * updated in the Prismic repository. As such, repository's metadata can only be
29
+ * considered valid for a short amount of time.
83
30
  */
84
31
  export const REPOSITORY_CACHE_TTL = 5000;
85
32
 
86
33
  /**
87
- * A ref or a function that returns a ref. If a static ref is known, one can be given. If the ref must be fetched on-demand, a function can be provided. This function can optionally be asynchronous.
34
+ * Modes for client ref management.
88
35
  */
89
- type RefStringOrFn =
90
- | string
91
- | (() => string | undefined | Promise<string | undefined>);
92
-
93
- /**
94
- * State types for a client's ref strategy.
95
- */
96
- const enum RefStateType {
97
- /** Use the repository's master ref. */
98
- Master,
36
+ enum RefStateMode {
37
+ /**
38
+ * Use the repository's master ref.
39
+ */
40
+ Master = "Master",
99
41
 
100
- /** Use a given Release identified by its ID. */
101
- ReleaseByID,
42
+ /**
43
+ * Use a given Release identified by its ID.
44
+ */
45
+ ReleaseID = "ReleaseID",
102
46
 
103
- /** Use a given Release identified by its label. */
104
- ReleaseByLabel,
47
+ /**
48
+ * Use a given Release identified by its label.
49
+ */
50
+ ReleaseLabel = "ReleaseLabel",
105
51
 
106
- /** Use a given ref. */
107
- Manual
52
+ /**
53
+ * Use a given ref.
54
+ */
55
+ Manual = "Manual",
108
56
  }
109
57
 
110
58
  /**
111
59
  * An object containing stateful information about a client's ref strategy.
112
60
  */
113
61
  type RefState = {
114
- /** Determines if automatic preview support is enabled. */
62
+ /**
63
+ * Determines if automatic preview support is enabled.
64
+ */
115
65
  autoPreviewsEnabled: boolean;
116
66
 
117
- /** An optional HTTP server request object used during previews if automatic previews are enabled. */
67
+ /**
68
+ * An optional HTTP server request object used during previews if automatic
69
+ * previews are enabled.
70
+ */
118
71
  httpRequest?: HttpRequestLike;
119
72
  } & (
120
73
  | {
121
- type: RefStateType.Master;
74
+ mode: RefStateMode.Master;
122
75
  }
123
76
  | {
124
- type: RefStateType.ReleaseByID;
125
- payload: {
126
- /** The ID of the Release. */
127
- releaseId: string;
128
- };
77
+ mode: RefStateMode.ReleaseID;
78
+ releaseID: string;
129
79
  }
130
80
  | {
131
- type: RefStateType.ReleaseByLabel;
132
- payload: {
133
- /** The label of the Release. */
134
- releaseLabel: string;
135
- };
81
+ mode: RefStateMode.ReleaseLabel;
82
+ releaseLabel: string;
136
83
  }
137
84
  | {
138
- type: RefStateType.Manual;
139
- payload: {
140
- /** The user-provided ref or ref thunk. */
141
- refStringOrFn: RefStringOrFn;
142
- };
85
+ mode: RefStateMode.Manual;
86
+ ref: RefStringOrThunk;
143
87
  }
144
88
  );
145
89
 
90
+ /**
91
+ * A ref or a function that returns a ref. If a static ref is known, one can be
92
+ * given. If the ref must be fetched on-demand, a function can be provided. This
93
+ * function can optionally be asynchronous.
94
+ */
95
+ type RefStringOrThunk =
96
+ | string
97
+ | (() => string | undefined | Promise<string | undefined>);
98
+
146
99
  /**
147
100
  * Configuration for clients that determine how content is queried.
148
101
  */
149
102
  export type ClientConfig = {
150
103
  /**
151
- * The secure token for accessing the Prismic repository. This is only required if the repository is set to private.
104
+ * The secure token for accessing the Prismic repository. This is only
105
+ * required if the repository is set to private.
152
106
  */
153
107
  accessToken?: string;
154
108
 
155
109
  /**
156
- * A string representing a version of the Prismic repository's content. This may point to the latest version (called the "master ref"), or a preview with draft content.
110
+ * A string representing a version of the Prismic repository's content. This
111
+ * may point to the latest version (called the "master ref"), or a preview
112
+ * with draft content.
157
113
  */
158
- ref?: RefStringOrFn;
114
+ ref?: RefStringOrThunk;
159
115
 
160
116
  /**
161
- * Default parameters that will be sent with each query. These parameters can be overridden on each query if needed.
117
+ * A list of Route Resolver objects that define how a document's `url` field
118
+ * is resolved.
119
+ *
120
+ * {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
162
121
  */
163
- defaultParams?: Omit<BuildQueryURLArgs, "ref" | "accessToken">;
122
+ routes?: NonNullable<BuildQueryURLArgs["routes"]>;
164
123
 
165
124
  /**
166
- * The function used to make network requests to the Prismic REST API. In environments where a global `fetch` function does not exist, such as Node.js, this function must be provided.
125
+ * Default parameters that will be sent with each query. These parameters can
126
+ * be overridden on each query if needed.
127
+ */
128
+ defaultParams?: Omit<
129
+ BuildQueryURLArgs,
130
+ "ref" | "integrationFieldsRef" | "accessToken" | "routes"
131
+ >;
132
+
133
+ /**
134
+ * The function used to make network requests to the Prismic REST API. In
135
+ * environments where a global `fetch` function does not exist, such as
136
+ * Node.js, this function must be provided.
167
137
  */
168
138
  fetch?: FetchLike;
169
139
  };
170
140
 
171
141
  /**
172
- * Parameters specific to client methods that fetch all documents. These methods start with `getAll` (for example, `getAllByType`).
142
+ * Parameters specific to client methods that fetch all documents. These methods
143
+ * start with `getAll` (for example, `getAllByType`).
173
144
  */
174
145
  type GetAllParams = {
175
146
  /**
176
- * Limit the number of documents queried. If a number is not provided, there will be no limit and all matching documents will be returned.
147
+ * Limit the number of documents queried. If a number is not provided, there
148
+ * will be no limit and all matching documents will be returned.
177
149
  */
178
150
  limit?: number;
179
151
  };
@@ -185,7 +157,7 @@ type ResolvePreviewArgs = {
185
157
  /**
186
158
  * A function that maps a Prismic document to a URL within your app.
187
159
  */
188
- linkResolver: prismicH.LinkResolverFunction;
160
+ linkResolver?: prismicH.LinkResolverFunction;
189
161
 
190
162
  /**
191
163
  * A fallback URL if the Link Resolver does not return a value.
@@ -193,20 +165,21 @@ type ResolvePreviewArgs = {
193
165
  defaultURL: string;
194
166
 
195
167
  /**
196
- * The preview token (also known as a ref) that will be used to query preview content from the Prismic repository.
168
+ * The preview token (also known as a ref) that will be used to query preview
169
+ * content from the Prismic repository.
197
170
  */
198
171
  previewToken?: string;
199
172
 
200
173
  /**
201
174
  * The previewed document that will be used to determine the destination URL.
202
175
  */
203
- documentId?: string;
176
+ documentID?: string;
204
177
  };
205
178
 
206
179
  /**
207
180
  * Creates a predicate to filter content by document type.
208
181
  *
209
- * @param documentType The document type to filter queried content.
182
+ * @param documentType - The document type to filter queried content.
210
183
  *
211
184
  * @returns A predicate that can be used in a Prismic REST API V2 request.
212
185
  */
@@ -214,40 +187,34 @@ const typePredicate = (documentType: string): string =>
214
187
  predicate.at("document.type", documentType);
215
188
 
216
189
  /**
217
- * Creates a predicate to filter content by document tags.
190
+ * Creates a predicate to filter content by document tags. All tags are required
191
+ * on the document.
218
192
  *
219
- * @param documentType Document tags to filter queried content.
193
+ * @param documentType - Document tags to filter queried content.
220
194
  *
221
195
  * @returns A predicate that can be used in a Prismic REST API V2 request.
222
196
  */
223
- const tagsPredicate = (tags: string | string[]): string =>
197
+ const everyTagPredicate = (tags: string | string[]): string =>
224
198
  predicate.at("document.tags", tags);
225
199
 
226
200
  /**
227
- * Returns the first ref from a list that passes a predicate (a function that returns true).
228
- *
229
- * @throws If a matching ref cannot be found.
201
+ * Creates a predicate to filter content by document tags. At least one matching
202
+ * tag is required on the document.
230
203
  *
231
- * @param refs A list of refs to search.
232
- * @param predicate A function that determines if a ref from the list matches the criteria.
204
+ * @param documentType - Document tags to filter queried content.
233
205
  *
234
- * @returns The first matching ref.
206
+ * @returns A predicate that can be used in a Prismic REST API V2 request.
235
207
  */
236
- const findRef = (refs: Ref[], predicate: (ref: Ref) => boolean): Ref => {
237
- const ref = refs.find(ref => predicate(ref));
238
-
239
- if (!ref) {
240
- throw new Error("Ref could not be found.");
241
- }
242
-
243
- return ref;
244
- };
208
+ const someTagsPredicate = (tags: string | string[]): string =>
209
+ predicate.any("document.tags", tags);
245
210
 
246
211
  /**
247
212
  * Creates a Prismic client that can be used to query a repository.
248
213
  *
249
- * @param endpoint The Prismic REST API V2 endpoint for the repository (use `prismic.getEndpoint` for the default endpoint).
250
- * @param options Configuration that determines how content will be queried from the Prismic repository.
214
+ * @param endpoint - The Prismic REST API V2 endpoint for the repository (use
215
+ * `prismic.getEndpoint` for the default endpoint).
216
+ * @param options - Configuration that determines how content will be queried
217
+ * from the Prismic repository.
251
218
  *
252
219
  * @returns A client that can query content from the repository.
253
220
  */
@@ -258,60 +225,86 @@ export const createClient = (
258
225
  /**
259
226
  * A client that allows querying content from a Prismic repository.
260
227
  *
261
- * If used in an environment where a global `fetch` function is unavailable, such as Node.js, the `fetch` option must be provided as part of the `options` parameter.
228
+ * If used in an environment where a global `fetch` function is unavailable,
229
+ * such as Node.js, the `fetch` option must be provided as part of the `options`
230
+ * parameter.
262
231
  */
263
232
  export class Client {
264
233
  /**
265
- * The Prismic REST API V2 endpoint for the repository (use `prismic.getEndpoint` for the default endpoint).
234
+ * The Prismic REST API V2 endpoint for the repository (use
235
+ * `prismic.getEndpoint` for the default endpoint).
266
236
  */
267
237
  endpoint: string;
268
238
 
269
239
  /**
270
- * The secure token for accessing the API (only needed if your repository is set to private).
240
+ * The secure token for accessing the API (only needed if your repository is
241
+ * set to private).
271
242
  *
272
243
  * {@link https://user-guides.prismic.io/en/articles/1036153-generating-an-access-token}
273
244
  */
274
245
  accessToken?: string;
275
246
 
276
247
  /**
277
- * The function used to make network requests to the Prismic REST API. In environments where a global `fetch` function does not exist, such as Node.js, this function must be provided.
248
+ * A list of Route Resolver objects that define how a document's `url` field
249
+ * is resolved.
250
+ *
251
+ * {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
252
+ */
253
+ routes?: NonNullable<BuildQueryURLArgs["routes"]>;
254
+
255
+ /**
256
+ * The function used to make network requests to the Prismic REST API. In
257
+ * environments where a global `fetch` function does not exist, such as
258
+ * Node.js, this function must be provided.
278
259
  */
279
260
  fetchFn: FetchLike;
280
261
 
281
262
  /**
282
- * Default parameters that will be sent with each query. These parameters can be overridden on each query if needed.
263
+ * Default parameters that will be sent with each query. These parameters can
264
+ * be overridden on each query if needed.
283
265
  */
284
- defaultParams?: Omit<BuildQueryURLArgs, "ref">;
266
+ defaultParams?: Omit<
267
+ BuildQueryURLArgs,
268
+ "ref" | "integrationFieldsRef" | "accessToken" | "routes"
269
+ >;
285
270
 
286
271
  /**
287
272
  * The client's ref mode state. This determines which ref is used during queries.
288
273
  */
289
- private refMode: RefState;
274
+ private refState: RefState = {
275
+ mode: RefStateMode.Master,
276
+ autoPreviewsEnabled: true,
277
+ };
278
+
279
+ /**
280
+ * Cached repository value.
281
+ */
282
+ private cachedRepository: prismicT.Repository | undefined;
290
283
 
291
284
  /**
292
- * Internal cache for low-level caching.
285
+ * Timestamp at which the cached repository data is considered stale.
293
286
  */
294
- private internalCache: SimpleTTLCache;
287
+ private cachedRepositoryExpiration = 0;
295
288
 
296
289
  /**
297
290
  * Creates a Prismic client that can be used to query a repository.
298
291
  *
299
- * If used in an environment where a global `fetch` function is unavailable, such as Node.js, the `fetch` option must be provided as part of the `options` parameter.
292
+ * If used in an environment where a global `fetch` function is unavailable,
293
+ * such as Node.js, the `fetch` option must be provided as part of the
294
+ * `options` parameter.
300
295
  *
301
- * @param endpoint The Prismic REST API V2 endpoint for the repository (use `prismic.getEndpoint` to get the default endpoint).
302
- * @param options Configuration that determines how content will be queried from the Prismic repository.
296
+ * @param endpoint - The Prismic REST API V2 endpoint for the repository (use
297
+ * `prismic.getEndpoint` to get the default endpoint).
298
+ * @param options - Configuration that determines how content will be queried
299
+ * from the Prismic repository.
303
300
  *
304
301
  * @returns A client that can query content from the repository.
305
302
  */
306
303
  constructor(endpoint: string, options: ClientConfig = {}) {
307
304
  this.endpoint = endpoint;
308
305
  this.accessToken = options.accessToken;
306
+ this.routes = options.routes;
309
307
  this.defaultParams = options.defaultParams;
310
- this.internalCache = createSimpleTTLCache();
311
- this.refMode = {
312
- type: RefStateType.Master,
313
- autoPreviewsEnabled: true
314
- };
315
308
 
316
309
  if (options.ref) {
317
310
  this.queryContentFromRef(options.ref);
@@ -322,8 +315,10 @@ export class Client {
322
315
  } else if (typeof globalThis.fetch === "function") {
323
316
  this.fetchFn = globalThis.fetch;
324
317
  } else {
325
- throw new Error(
326
- "A valid fetch implementation was not provided. In environments where fetch is not available (including Node.js), a fetch implementation must be provided via a polyfill or the `fetch` option."
318
+ throw new PrismicError(
319
+ "A valid fetch implementation was not provided. In environments where fetch is not available (including Node.js), a fetch implementation must be provided via a polyfill or the `fetch` option.",
320
+ undefined,
321
+ undefined,
327
322
  );
328
323
  }
329
324
 
@@ -334,137 +329,163 @@ export class Client {
334
329
  }
335
330
 
336
331
  /**
337
- * Enables the client to automatically query content from a preview session if one is active in browser environments. This is enabled by default in the browser.
332
+ * Enables the client to automatically query content from a preview session if
333
+ * one is active in browser environments. This is enabled by default in the browser.
338
334
  *
339
335
  * For server environments, use `enableAutoPreviewsFromReq`.
340
336
  *
341
- * @see enableAutoPreviewsFromReq
342
- *
343
337
  * @example
338
+ *
344
339
  * ```ts
345
- * client.enableAutoPreviews()
340
+ * client.enableAutoPreviews();
346
341
  * ```
342
+ *
343
+ * @see enableAutoPreviewsFromReq
347
344
  */
348
345
  enableAutoPreviews(): void {
349
- this.refMode.autoPreviewsEnabled = true;
346
+ this.refState.autoPreviewsEnabled = true;
350
347
  }
351
348
 
352
349
  /**
353
- * Enables the client to automatically query content from a preview session if one is active in server environments. This is disabled by default on the server.
350
+ * Enables the client to automatically query content from a preview session if
351
+ * one is active in server environments. This is disabled by default on the server.
354
352
  *
355
353
  * For browser environments, use `enableAutoPreviews`.
356
354
  *
357
- * @param req An HTTP server request object containing the request's cookies.
358
- *
359
355
  * @example
356
+ *
360
357
  * ```ts
361
358
  * // In an express app
362
- * app.get('/', function (req, res) {
363
- * client.enableAutoPreviewsFromReq(req)
364
- * })
359
+ * app.get("/", function (req, res) {
360
+ * client.enableAutoPreviewsFromReq(req);
361
+ * });
365
362
  * ```
363
+ *
364
+ * @param req - An HTTP server request object containing the request's cookies.
366
365
  */
367
366
  enableAutoPreviewsFromReq<R extends HttpRequestLike>(req: R): void {
368
- this.refMode.httpRequest = req;
369
- this.refMode.autoPreviewsEnabled = true;
367
+ this.refState.httpRequest = req;
368
+ this.refState.autoPreviewsEnabled = true;
370
369
  }
371
370
 
372
371
  /**
373
- * Disables the client from automatically querying content from a preview session if one is active.
372
+ * Disables the client from automatically querying content from a preview
373
+ * session if one is active.
374
374
  *
375
- * Automatic preview content querying is enabled by default unless this method is called.
375
+ * Automatic preview content querying is enabled by default unless this method
376
+ * is called.
376
377
  *
377
378
  * @example
379
+ *
378
380
  * ```ts
379
- * client.disableAutoPreviews()
381
+ * client.disableAutoPreviews();
380
382
  * ```
381
383
  */
382
384
  disableAutoPreviews(): void {
383
- this.refMode.autoPreviewsEnabled = false;
385
+ this.refState.autoPreviewsEnabled = false;
384
386
  }
385
387
 
386
388
  /**
387
389
  * Queries content from the Prismic repository.
388
390
  *
389
- * @typeParam TDocument Type of Prismic documents returned.
390
- * @param params Parameters to filter, sort, and paginate results.
391
- *
392
- * @returns A paginated response containing the result of the query.
391
+ * @deprecated Use `get` instead.
392
+ * @example
393
393
  *
394
394
  * ```ts
395
- * const response = await client.get()
395
+ * const response = await client.query(
396
+ * prismic.predicate.at("document.type", "page"),
397
+ * );
396
398
  * ```
397
399
  *
398
- * @deprecated Use `get` instead.
400
+ * @typeParam TDocument - Type of Prismic documents returned.
401
+ * @param params - Parameters to filter, sort, and paginate results.
402
+ *
403
+ * @returns A paginated response containing the result of the query.
399
404
  */
400
- query = this.get.bind(this);
405
+ async query<TDocument extends prismicT.PrismicDocument>(
406
+ predicates: NonNullable<BuildQueryURLArgs["predicates"]>,
407
+ params?: Partial<Omit<BuildQueryURLArgs, "predicates">>,
408
+ ): Promise<prismicT.Query<TDocument>> {
409
+ const url = await this.buildQueryURL({ ...params, predicates });
410
+
411
+ return await this.fetch<prismicT.Query<TDocument>>(url, params);
412
+ }
401
413
 
402
414
  /**
403
415
  * Queries content from the Prismic repository.
404
416
  *
405
- * @typeParam TDocument Type of Prismic documents returned.
406
- * @param params Parameters to filter, sort, and paginate results.
407
- *
408
- * @returns A paginated response containing the result of the query.
417
+ * @example
409
418
  *
410
419
  * ```ts
411
- * const response = await client.get()
420
+ * const response = await client.get();
412
421
  * ```
422
+ *
423
+ * @typeParam TDocument - Type of Prismic documents returned.
424
+ * @param params - Parameters to filter, sort, and paginate results.
425
+ *
426
+ * @returns A paginated response containing the result of the query.
413
427
  */
414
428
  async get<TDocument extends prismicT.PrismicDocument>(
415
- params?: Partial<BuildQueryURLArgs>
416
- ): Promise<Query<TDocument>> {
429
+ params?: Partial<BuildQueryURLArgs>,
430
+ ): Promise<prismicT.Query<TDocument>> {
417
431
  const url = await this.buildQueryURL(params);
418
432
 
419
- return await this.fetch<Query<TDocument>>(url, params);
433
+ return await this.fetch<prismicT.Query<TDocument>>(url, params);
420
434
  }
421
435
 
422
436
  /**
423
- * Queries content from the Prismic repository and returns only the first result, if any.
424
- *
425
- * @typeParam TDocument Type of the Prismic document returned.
426
- * @param params Parameters to filter, sort, and paginate results.
427
- *
428
- * @returns The first result of the query, if any.
437
+ * Queries content from the Prismic repository and returns only the first
438
+ * result, if any.
429
439
  *
430
440
  * @example
441
+ *
431
442
  * ```ts
432
- * const document = await client.getFirst()
443
+ * const document = await client.getFirst();
433
444
  * ```
445
+ *
446
+ * @typeParam TDocument - Type of the Prismic document returned.
447
+ * @param params - Parameters to filter, sort, and paginate results. @returns
448
+ * The first result of the query, if any.
434
449
  */
435
450
  async getFirst<TDocument extends prismicT.PrismicDocument>(
436
- params?: Partial<BuildQueryURLArgs>
451
+ params?: Partial<BuildQueryURLArgs>,
437
452
  ): Promise<TDocument> {
438
- const result = await this.get<TDocument>(params);
453
+ const url = await this.buildQueryURL(params);
454
+ const result = await this.fetch<prismicT.Query<TDocument>>(url, params);
455
+
439
456
  const firstResult = result.results[0];
440
457
 
441
458
  if (firstResult) {
442
459
  return firstResult;
443
460
  }
444
461
 
445
- throw new Error("No documents were returned");
462
+ throw new PrismicError("No documents were returned", url, undefined);
446
463
  }
447
464
 
448
465
  /**
449
- * Queries content from the Prismic repository and returns all matching content. If no predicates are provided, all documents will be fetched.
466
+ * Queries content from the Prismic repository and returns all matching
467
+ * content. If no predicates are provided, all documents will be fetched.
450
468
  *
451
469
  * This method may make multiple network requests to query all matching content.
452
470
  *
453
- * @typeParam TDocument Type of Prismic documents returned.
454
- * @param params Parameters to filter, sort, and paginate results.
455
- *
456
- * @returns A list of documents matching the query.
457
- *
458
471
  * @example
472
+ *
459
473
  * ```ts
460
- * const response = await client.getAll()
474
+ * const response = await client.getAll();
461
475
  * ```
476
+ *
477
+ * @typeParam TDocument - Type of Prismic documents returned. @param params -
478
+ * Parameters to filter, sort, and paginate results. @returns A list of
479
+ * documents matching the query.
462
480
  */
463
481
  async getAll<TDocument extends prismicT.PrismicDocument>(
464
- params: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams = {}
482
+ params: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams = {},
465
483
  ): Promise<TDocument[]> {
466
484
  const { limit = Infinity, ...actualParams } = params;
467
- const resolvedParams = { pageSize: MAX_PAGE_SIZE, ...actualParams };
485
+ const resolvedParams = {
486
+ ...actualParams,
487
+ pageSize: actualParams.pageSize || MAX_PAGE_SIZE,
488
+ };
468
489
 
469
490
  const result = await this.get<TDocument>(resolvedParams);
470
491
 
@@ -484,26 +505,28 @@ export class Client {
484
505
  * Queries a document from the Prismic repository with a specific ID.
485
506
  *
486
507
  * @remarks
487
- *
488
- * A document's UID is different from its ID. An ID is automatically generated for all documents and is made available on its `id` property. A UID is provided in the Prismic editor and is unique among all documents of its Custom Type.
489
- *
490
- * @typeParam TDocument Type of the Prismic document returned.
491
- * @param id ID of the document.
492
- * @param params Parameters to filter, sort, and paginate the results.
493
- *
494
- * @returns The document with an ID matching the `id` parameter, if a matching document exists.
495
- *
508
+ * A document's UID is different from its ID. An ID is automatically generated
509
+ * for all documents and is made available on its `id` property. A UID is
510
+ * provided in the Prismic editor and is unique among all documents of its Custom Type.
496
511
  * @example
512
+ *
497
513
  * ```ts
498
- * const document = await client.getByID('WW4bKScAAMAqmluX')
514
+ * const document = await client.getByID("WW4bKScAAMAqmluX");
499
515
  * ```
516
+ *
517
+ * @typeParam TDocument- Type of the Prismic document returned.
518
+ * @param id - ID of the document.
519
+ * @param params - Parameters to filter, sort, and paginate the results.
520
+ *
521
+ * @returns The document with an ID matching the `id` parameter, if a matching
522
+ * document exists.
500
523
  */
501
524
  async getByID<TDocument extends prismicT.PrismicDocument>(
502
525
  id: string,
503
- params?: Partial<BuildQueryURLArgs>
526
+ params?: Partial<BuildQueryURLArgs>,
504
527
  ): Promise<TDocument> {
505
528
  return await this.getFirst<TDocument>(
506
- appendPredicates(predicate.at("document.id", id))(params)
529
+ appendPredicates(params, predicate.at("document.id", id)),
507
530
  );
508
531
  }
509
532
 
@@ -511,26 +534,31 @@ export class Client {
511
534
  * Queries documents from the Prismic repository with specific IDs.
512
535
  *
513
536
  * @remarks
514
- *
515
- * A document's UID is different from its ID. An ID is automatically generated for all documents and is made available on its `id` property. A UID is provided in the Prismic editor and is unique among all documents of its Custom Type.
516
- *
517
- * @typeParam TDocument Type of Prismic documents returned.
518
- * @param ids A list of document IDs.
519
- * @param params Parameters to filter, sort, and paginate the results.
520
- *
521
- * @returns A paginated response containing documents with IDs matching the `ids` parameter.
522
- *
537
+ * A document's UID is different from its ID. An ID is automatically generated
538
+ * for all documents and is made available on its `id` property. A UID is
539
+ * provided in the Prismic editor and is unique among all documents of its Custom Type.
523
540
  * @example
541
+ *
524
542
  * ```ts
525
- * const response = await client.getByIDs(['WW4bKScAAMAqmluX', 'U1kTRgEAAC8A5ldS'])
543
+ * const response = await client.getByIDs([
544
+ * "WW4bKScAAMAqmluX",
545
+ * "U1kTRgEAAC8A5ldS",
546
+ * ]);
526
547
  * ```
548
+ *
549
+ * @typeParam TDocument - Type of Prismic documents returned.
550
+ * @param ids - A list of document IDs.
551
+ * @param params - Parameters to filter, sort, and paginate the results.
552
+ *
553
+ * @returns A paginated response containing documents with IDs matching the
554
+ * `ids` parameter.
527
555
  */
528
556
  async getByIDs<TDocument extends prismicT.PrismicDocument>(
529
557
  ids: string[],
530
- params?: Partial<BuildQueryURLArgs>
531
- ): Promise<Query<TDocument>> {
558
+ params?: Partial<BuildQueryURLArgs>,
559
+ ): Promise<prismicT.Query<TDocument>> {
532
560
  return await this.get<TDocument>(
533
- appendPredicates(predicate.in("document.id", ids))(params)
561
+ appendPredicates(params, predicate.in("document.id", ids)),
534
562
  );
535
563
  }
536
564
 
@@ -540,26 +568,30 @@ export class Client {
540
568
  * This method may make multiple network requests to query all matching content.
541
569
  *
542
570
  * @remarks
543
- *
544
- * A document's UID is different from its ID. An ID is automatically generated for all documents and is made available on its `id` property. A UID is provided in the Prismic editor and is unique among all documents of its Custom Type.
545
- *
546
- * @typeParam TDocument Type of Prismic documents returned.
547
- * @param ids A list of document IDs.
548
- * @param params Parameters to filter, sort, and paginate the results.
549
- *
550
- * @returns A list of documents with IDs matching the `ids` parameter, if a matching document exists.
551
- *
571
+ * A document's UID is different from its ID. An ID is automatically generated
572
+ * for all documents and is made available on its `id` property. A UID is
573
+ * provided in the Prismic editor and is unique among all documents of its Custom Type.
552
574
  * @example
575
+ *
553
576
  * ```ts
554
- * const response = await client.getAllByIDs(['WW4bKScAAMAqmluX', 'U1kTRgEAAC8A5ldS'])
577
+ * const response = await client.getAllByIDs([
578
+ * "WW4bKScAAMAqmluX",
579
+ * "U1kTRgEAAC8A5ldS",
580
+ * ]);
555
581
  * ```
582
+ *
583
+ * @typeParam TDocument - Type of Prismic documents returned.
584
+ * @param ids - A list of document IDs.
585
+ * @param params - Parameters to filter, sort, and paginate the results.
586
+ *
587
+ * @returns A list of documents with IDs matching the `ids` parameter.
556
588
  */
557
589
  async getAllByIDs<TDocument extends prismicT.PrismicDocument>(
558
590
  ids: string[],
559
- params?: Partial<BuildQueryURLArgs>
591
+ params?: Partial<BuildQueryURLArgs>,
560
592
  ): Promise<TDocument[]> {
561
593
  return await this.getAll<TDocument>(
562
- appendPredicates(predicate.in("document.id", ids))(params)
594
+ appendPredicates(params, predicate.in("document.id", ids)),
563
595
  );
564
596
  }
565
597
 
@@ -567,83 +599,164 @@ export class Client {
567
599
  * Queries a document from the Prismic repository with a specific UID and Custom Type.
568
600
  *
569
601
  * @remarks
570
- *
571
- * A document's UID is different from its ID. An ID is automatically generated for all documents and is made available on its `id` property. A UID is provided in the Prismic editor and is unique among all documents of its Custom Type.
572
- *
573
- * @typeParam TDocument Type of the Prismic document returned.
574
- * @param documentType The API ID of the document's Custom Type.
575
- * @param uid UID of the document.
576
- * @param params Parameters to filter, sort, and paginate the results.
577
- *
578
- * @returns The document with a UID matching the `uid` parameter, if a matching document exists.
579
- *
602
+ * A document's UID is different from its ID. An ID is automatically generated
603
+ * for all documents and is made available on its `id` property. A UID is
604
+ * provided in the Prismic editor and is unique among all documents of its Custom Type.
580
605
  * @example
606
+ *
581
607
  * ```ts
582
- * const document = await client.getByUID('blog_post', 'my-first-post')
608
+ * const document = await client.getByUID("blog_post", "my-first-post");
583
609
  * ```
610
+ *
611
+ * @typeParam TDocument - Type of the Prismic document returned.
612
+ * @param documentType - The API ID of the document's Custom Type.
613
+ * @param uid - UID of the document.
614
+ * @param params - Parameters to filter, sort, and paginate the results.
615
+ *
616
+ * @returns The document with a UID matching the `uid` parameter, if a
617
+ * matching document exists.
584
618
  */
585
619
  async getByUID<TDocument extends prismicT.PrismicDocument>(
586
620
  documentType: string,
587
621
  uid: string,
588
- params?: Partial<BuildQueryURLArgs>
622
+ params?: Partial<BuildQueryURLArgs>,
589
623
  ): Promise<TDocument> {
590
624
  return await this.getFirst<TDocument>(
591
- appendPredicates(
625
+ appendPredicates(params, [
592
626
  typePredicate(documentType),
593
- predicate.at(`my.${documentType}.uid`, uid)
594
- )(params)
627
+ predicate.at(`my.${documentType}.uid`, uid),
628
+ ]),
595
629
  );
596
630
  }
597
631
 
598
632
  /**
599
- * Queries a singleton document from the Prismic repository for a specific Custom Type.
633
+ * Queries document from the Prismic repository with specific UIDs and Custom Type.
600
634
  *
601
635
  * @remarks
636
+ * A document's UID is different from its ID. An ID is automatically generated
637
+ * for all documents and is made available on its `id` property. A UID is
638
+ * provided in the Prismic editor and is unique among all documents of its Custom Type.
639
+ * @example
602
640
  *
603
- * A singleton document is one that is configured in Prismic to only allow one instance. For example, a repository may be configured to contain just one Settings document. This is in contrast to a repeatable Custom Type which allows multiple instances of itself.
641
+ * ```ts
642
+ * const document = await client.getByUIDs("blog_post", [
643
+ * "my-first-post",
644
+ * "my-second-post",
645
+ * ]);
646
+ * ```
604
647
  *
605
- * @typeParam TDocument Type of the Prismic document returned.
606
- * @param documentType The API ID of the singleton Custom Type.
607
- * @param params Parameters to filter, sort, and paginate the results.
648
+ * @typeParam TDocument - Type of the Prismic document returned.
649
+ * @param documentType - The API ID of the document's Custom Type.
650
+ * @param uids - A list of document UIDs.
651
+ * @param params - Parameters to filter, sort, and paginate the results.
608
652
  *
609
- * @returns The singleton document for the Custom Type, if a matching document exists.
653
+ * @returns A paginated response containing documents with UIDs matching the
654
+ * `uids` parameter.
655
+ */
656
+ async getByUIDs<TDocument extends prismicT.PrismicDocument>(
657
+ documentType: string,
658
+ uids: string[],
659
+ params?: Partial<BuildQueryURLArgs>,
660
+ ): Promise<prismicT.Query<TDocument>> {
661
+ return await this.get<TDocument>(
662
+ appendPredicates(params, [
663
+ typePredicate(documentType),
664
+ predicate.in(`my.${documentType}.uid`, uids),
665
+ ]),
666
+ );
667
+ }
668
+
669
+ /**
670
+ * Queries all documents from the Prismic repository with specific UIDs and Custom Type.
610
671
  *
672
+ * This method may make multiple network requests to query all matching content.
673
+ *
674
+ * @remarks
675
+ * A document's UID is different from its ID. An ID is automatically generated
676
+ * for all documents and is made available on its `id` property. A UID is
677
+ * provided in the Prismic editor and is unique among all documents of its Custom Type.
611
678
  * @example
679
+ *
612
680
  * ```ts
613
- * const document = await client.getSingle('settings')
681
+ * const response = await client.getAllByUIDs([
682
+ * "my-first-post",
683
+ * "my-second-post",
684
+ * ]);
614
685
  * ```
686
+ *
687
+ * @typeParam TDocument - Type of Prismic documents returned.
688
+ * @param documentType - The API ID of the document's Custom Type.
689
+ * @param uids - A list of document UIDs.
690
+ * @param params - Parameters to filter, sort, and paginate the results.
691
+ *
692
+ * @returns A list of documents with UIDs matching the `uids` parameter.
693
+ */
694
+ async getAllByUIDs<TDocument extends prismicT.PrismicDocument>(
695
+ documentType: string,
696
+ uids: string[],
697
+ params?: Partial<BuildQueryURLArgs>,
698
+ ): Promise<TDocument[]> {
699
+ return await this.getAll<TDocument>(
700
+ appendPredicates(params, [
701
+ typePredicate(documentType),
702
+ predicate.in(`my.${documentType}.uid`, uids),
703
+ ]),
704
+ );
705
+ }
706
+
707
+ /**
708
+ * Queries a singleton document from the Prismic repository for a specific Custom Type.
709
+ *
710
+ * @remarks
711
+ * A singleton document is one that is configured in Prismic to only allow one
712
+ * instance. For example, a repository may be configured to contain just one
713
+ * Settings document. This is in contrast to a repeatable Custom Type which
714
+ * allows multiple instances of itself.
715
+ * @example
716
+ *
717
+ * ```ts
718
+ * const document = await client.getSingle("settings");
719
+ * ```
720
+ *
721
+ * @typeParam TDocument - Type of the Prismic document returned.
722
+ * @param documentType - The API ID of the singleton Custom Type.
723
+ * @param params - Parameters to filter, sort, and paginate the results.
724
+ *
725
+ * @returns The singleton document for the Custom Type, if a matching document exists.
615
726
  */
616
727
  async getSingle<TDocument extends prismicT.PrismicDocument>(
617
728
  documentType: string,
618
- params?: Partial<BuildQueryURLArgs>
729
+ params?: Partial<BuildQueryURLArgs>,
619
730
  ): Promise<TDocument> {
620
731
  return await this.getFirst<TDocument>(
621
- appendPredicates(typePredicate(documentType))(params)
732
+ appendPredicates(params, typePredicate(documentType)),
622
733
  );
623
734
  }
624
735
 
625
736
  /**
626
737
  * Queries documents from the Prismic repository for a specific Custom Type.
627
738
  *
628
- * Use `getAllByType` instead if you need to query all documents for a specific Custom Type.
629
- *
630
- * @typeParam TDocument Type of Prismic documents returned.
631
- * @param documentType The API ID of the Custom Type.
632
- * @param params Parameters to filter, sort, and paginate the results.
633
- *
634
- * @returns A paginated response containing documents of the Custom Type.
739
+ * Use `getAllByType` instead if you need to query all documents for a
740
+ * specific Custom Type.
635
741
  *
636
742
  * @example
743
+ *
637
744
  * ```ts
638
- * const response = await client.getByType('blog_post')
745
+ * const response = await client.getByType("blog_post");
639
746
  * ```
747
+ *
748
+ * @typeParam TDocument - Type of Prismic documents returned.
749
+ * @param documentType - The API ID of the Custom Type.
750
+ * @param params - Parameters to filter, sort, and paginate the results.
751
+ *
752
+ * @returns A paginated response containing documents of the Custom Type.
640
753
  */
641
754
  async getByType<TDocument extends prismicT.PrismicDocument>(
642
755
  documentType: string,
643
- params?: Partial<BuildQueryURLArgs>
644
- ): Promise<Query<TDocument>> {
756
+ params?: Partial<BuildQueryURLArgs>,
757
+ ): Promise<prismicT.Query<TDocument>> {
645
758
  return await this.get<TDocument>(
646
- appendPredicates(typePredicate(documentType))(params)
759
+ appendPredicates(params, typePredicate(documentType)),
647
760
  );
648
761
  }
649
762
 
@@ -652,23 +765,24 @@ export class Client {
652
765
  *
653
766
  * This method may make multiple network requests to query all matching content.
654
767
  *
655
- * @typeParam TDocument Type of Prismic documents returned.
656
- * @param documentType The API ID of the Custom Type.
657
- * @param params Parameters to filter, sort, and paginate the results.
658
- *
659
- * @returns A list of all documents of the Custom Type.
660
- *
661
768
  * @example
769
+ *
662
770
  * ```ts
663
- * const response = await client.getByType('blog_post')
771
+ * const response = await client.getByType("blog_post");
664
772
  * ```
773
+ *
774
+ * @typeParam TDocument - Type of Prismic documents returned.
775
+ * @param documentType - The API ID of the Custom Type.
776
+ * @param params - Parameters to filter, sort, and paginate the results.
777
+ *
778
+ * @returns A list of all documents of the Custom Type.
665
779
  */
666
780
  async getAllByType<TDocument extends prismicT.PrismicDocument>(
667
781
  documentType: string,
668
- params?: Partial<Omit<BuildQueryURLArgs, "page">>
782
+ params?: Partial<Omit<BuildQueryURLArgs, "page">>,
669
783
  ): Promise<TDocument[]> {
670
784
  return await this.getAll<TDocument>(
671
- appendPredicates(typePredicate(documentType))(params)
785
+ appendPredicates(params, typePredicate(documentType)),
672
786
  );
673
787
  }
674
788
 
@@ -677,23 +791,24 @@ export class Client {
677
791
  *
678
792
  * Use `getAllByTag` instead if you need to query all documents with a specific tag.
679
793
  *
680
- * @typeParam TDocument Type of Prismic documents returned.
681
- * @param tag The tag that must be included on a document.
682
- * @param params Parameters to filter, sort, and paginate the results.
683
- *
684
- * @returns A paginated response containing documents with the tag.
685
- *
686
794
  * @example
795
+ *
687
796
  * ```ts
688
- * const response = await client.getByTag('food')
797
+ * const response = await client.getByTag("food");
689
798
  * ```
799
+ *
800
+ * @typeParam TDocument - Type of Prismic documents returned.
801
+ * @param tag - The tag that must be included on a document.
802
+ * @param params - Parameters to filter, sort, and paginate the results.
803
+ *
804
+ * @returns A paginated response containing documents with the tag.
690
805
  */
691
806
  async getByTag<TDocument extends prismicT.PrismicDocument>(
692
807
  tag: string,
693
- params?: Partial<BuildQueryURLArgs>
694
- ): Promise<Query<TDocument>> {
808
+ params?: Partial<BuildQueryURLArgs>,
809
+ ): Promise<prismicT.Query<TDocument>> {
695
810
  return await this.get<TDocument>(
696
- appendPredicates(tagsPredicate(tag))(params)
811
+ appendPredicates(params, everyTagPredicate(tag)),
697
812
  );
698
813
  }
699
814
 
@@ -702,168 +817,230 @@ export class Client {
702
817
  *
703
818
  * This method may make multiple network requests to query all matching content.
704
819
  *
705
- * @typeParam TDocument Type of Prismic documents returned.
706
- * @param tag The tag that must be included on a document.
707
- * @param params Parameters to filter, sort, and paginate the results.
708
- *
709
- * @returns A list of all documents with the tag.
710
- *
711
820
  * @example
821
+ *
712
822
  * ```ts
713
- * const response = await client.getAllByTag('food')
823
+ * const response = await client.getAllByTag("food");
714
824
  * ```
825
+ *
826
+ * @typeParam TDocument - Type of Prismic documents returned.
827
+ * @param tag - The tag that must be included on a document.
828
+ * @param params - Parameters to filter, sort, and paginate the results.
829
+ *
830
+ * @returns A list of all documents with the tag.
715
831
  */
716
832
  async getAllByTag<TDocument extends prismicT.PrismicDocument>(
717
833
  tag: string,
718
- params?: Partial<Omit<BuildQueryURLArgs, "page">>
834
+ params?: Partial<Omit<BuildQueryURLArgs, "page">>,
719
835
  ): Promise<TDocument[]> {
720
836
  return await this.getAll<TDocument>(
721
- appendPredicates(tagsPredicate(tag))(params)
837
+ appendPredicates(params, everyTagPredicate(tag)),
722
838
  );
723
839
  }
724
840
 
725
841
  /**
726
- * Queries documents from the Prismic repository with a specific tag.
727
- *
728
- * @typeParam TDocument Type of Prismic documents returned.
729
- * @param tags A list of tags that must be included on a document.
730
- * @param params Parameters to filter, sort, and paginate the results.
731
- *
732
- * @returns A paginated response containing documents with the tag.
842
+ * Queries documents from the Prismic repository with specific tags. A
843
+ * document must be tagged with all of the queried tags to be included.
733
844
  *
734
845
  * @example
846
+ *
735
847
  * ```ts
736
- * const response = await client.getAllByTag('food')
848
+ * const response = await client.getByEveryTag(["food", "fruit"]);
737
849
  * ```
850
+ *
851
+ * @typeParam TDocument - Type of Prismic documents returned.
852
+ * @param tags - A list of tags that must be included on a document.
853
+ * @param params - Parameters to filter, sort, and paginate the results.
854
+ *
855
+ * @returns A paginated response containing documents with the tags.
738
856
  */
739
- async getByTags<TDocument extends prismicT.PrismicDocument>(
857
+ async getByEveryTag<TDocument extends prismicT.PrismicDocument>(
740
858
  tags: string[],
741
- params?: Partial<BuildQueryURLArgs>
742
- ): Promise<Query<TDocument>> {
859
+ params?: Partial<BuildQueryURLArgs>,
860
+ ): Promise<prismicT.Query<TDocument>> {
743
861
  return await this.get<TDocument>(
744
- appendPredicates(tagsPredicate(tags))(params)
862
+ appendPredicates(params, everyTagPredicate(tags)),
745
863
  );
746
864
  }
747
865
 
748
866
  /**
749
- * Queries all documents from the Prismic repository with a specific tag.
867
+ * Queries documents from the Prismic repository with specific tags. A
868
+ * document must be tagged with all of the queried tags to be included.
750
869
  *
751
870
  * This method may make multiple network requests to query all matching content.
752
871
  *
753
- * @typeParam TDocument Type of Prismic documents returned.
754
- * @param tags A list of tags that must be included on a document.
755
- * @param params Parameters to filter, sort, and paginate the results.
872
+ * @example
756
873
  *
757
- * @returns A list of all documents with the tag.
874
+ * ```ts
875
+ * const response = await client.getAllByEveryTag(["food", "fruit"]);
876
+ * ```
877
+ *
878
+ * @typeParam TDocument - Type of Prismic documents returned.
879
+ * @param tags - A list of tags that must be included on a document.
880
+ * @param params - Parameters to filter, sort, and paginate the results.
881
+ *
882
+ * @returns A list of all documents with the tags.
883
+ */
884
+ async getAllByEveryTag<TDocument extends prismicT.PrismicDocument>(
885
+ tags: string[],
886
+ params?: Partial<Omit<BuildQueryURLArgs, "page">>,
887
+ ): Promise<TDocument[]> {
888
+ return await this.getAll<TDocument>(
889
+ appendPredicates(params, everyTagPredicate(tags)),
890
+ );
891
+ }
892
+
893
+ /**
894
+ * Queries documents from the Prismic repository with specific tags. A
895
+ * document must be tagged with at least one of the queried tags to be included.
758
896
  *
759
897
  * @example
898
+ *
760
899
  * ```ts
761
- * const response = await client.getAllByTag('food')
900
+ * const response = await client.getByEveryTag(["food", "fruit"]);
762
901
  * ```
902
+ *
903
+ * @typeParam TDocument - Type of Prismic documents returned.
904
+ * @param tags - A list of tags that must be included on a document.
905
+ * @param params - Parameters to filter, sort, and paginate the results.
906
+ *
907
+ * @returns A paginated response containing documents with at least one of the tags.
763
908
  */
764
- async getAllByTags<TDocument extends prismicT.PrismicDocument>(
909
+ async getBySomeTags<TDocument extends prismicT.PrismicDocument>(
765
910
  tags: string[],
766
- params?: Partial<Omit<BuildQueryURLArgs, "page">>
911
+ params?: Partial<BuildQueryURLArgs>,
912
+ ): Promise<prismicT.Query<TDocument>> {
913
+ return await this.get<TDocument>(
914
+ appendPredicates(params, someTagsPredicate(tags)),
915
+ );
916
+ }
917
+
918
+ /**
919
+ * Queries documents from the Prismic repository with specific tags. A
920
+ * document must be tagged with at least one of the queried tags to be included.
921
+ *
922
+ * This method may make multiple network requests to query all matching content.
923
+ *
924
+ * @example
925
+ *
926
+ * ```ts
927
+ * const response = await client.getAllByEveryTag(["food", "fruit"]);
928
+ * ```
929
+ *
930
+ * @typeParam TDocument - Type of Prismic documents returned.
931
+ * @param tags - A list of tags that must be included on a document.
932
+ * @param params - Parameters to filter, sort, and paginate the results.
933
+ *
934
+ * @returns A list of all documents with at least one of the tags.
935
+ */
936
+ async getAllBySomeTags<TDocument extends prismicT.PrismicDocument>(
937
+ tags: string[],
938
+ params?: Partial<Omit<BuildQueryURLArgs, "page">>,
767
939
  ): Promise<TDocument[]> {
768
940
  return await this.getAll<TDocument>(
769
- appendPredicates(tagsPredicate(tags))(params)
941
+ appendPredicates(params, someTagsPredicate(tags)),
770
942
  );
771
943
  }
772
944
 
773
945
  /**
774
- * Returns metadata about the Prismic repository, such as its refs, releases, and custom types.
946
+ * Returns metadata about the Prismic repository, such as its refs, releases,
947
+ * and custom types.
775
948
  *
776
949
  * @returns Repository metadata.
777
950
  */
778
- async getRepository(): Promise<Repository> {
779
- return await this.fetch<Repository>(this.endpoint);
951
+ async getRepository(): Promise<prismicT.Repository> {
952
+ return await this.fetch<prismicT.Repository>(this.endpoint);
780
953
  }
781
954
 
782
955
  /**
783
956
  * Returns a list of all refs for the Prismic repository.
784
957
  *
785
- * Refs are used to identify which version of the repository's content should be queried. All repositories will have at least one ref pointing to the latest published content called the "master ref".
958
+ * Refs are used to identify which version of the repository's content should
959
+ * be queried. All repositories will have at least one ref pointing to the
960
+ * latest published content called the "master ref".
786
961
  *
787
962
  * @returns A list of all refs for the Prismic repository.
788
963
  */
789
- async getRefs(): Promise<Ref[]> {
790
- const res = await this.getRepository();
964
+ async getRefs(): Promise<prismicT.Ref[]> {
965
+ const repository = await this.getRepository();
791
966
 
792
- return res.refs;
967
+ return repository.refs;
793
968
  }
794
969
 
795
970
  /**
796
971
  * Returns a ref for the Prismic repository with a matching ID.
797
972
  *
798
- * @param id ID of the ref.
973
+ * @param id - ID of the ref.
799
974
  *
800
975
  * @returns The ref with a matching ID, if it exists.
801
976
  */
802
- async getRefById(id: string): Promise<Ref> {
977
+ async getRefByID(id: string): Promise<prismicT.Ref> {
803
978
  const refs = await this.getRefs();
804
979
 
805
- return findRef(refs, ref => ref.id === id);
980
+ return findRefByID(refs, id);
806
981
  }
807
982
 
808
983
  /**
809
984
  * Returns a ref for the Prismic repository with a matching label.
810
985
  *
811
- * @param label Label of the ref.
986
+ * @param label - Label of the ref.
812
987
  *
813
988
  * @returns The ref with a matching label, if it exists.
814
989
  */
815
- async getRefByLabel(label: string): Promise<Ref> {
990
+ async getRefByLabel(label: string): Promise<prismicT.Ref> {
816
991
  const refs = await this.getRefs();
817
992
 
818
- return findRef(refs, ref => ref.label === label);
993
+ return findRefByLabel(refs, label);
819
994
  }
820
995
 
821
996
  /**
822
- * Returns the master ref for the Prismic repository. The master ref points to the repository's latest published content.
997
+ * Returns the master ref for the Prismic repository. The master ref points to
998
+ * the repository's latest published content.
823
999
  *
824
1000
  * @returns The repository's master ref.
825
1001
  */
826
- async getMasterRef(): Promise<Ref> {
1002
+ async getMasterRef(): Promise<prismicT.Ref> {
827
1003
  const refs = await this.getRefs();
828
1004
 
829
- return findRef(refs, ref => ref.isMasterRef);
1005
+ return findMasterRef(refs);
830
1006
  }
831
1007
 
832
1008
  /**
833
- * Returns a list of all Releases for the Prismic repository. Releases are used to group content changes before publishing.
1009
+ * Returns a list of all Releases for the Prismic repository. Releases are
1010
+ * used to group content changes before publishing.
834
1011
  *
835
1012
  * @returns A list of all Releases for the Prismic repository.
836
1013
  */
837
- async getReleases(): Promise<Ref[]> {
1014
+ async getReleases(): Promise<prismicT.Ref[]> {
838
1015
  const refs = await this.getRefs();
839
1016
 
840
- return refs.filter(ref => !ref.isMasterRef);
1017
+ return refs.filter((ref) => !ref.isMasterRef);
841
1018
  }
842
1019
 
843
1020
  /**
844
1021
  * Returns a Release for the Prismic repository with a matching ID.
845
1022
  *
846
- * @param id ID of the Release.
1023
+ * @param id - ID of the Release.
847
1024
  *
848
1025
  * @returns The Release with a matching ID, if it exists.
849
1026
  */
850
- async getReleaseByID(id: string): Promise<Ref> {
1027
+ async getReleaseByID(id: string): Promise<prismicT.Ref> {
851
1028
  const releases = await this.getReleases();
852
1029
 
853
- return findRef(releases, ref => ref.id === id);
1030
+ return findRefByID(releases, id);
854
1031
  }
855
1032
 
856
1033
  /**
857
1034
  * Returns a Release for the Prismic repository with a matching label.
858
1035
  *
859
- * @param label Label of the ref.
1036
+ * @param label - Label of the ref.
860
1037
  *
861
1038
  * @returns The ref with a matching label, if it exists.
862
1039
  */
863
- async getReleaseByLabel(label: string): Promise<Ref> {
1040
+ async getReleaseByLabel(label: string): Promise<prismicT.Ref> {
864
1041
  const releases = await this.getReleases();
865
1042
 
866
- return findRef(releases, ref => ref.label === label);
1043
+ return findRefByLabel(releases, label);
867
1044
  }
868
1045
 
869
1046
  /**
@@ -877,78 +1054,81 @@ export class Client {
877
1054
 
878
1055
  return await this.fetch<string[]>(tagsForm.action);
879
1056
  } catch {
880
- const res = await this.getRepository();
1057
+ const repository = await this.getRepository();
881
1058
 
882
- return res.tags;
1059
+ return repository.tags;
883
1060
  }
884
1061
  }
885
1062
 
886
1063
  /**
887
1064
  * Builds a URL used to query content from the Prismic repository.
888
1065
  *
889
- * @param params Parameters to filter, sort, and paginate the results.
1066
+ * @param params - Parameters to filter, sort, and paginate the results.
890
1067
  *
891
1068
  * @returns A URL string that can be requested to query content.
892
1069
  */
893
1070
  async buildQueryURL(
894
- params: Partial<BuildQueryURLArgs> = {}
1071
+ params: Partial<BuildQueryURLArgs> = {},
895
1072
  ): Promise<string> {
896
- const {
897
- ref = await this.getResolvedRefString(),
898
- accessToken: _accessToken,
899
- ...actualParams
900
- } = params;
1073
+ const ref = params.ref || (await this.getResolvedRefString());
1074
+ const integrationFieldsRef =
1075
+ params.integrationFieldsRef ||
1076
+ (await this.getCachedRepository()).integrationFieldsRef ||
1077
+ undefined;
901
1078
 
902
1079
  return buildQueryURL(this.endpoint, {
903
1080
  ...this.defaultParams,
904
- ...actualParams,
905
- ref
1081
+ ...params,
1082
+ ref,
1083
+ integrationFieldsRef,
1084
+ routes: params.routes || this.routes,
1085
+ accessToken: undefined,
906
1086
  });
907
1087
  }
908
1088
 
909
1089
  /**
910
- * Determines the URL for a previewed document during an active preview session. The result of this method should be used to redirect the user to the document's URL.
911
- *
912
- * @param args Arguments to configure the URL resolving.
913
- *
914
- * @returns The URL for the previewed document during an active preview session. The user should be redirected to this URL.
1090
+ * Determines the URL for a previewed document during an active preview
1091
+ * session. The result of this method should be used to redirect the user to
1092
+ * the document's URL.
915
1093
  *
916
1094
  * @example
1095
+ *
917
1096
  * ```ts
918
- * const url = client.resolvePreviewURL({
919
- * linkResolver: (document) => `/${document.uid}`
920
- * defaultURL: '/'
921
- * })
1097
+ * const url = client.resolvePreviewURL({
1098
+ * linkResolver: (document) => `/${document.uid}`
1099
+ * defaultURL: '/'
1100
+ * })
922
1101
  * ```
1102
+ *
1103
+ * @param args - Arguments to configure the URL resolving.
1104
+ *
1105
+ * @returns The URL for the previewed document during an active preview
1106
+ * session. The user should be redirected to this URL.
923
1107
  */
924
1108
  async resolvePreviewURL(args: ResolvePreviewArgs): Promise<string> {
925
- let documentId = args.documentId;
1109
+ let documentID = args.documentID;
926
1110
  let previewToken = args.previewToken;
927
1111
 
928
1112
  if (typeof globalThis.location !== "undefined") {
929
1113
  const searchParams = new URLSearchParams(globalThis.location.search);
930
- documentId = documentId || searchParams.get("documentId") || undefined;
1114
+
1115
+ documentID = documentID || searchParams.get("documentId") || undefined;
931
1116
  previewToken = previewToken || searchParams.get("token") || undefined;
932
- } else if (this.refMode.httpRequest?.query) {
933
- if (typeof this.refMode.httpRequest.query.documentId === "string") {
934
- documentId = documentId || this.refMode.httpRequest.query.documentId;
935
- }
936
- if (typeof this.refMode.httpRequest.query.token === "string") {
937
- previewToken = previewToken || this.refMode.httpRequest.query.token;
938
- }
1117
+ } else if (this.refState.httpRequest?.query) {
1118
+ documentID =
1119
+ documentID || (this.refState.httpRequest.query.documentId as string);
1120
+ previewToken =
1121
+ previewToken || (this.refState.httpRequest.query.token as string);
939
1122
  }
940
1123
 
941
- if (documentId != null) {
942
- const document = await this.getByID(documentId, {
943
- ref: previewToken
1124
+ if (documentID != null) {
1125
+ const document = await this.getByID(documentID, {
1126
+ ref: previewToken,
944
1127
  });
945
1128
 
946
1129
  // We know we have a valid field to resolve since we are using prismicH.documentToLinkField
947
1130
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
948
- return prismicH.asLink(
949
- prismicH.documentToLinkField(document),
950
- args.linkResolver
951
- )!;
1131
+ return prismicH.asLink(document, args.linkResolver)!;
952
1132
  } else {
953
1133
  return args.defaultURL;
954
1134
  }
@@ -960,78 +1140,83 @@ export class Client {
960
1140
  * If the `ref` parameter is provided during a query, it takes priority for that query.
961
1141
  *
962
1142
  * @example
1143
+ *
963
1144
  * ```ts
964
- * await client.queryLatestContent()
965
- * const document = await client.getByID('WW4bKScAAMAqmluX')
1145
+ * await client.queryLatestContent();
1146
+ * const document = await client.getByID("WW4bKScAAMAqmluX");
966
1147
  * ```
967
1148
  */
968
1149
  queryLatestContent(): void {
969
- this.refMode = {
970
- ...this.refMode,
971
- type: RefStateType.Master
972
- };
1150
+ this.refState.mode = RefStateMode.Master;
973
1151
  }
974
1152
 
975
1153
  /**
976
- * Configures the client to query content from a specific Release identified by its ID for all future queries.
1154
+ * Configures the client to query content from a specific Release identified
1155
+ * by its ID for all future queries.
977
1156
  *
978
1157
  * If the `ref` parameter is provided during a query, it takes priority for that query.
979
1158
  *
980
- * @param id The ID of the Release.
981
- *
982
1159
  * @example
1160
+ *
983
1161
  * ```ts
984
- * await client.queryContentFromReleaseByID('YLB7OBAAACMA7Cpa')
985
- * const document = await client.getByID('WW4bKScAAMAqmluX')
1162
+ * await client.queryContentFromReleaseByID("YLB7OBAAACMA7Cpa");
1163
+ * const document = await client.getByID("WW4bKScAAMAqmluX");
986
1164
  * ```
1165
+ *
1166
+ * @param id - The ID of the Release.
987
1167
  */
988
- queryContentFromReleaseByID(releaseId: string): void {
989
- this.refMode = {
990
- ...this.refMode,
991
- type: RefStateType.ReleaseByID,
992
- payload: { releaseId }
1168
+ queryContentFromReleaseByID(releaseID: string): void {
1169
+ this.refState = {
1170
+ ...this.refState,
1171
+ mode: RefStateMode.ReleaseID,
1172
+ releaseID,
993
1173
  };
994
1174
  }
995
1175
 
996
1176
  /**
997
- * Configures the client to query content from a specific Release identified by its label for all future queries.
1177
+ * Configures the client to query content from a specific Release identified
1178
+ * by its label for all future queries.
998
1179
  *
999
1180
  * If the `ref` parameter is provided during a query, it takes priority for that query.
1000
1181
  *
1001
- * @param label The label of the Release.
1002
- *
1003
1182
  * @example
1183
+ *
1004
1184
  * ```ts
1005
- * await client.queryContentFromReleaseByLabel('My Release')
1006
- * const document = await client.getByID('WW4bKScAAMAqmluX')
1185
+ * await client.queryContentFromReleaseByLabel("My Release");
1186
+ * const document = await client.getByID("WW4bKScAAMAqmluX");
1007
1187
  * ```
1188
+ *
1189
+ * @param label - The label of the Release.
1008
1190
  */
1009
1191
  queryContentFromReleaseByLabel(releaseLabel: string): void {
1010
- this.refMode = {
1011
- ...this.refMode,
1012
- type: RefStateType.ReleaseByLabel,
1013
- payload: { releaseLabel }
1192
+ this.refState = {
1193
+ ...this.refState,
1194
+ mode: RefStateMode.ReleaseLabel,
1195
+ releaseLabel,
1014
1196
  };
1015
1197
  }
1016
1198
 
1017
1199
  /**
1018
- * Configures the client to query content from a specific ref. The ref can be provided as a string or a function.
1019
- *
1020
- * If a function is provided, the ref is fetched lazily before each query. The function may also be asynchronous.
1200
+ * Configures the client to query content from a specific ref. The ref can be
1201
+ * provided as a string or a function.
1021
1202
  *
1022
- * @param ref The ref or a function that returns the ref from which to query content.
1203
+ * If a function is provided, the ref is fetched lazily before each query. The
1204
+ * function may also be asynchronous.
1023
1205
  *
1024
1206
  * @example
1207
+ *
1025
1208
  * ```ts
1026
- * await client.queryContentFromRef('my-ref')
1027
- * const document = await client.getByID('WW4bKScAAMAqmluX')
1209
+ * await client.queryContentFromRef("my-ref");
1210
+ * const document = await client.getByID("WW4bKScAAMAqmluX");
1028
1211
  * ```
1212
+ *
1213
+ * @param ref - The ref or a function that returns the ref from which to query content.
1029
1214
  */
1030
- queryContentFromRef(ref: RefStringOrFn): void {
1031
- this.refMode = {
1032
- ...this.refMode,
1033
- type: RefStateType.Manual,
1034
- payload: { refStringOrFn: ref }
1215
+ queryContentFromRef(ref: RefStringOrThunk): void {
1216
+ this.refState = {
1217
+ ...this.refState,
1218
+ mode: RefStateMode.Manual,
1219
+ ref,
1035
1220
  };
1036
1221
  }
1037
1222
 
@@ -1040,157 +1225,120 @@ export class Client {
1040
1225
  *
1041
1226
  * @returns Cached repository metadata.
1042
1227
  */
1043
- private async getCachedRepository(): Promise<Repository> {
1044
- const cacheKey = this.endpoint;
1045
-
1046
- const cachedRepository = this.internalCache.get<Repository>(cacheKey);
1047
-
1048
- if (cachedRepository) {
1049
- return cachedRepository;
1228
+ private async getCachedRepository(): Promise<prismicT.Repository> {
1229
+ if (
1230
+ !this.cachedRepository ||
1231
+ Date.now() >= this.cachedRepositoryExpiration
1232
+ ) {
1233
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1234
+ this.cachedRepository = await this.getRepository();
1050
1235
  }
1051
1236
 
1052
- const repository = await this.getRepository();
1053
-
1054
- this.internalCache.set(cacheKey, repository, REPOSITORY_CACHE_TTL);
1055
-
1056
- return repository;
1237
+ return this.cachedRepository;
1057
1238
  }
1058
1239
 
1059
1240
  /**
1060
- * Returns a cached Prismic repository form. Forms are used to determine API endpoints for types of repository data.
1061
- *
1062
- * @throws If a matching form cannot be found.
1241
+ * Returns a cached Prismic repository form. Forms are used to determine API
1242
+ * endpoints for types of repository data.
1063
1243
  *
1064
- * @param name Name of the form.
1244
+ * @param name - Name of the form.
1065
1245
  *
1066
1246
  * @returns The repository form.
1247
+ * @throws If a matching form cannot be found.
1067
1248
  */
1068
- private async getCachedRepositoryForm(name: string): Promise<Form> {
1249
+ private async getCachedRepositoryForm(name: string): Promise<prismicT.Form> {
1069
1250
  const cachedRepository = await this.getCachedRepository();
1070
1251
  const form = cachedRepository.forms[name];
1071
1252
 
1072
1253
  if (!form) {
1073
- throw new Error(`Form with name "${name}" could not be found`);
1254
+ throw new PrismicError(
1255
+ `Form with name "${name}" could not be found`,
1256
+ undefined,
1257
+ undefined,
1258
+ );
1074
1259
  }
1075
1260
 
1076
1261
  return form;
1077
1262
  }
1078
1263
 
1079
1264
  /**
1080
- * Returns the preview ref for the client, if one exists.
1081
- *
1082
- * If this method is used in the browser, the browser's cookies will be read. If this method is used on the server, the cookies from the saved HTTP Request will be read, if an HTTP Request was given.
1083
- *
1084
- * @returns The preview ref as a string, if one exists.
1085
- */
1086
- private getPreviewRefString(): string | undefined {
1087
- if (globalThis.document?.cookie) {
1088
- return getCookie(cookie.preview, globalThis.document.cookie);
1089
- } else if (this.refMode.httpRequest?.headers?.cookie) {
1090
- return getCookie(cookie.preview, this.refMode.httpRequest.headers.cookie);
1091
- }
1092
- }
1093
-
1094
- /**
1095
- * Returns the ref needed to query based on the client's current state. This method may make a network request to fetch a ref or resolve the users's ref thunk.
1265
+ * Returns the ref needed to query based on the client's current state. This
1266
+ * method may make a network request to fetch a ref or resolve the user's ref thunk.
1096
1267
  *
1097
1268
  * If auto previews are enabled, the preview ref takes priority if available.
1098
1269
  *
1099
1270
  * The following strategies are used depending on the client's state:
1100
1271
  *
1101
- * - If the user called `queryLatestContent`: Use the repository's master ref. The ref is cached for 5 seconds. After 5 seconds, a new master ref is fetched.
1102
- *
1103
- * - If the user called `queryContentFromReleaseByID`: Use the release's ref. The ref is cached for 5 seconds. After 5 seconds, a new ref for the release is fetched.
1104
- *
1105
- * - If the user called `queryContentFromReleaseByLabel`: Use the release's ref. The ref is cached for 5 seconds. After 5 seconds, a new ref for the release is fetched.
1106
- *
1107
- * - If the user called `queryContentFromRef`: Use the provided ref. Fall back to the master ref if the ref is not a string.
1272
+ * - If the user called `queryLatestContent`: Use the repository's master ref.
1273
+ * The ref is cached for 5 seconds. After 5 seconds, a new master ref is fetched.
1274
+ * - If the user called `queryContentFromReleaseByID`: Use the release's ref.
1275
+ * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1276
+ * release is fetched.
1277
+ * - If the user called `queryContentFromReleaseByLabel`: Use the release's ref.
1278
+ * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1279
+ * release is fetched.
1280
+ * - If the user called `queryContentFromRef`: Use the provided ref. Fall back
1281
+ * to the master ref if the ref is not a string.
1108
1282
  *
1109
1283
  * @returns The ref to use during a query.
1110
1284
  */
1111
1285
  private async getResolvedRefString(): Promise<string> {
1112
- if (this.refMode.autoPreviewsEnabled) {
1113
- const previewRef = this.getPreviewRefString();
1286
+ if (this.refState.autoPreviewsEnabled) {
1287
+ let previewRef: string | undefined = undefined;
1288
+
1289
+ if (globalThis.document?.cookie) {
1290
+ previewRef = getCookie(cookie.preview, globalThis.document.cookie);
1291
+ } else if (this.refState.httpRequest?.headers?.cookie) {
1292
+ previewRef = getCookie(
1293
+ cookie.preview,
1294
+ this.refState.httpRequest.headers.cookie,
1295
+ );
1296
+ }
1114
1297
 
1115
1298
  if (previewRef) {
1116
1299
  return previewRef;
1117
1300
  }
1118
1301
  }
1119
1302
 
1120
- switch (this.refMode.type) {
1121
- case RefStateType.ReleaseByID: {
1122
- const releaseId = this.refMode.payload.releaseId;
1123
- const repository = await this.getCachedRepository();
1124
- const ref = findRef(repository.refs, ref => ref.id === releaseId);
1125
-
1126
- return ref.ref;
1127
- }
1128
-
1129
- case RefStateType.ReleaseByLabel: {
1130
- const releaseLabel = this.refMode.payload.releaseLabel;
1131
- const repository = await this.getCachedRepository();
1132
- const ref = findRef(repository.refs, ref => ref.label === releaseLabel);
1133
-
1134
- return ref.ref;
1135
- }
1136
-
1137
- case RefStateType.Manual: {
1138
- const thisRefStringOrFn = this.refMode.payload.refStringOrFn;
1139
-
1140
- if (typeof thisRefStringOrFn === "function") {
1141
- const res = await thisRefStringOrFn();
1142
-
1143
- if (typeof res === "string") {
1144
- return res;
1145
- }
1146
- } else if (thisRefStringOrFn) {
1147
- return thisRefStringOrFn;
1148
- }
1149
- }
1150
-
1151
- case RefStateType.Master:
1152
- default: {
1153
- const repository = await this.getCachedRepository();
1154
- const ref = findRef(repository.refs, ref => ref.isMasterRef);
1303
+ const cachedRepository = await this.getCachedRepository();
1155
1304
 
1156
- return ref.ref;
1305
+ const refModeType = this.refState.mode;
1306
+ if (refModeType === RefStateMode.ReleaseID) {
1307
+ return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
1308
+ } else if (refModeType === RefStateMode.ReleaseLabel) {
1309
+ return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel)
1310
+ .ref;
1311
+ } else if (refModeType === RefStateMode.Manual) {
1312
+ const res = await castThunk(this.refState.ref)();
1313
+
1314
+ if (typeof res === "string") {
1315
+ return res;
1157
1316
  }
1158
1317
  }
1159
- }
1160
-
1161
- /**
1162
- * Returns the network request options required by the Prismic repository.
1163
- *
1164
- * It currently only includes an Authorization header if an access token is provided.
1165
- *
1166
- * @param params Parameters for the query, including an access token.
1167
- *
1168
- * @returns Request options that can be used to make a network request to query the repository.
1169
- */
1170
- private buildRequestOptions(
1171
- params?: Partial<BuildQueryURLArgs>
1172
- ): RequestInitLike {
1173
- const accessToken = params?.accessToken || this.accessToken;
1174
1318
 
1175
- return accessToken
1176
- ? { headers: { Authorization: `Token ${accessToken}` } }
1177
- : {};
1319
+ return findMasterRef(cachedRepository.refs).ref;
1178
1320
  }
1179
1321
 
1180
1322
  /**
1181
- * Performs a network request using the configured `fetch` function. It assumes all successful responses will have a JSON content type. It also normalizes unsuccessful network requests.
1323
+ * Performs a network request using the configured `fetch` function. It
1324
+ * assumes all successful responses will have a JSON content type. It also
1325
+ * normalizes unsuccessful network requests.
1182
1326
  *
1183
- * @typeParam T The JSON response.
1184
- * @param url URL to the resource to fetch.
1185
- * @param params Prismic REST API parameters for the network request.
1327
+ * @typeParam T - The JSON response.
1328
+ * @param url - URL to the resource to fetch.
1329
+ * @param params - Prismic REST API parameters for the network request.
1186
1330
  *
1187
1331
  * @returns The JSON response from the network request.
1188
1332
  */
1189
1333
  private async fetch<T = unknown>(
1190
1334
  url: string,
1191
- params?: Partial<BuildQueryURLArgs>
1335
+ params?: Partial<BuildQueryURLArgs>,
1192
1336
  ): Promise<T> {
1193
- const options = this.buildRequestOptions(params);
1337
+ const accessToken = (params && params.accessToken) || this.accessToken;
1338
+ const options = accessToken
1339
+ ? { headers: { Authorization: `Token ${accessToken}` } }
1340
+ : {};
1341
+
1194
1342
  const res = await this.fetchFn(url, options);
1195
1343
 
1196
1344
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1200,7 +1348,7 @@ export class Client {
1200
1348
  // Content Type. If not, this will throw, signaling an invalid response.
1201
1349
  json = await res.json();
1202
1350
  } catch {
1203
- throw new PrismicError(undefined, { url });
1351
+ throw new PrismicError(undefined, url, undefined);
1204
1352
  }
1205
1353
 
1206
1354
  switch (res.status) {
@@ -1213,29 +1361,25 @@ export class Client {
1213
1361
  // - Invalid predicate syntax
1214
1362
  // - Ref not provided (ignored)
1215
1363
  case 400: {
1216
- if (isParsingErrorAPIResponse(json)) {
1217
- throw new ParsingError(json.message, {
1218
- url,
1219
- response: json
1220
- });
1221
- }
1222
-
1223
- break;
1364
+ throw new ParsingError(json.message, url, json);
1224
1365
  }
1225
1366
 
1367
+ // Unauthorized
1368
+ // - Missing access token for repository endpoint
1369
+ // - Incorrect access token for repository endpoint
1370
+ case 401:
1226
1371
  // Forbidden
1227
- // - Missing access token
1228
- // - Incorrect access token
1372
+ // - Missing access token for query endpoint
1373
+ // - Incorrect access token for query endpoint
1229
1374
  case 403: {
1230
- if (isForbiddenErrorAPIResponse(json)) {
1231
- throw new ForbiddenError(json.error, {
1232
- url,
1233
- response: json
1234
- });
1235
- }
1375
+ throw new ForbiddenError(
1376
+ "error" in json ? json.error : json.message,
1377
+ url,
1378
+ json,
1379
+ );
1236
1380
  }
1237
1381
  }
1238
1382
 
1239
- throw new PrismicError(undefined, { url, response: json });
1383
+ throw new PrismicError(undefined, url, json);
1240
1384
  }
1241
1385
  }