@prismicio/client 6.0.0-alpha.8 → 6.0.0-beta.2

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