@prismicio/client 6.0.0-beta.0 → 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
@@ -3,78 +3,18 @@ import * as prismicH from "@prismicio/helpers";
3
3
 
4
4
  import { appendPredicates } from "./lib/appendPredicates";
5
5
  import { castThunk } from "./lib/castThunk";
6
+ import { findMasterRef } from "./lib/findMasterRef";
7
+ import { findRefByID } from "./lib/findRefByID";
8
+ import { findRefByLabel } from "./lib/findRefByLabel";
6
9
  import { getCookie } from "./lib/getCookie";
7
10
 
8
- import {
9
- FetchLike,
10
- HttpRequestLike,
11
- // TODO: Uncomment when the Authorization header can be used
12
- // @see Related issue - {@link https://github.com/prismicio/issue-tracker-wroom/issues/351}
13
- // RequestInitLike
14
- } from "./types";
11
+ import { FetchLike, HttpRequestLike } from "./types";
15
12
  import { buildQueryURL, BuildQueryURLArgs } from "./buildQueryURL";
16
- import { ForbiddenError, isForbiddenErrorAPIResponse } from "./ForbiddenError";
17
- import { ParsingError, isParsingErrorAPIResponse } from "./ParsingError";
13
+ import { ForbiddenError } from "./ForbiddenError";
14
+ import { ParsingError } from "./ParsingError";
18
15
  import { PrismicError } from "./PrismicError";
16
+ import { predicate } from "./predicate";
19
17
  import * as cookie from "./cookie";
20
- import * as predicate from "./predicate";
21
-
22
- /**
23
- * A container for items in a SimpleTTLCache.
24
- */
25
- type SimpleTTLCacheValueContainer<T = unknown> = {
26
- expiresAt: number;
27
- value: T;
28
- };
29
-
30
- /**
31
- * A simple time-to-live cache where items are only valid for a given number of
32
- * 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).
41
- * After the TTL has ellapsed, the value is considered stale and will not be
42
- * 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`
50
- * will be returned.
51
- *
52
- * @param key - Key for the item.
53
- *
54
- * @returns The value for the key, if a value exists.
55
- */
56
- get<T>(key: string): T | undefined {
57
- const cacheValue = cache.get(key);
58
-
59
- if (cacheValue) {
60
- if (new Date().getTime() < cacheValue.expiresAt) {
61
- return cacheValue.value as T;
62
- }
63
- }
64
- },
65
-
66
- /**
67
- * Set a value in the cache for a given key and TTL.
68
- *
69
- * @param key - Key to identify the item.
70
- * @param value - Value for the key.
71
- * @param ttl - Number of milliseconds to consider the value fresh.
72
- */
73
- set<T>(key: string, value: T, ttl: number): void {
74
- cache.set(key, { expiresAt: new Date().getTime() + ttl, value });
75
- },
76
- };
77
- };
78
18
 
79
19
  /**
80
20
  * The largest page size allowed by the Prismic REST API V2. This value is used
@@ -91,37 +31,28 @@ const MAX_PAGE_SIZE = 100;
91
31
  export const REPOSITORY_CACHE_TTL = 5000;
92
32
 
93
33
  /**
94
- * A ref or a function that returns a ref. If a static ref is known, one can be
95
- * given. If the ref must be fetched on-demand, a function can be provided. This
96
- * function can optionally be asynchronous.
97
- */
98
- type RefStringOrThunk =
99
- | string
100
- | (() => string | undefined | Promise<string | undefined>);
101
-
102
- /**
103
- * State types for a client's ref strategy.
34
+ * Modes for client ref management.
104
35
  */
105
- const enum RefStateType {
36
+ enum RefStateMode {
106
37
  /**
107
38
  * Use the repository's master ref.
108
39
  */
109
- Master,
40
+ Master = "Master",
110
41
 
111
42
  /**
112
43
  * Use a given Release identified by its ID.
113
44
  */
114
- ReleaseByID,
45
+ ReleaseID = "ReleaseID",
115
46
 
116
47
  /**
117
48
  * Use a given Release identified by its label.
118
49
  */
119
- ReleaseByLabel,
50
+ ReleaseLabel = "ReleaseLabel",
120
51
 
121
52
  /**
122
53
  * Use a given ref.
123
54
  */
124
- Manual,
55
+ Manual = "Manual",
125
56
  }
126
57
 
127
58
  /**
@@ -140,37 +71,31 @@ type RefState = {
140
71
  httpRequest?: HttpRequestLike;
141
72
  } & (
142
73
  | {
143
- type: RefStateType.Master;
74
+ mode: RefStateMode.Master;
144
75
  }
145
76
  | {
146
- type: RefStateType.ReleaseByID;
147
- payload: {
148
- /**
149
- * The ID of the Release.
150
- */
151
- releaseID: string;
152
- };
77
+ mode: RefStateMode.ReleaseID;
78
+ releaseID: string;
153
79
  }
154
80
  | {
155
- type: RefStateType.ReleaseByLabel;
156
- payload: {
157
- /**
158
- * The label of the Release.
159
- */
160
- releaseLabel: string;
161
- };
81
+ mode: RefStateMode.ReleaseLabel;
82
+ releaseLabel: string;
162
83
  }
163
84
  | {
164
- type: RefStateType.Manual;
165
- payload: {
166
- /**
167
- * The user-provided ref or ref thunk.
168
- */
169
- refStringOrFn: RefStringOrThunk;
170
- };
85
+ mode: RefStateMode.Manual;
86
+ ref: RefStringOrThunk;
171
87
  }
172
88
  );
173
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
+
174
99
  /**
175
100
  * Configuration for clients that determine how content is queried.
176
101
  */
@@ -188,12 +113,6 @@ export type ClientConfig = {
188
113
  */
189
114
  ref?: RefStringOrThunk;
190
115
 
191
- /**
192
- * A string representing a version of the Prismic repository's Integration
193
- * Fields content.
194
- */
195
- integrationFieldsRef?: RefStringOrThunk;
196
-
197
116
  /**
198
117
  * A list of Route Resolver objects that define how a document's `url` field
199
118
  * is resolved.
@@ -268,38 +187,26 @@ const typePredicate = (documentType: string): string =>
268
187
  predicate.at("document.type", documentType);
269
188
 
270
189
  /**
271
- * 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.
272
192
  *
273
193
  * @param documentType - Document tags to filter queried content.
274
194
  *
275
195
  * @returns A predicate that can be used in a Prismic REST API V2 request.
276
196
  */
277
- const tagsPredicate = (tags: string | string[]): string =>
197
+ const everyTagPredicate = (tags: string | string[]): string =>
278
198
  predicate.at("document.tags", tags);
279
199
 
280
200
  /**
281
- * Returns the first ref from a list that passes a predicate (a function that
282
- * returns true).
201
+ * Creates a predicate to filter content by document tags. At least one matching
202
+ * tag is required on the document.
283
203
  *
284
- * @param refs - A list of refs to search.
285
- * @param predicate - A function that determines if a ref from the list matches
286
- * the criteria.
204
+ * @param documentType - Document tags to filter queried content.
287
205
  *
288
- * @returns The first matching ref.
289
- * @throws If a matching ref cannot be found.
206
+ * @returns A predicate that can be used in a Prismic REST API V2 request.
290
207
  */
291
- const findRef = (
292
- refs: prismicT.Ref[],
293
- predicate: (ref: prismicT.Ref) => boolean,
294
- ): prismicT.Ref => {
295
- const ref = refs.find((ref) => predicate(ref));
296
-
297
- if (!ref) {
298
- throw new Error("Ref could not be found.");
299
- }
300
-
301
- return ref;
302
- };
208
+ const someTagsPredicate = (tags: string | string[]): string =>
209
+ predicate.any("document.tags", tags);
303
210
 
304
211
  /**
305
212
  * Creates a Prismic client that can be used to query a repository.
@@ -337,13 +244,6 @@ export class Client {
337
244
  */
338
245
  accessToken?: string;
339
246
 
340
- /**
341
- * The client's Integration Fields ref for fetching the latest Integration Fields data.
342
- *
343
- * {@link https://prismic.io/docs/core-concepts/integration-fields}
344
- */
345
- integrationFieldsRef?: RefStringOrThunk;
346
-
347
247
  /**
348
248
  * A list of Route Resolver objects that define how a document's `url` field
349
249
  * is resolved.
@@ -371,12 +271,20 @@ export class Client {
371
271
  /**
372
272
  * The client's ref mode state. This determines which ref is used during queries.
373
273
  */
374
- 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;
375
283
 
376
284
  /**
377
- * Internal cache for low-level caching.
285
+ * Timestamp at which the cached repository data is considered stale.
378
286
  */
379
- private internalCache: SimpleTTLCache;
287
+ private cachedRepositoryExpiration = 0;
380
288
 
381
289
  /**
382
290
  * Creates a Prismic client that can be used to query a repository.
@@ -395,14 +303,8 @@ export class Client {
395
303
  constructor(endpoint: string, options: ClientConfig = {}) {
396
304
  this.endpoint = endpoint;
397
305
  this.accessToken = options.accessToken;
398
- this.integrationFieldsRef = options.integrationFieldsRef;
399
306
  this.routes = options.routes;
400
307
  this.defaultParams = options.defaultParams;
401
- this.internalCache = createSimpleTTLCache();
402
- this.refMode = {
403
- type: RefStateType.Master,
404
- autoPreviewsEnabled: true,
405
- };
406
308
 
407
309
  if (options.ref) {
408
310
  this.queryContentFromRef(options.ref);
@@ -413,8 +315,10 @@ export class Client {
413
315
  } else if (typeof globalThis.fetch === "function") {
414
316
  this.fetchFn = globalThis.fetch;
415
317
  } else {
416
- throw new Error(
318
+ throw new PrismicError(
417
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,
418
322
  );
419
323
  }
420
324
 
@@ -439,7 +343,7 @@ export class Client {
439
343
  * @see enableAutoPreviewsFromReq
440
344
  */
441
345
  enableAutoPreviews(): void {
442
- this.refMode.autoPreviewsEnabled = true;
346
+ this.refState.autoPreviewsEnabled = true;
443
347
  }
444
348
 
445
349
  /**
@@ -460,8 +364,8 @@ export class Client {
460
364
  * @param req - An HTTP server request object containing the request's cookies.
461
365
  */
462
366
  enableAutoPreviewsFromReq<R extends HttpRequestLike>(req: R): void {
463
- this.refMode.httpRequest = req;
464
- this.refMode.autoPreviewsEnabled = true;
367
+ this.refState.httpRequest = req;
368
+ this.refState.autoPreviewsEnabled = true;
465
369
  }
466
370
 
467
371
  /**
@@ -478,7 +382,7 @@ export class Client {
478
382
  * ```
479
383
  */
480
384
  disableAutoPreviews(): void {
481
- this.refMode.autoPreviewsEnabled = false;
385
+ this.refState.autoPreviewsEnabled = false;
482
386
  }
483
387
 
484
388
  /**
@@ -488,7 +392,9 @@ export class Client {
488
392
  * @example
489
393
  *
490
394
  * ```ts
491
- * const response = await client.get();
395
+ * const response = await client.query(
396
+ * prismic.predicate.at("document.type", "page"),
397
+ * );
492
398
  * ```
493
399
  *
494
400
  * @typeParam TDocument - Type of Prismic documents returned.
@@ -496,7 +402,14 @@ export class Client {
496
402
  *
497
403
  * @returns A paginated response containing the result of the query.
498
404
  */
499
- 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
+ }
500
413
 
501
414
  /**
502
415
  * Queries content from the Prismic repository.
@@ -517,10 +430,7 @@ export class Client {
517
430
  ): Promise<prismicT.Query<TDocument>> {
518
431
  const url = await this.buildQueryURL(params);
519
432
 
520
- // TODO: Uncomment when the Authorization header can be used
521
- // @see Related issue - {@link https://github.com/prismicio/issue-tracker-wroom/issues/351}
522
- // return await this.fetch<Query<TDocument>>(url, params);
523
- return await this.fetch<prismicT.Query<TDocument>>(url);
433
+ return await this.fetch<prismicT.Query<TDocument>>(url, params);
524
434
  }
525
435
 
526
436
  /**
@@ -540,14 +450,16 @@ export class Client {
540
450
  async getFirst<TDocument extends prismicT.PrismicDocument>(
541
451
  params?: Partial<BuildQueryURLArgs>,
542
452
  ): Promise<TDocument> {
543
- 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
+
544
456
  const firstResult = result.results[0];
545
457
 
546
458
  if (firstResult) {
547
459
  return firstResult;
548
460
  }
549
461
 
550
- throw new Error("No documents were returned");
462
+ throw new PrismicError("No documents were returned", url, undefined);
551
463
  }
552
464
 
553
465
  /**
@@ -570,7 +482,10 @@ export class Client {
570
482
  params: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams = {},
571
483
  ): Promise<TDocument[]> {
572
484
  const { limit = Infinity, ...actualParams } = params;
573
- const resolvedParams = { pageSize: MAX_PAGE_SIZE, ...actualParams };
485
+ const resolvedParams = {
486
+ ...actualParams,
487
+ pageSize: actualParams.pageSize || MAX_PAGE_SIZE,
488
+ };
574
489
 
575
490
  const result = await this.get<TDocument>(resolvedParams);
576
491
 
@@ -611,7 +526,7 @@ export class Client {
611
526
  params?: Partial<BuildQueryURLArgs>,
612
527
  ): Promise<TDocument> {
613
528
  return await this.getFirst<TDocument>(
614
- appendPredicates(predicate.at("document.id", id))(params),
529
+ appendPredicates(params, predicate.at("document.id", id)),
615
530
  );
616
531
  }
617
532
 
@@ -643,7 +558,7 @@ export class Client {
643
558
  params?: Partial<BuildQueryURLArgs>,
644
559
  ): Promise<prismicT.Query<TDocument>> {
645
560
  return await this.get<TDocument>(
646
- appendPredicates(predicate.in("document.id", ids))(params),
561
+ appendPredicates(params, predicate.in("document.id", ids)),
647
562
  );
648
563
  }
649
564
 
@@ -676,7 +591,7 @@ export class Client {
676
591
  params?: Partial<BuildQueryURLArgs>,
677
592
  ): Promise<TDocument[]> {
678
593
  return await this.getAll<TDocument>(
679
- appendPredicates(predicate.in("document.id", ids))(params),
594
+ appendPredicates(params, predicate.in("document.id", ids)),
680
595
  );
681
596
  }
682
597
 
@@ -707,10 +622,10 @@ export class Client {
707
622
  params?: Partial<BuildQueryURLArgs>,
708
623
  ): Promise<TDocument> {
709
624
  return await this.getFirst<TDocument>(
710
- appendPredicates(
625
+ appendPredicates(params, [
711
626
  typePredicate(documentType),
712
627
  predicate.at(`my.${documentType}.uid`, uid),
713
- )(params),
628
+ ]),
714
629
  );
715
630
  }
716
631
 
@@ -744,10 +659,10 @@ export class Client {
744
659
  params?: Partial<BuildQueryURLArgs>,
745
660
  ): Promise<prismicT.Query<TDocument>> {
746
661
  return await this.get<TDocument>(
747
- appendPredicates(
662
+ appendPredicates(params, [
748
663
  typePredicate(documentType),
749
664
  predicate.in(`my.${documentType}.uid`, uids),
750
- )(params),
665
+ ]),
751
666
  );
752
667
  }
753
668
 
@@ -782,10 +697,10 @@ export class Client {
782
697
  params?: Partial<BuildQueryURLArgs>,
783
698
  ): Promise<TDocument[]> {
784
699
  return await this.getAll<TDocument>(
785
- appendPredicates(
700
+ appendPredicates(params, [
786
701
  typePredicate(documentType),
787
702
  predicate.in(`my.${documentType}.uid`, uids),
788
- )(params),
703
+ ]),
789
704
  );
790
705
  }
791
706
 
@@ -814,7 +729,7 @@ export class Client {
814
729
  params?: Partial<BuildQueryURLArgs>,
815
730
  ): Promise<TDocument> {
816
731
  return await this.getFirst<TDocument>(
817
- appendPredicates(typePredicate(documentType))(params),
732
+ appendPredicates(params, typePredicate(documentType)),
818
733
  );
819
734
  }
820
735
 
@@ -841,7 +756,7 @@ export class Client {
841
756
  params?: Partial<BuildQueryURLArgs>,
842
757
  ): Promise<prismicT.Query<TDocument>> {
843
758
  return await this.get<TDocument>(
844
- appendPredicates(typePredicate(documentType))(params),
759
+ appendPredicates(params, typePredicate(documentType)),
845
760
  );
846
761
  }
847
762
 
@@ -867,7 +782,7 @@ export class Client {
867
782
  params?: Partial<Omit<BuildQueryURLArgs, "page">>,
868
783
  ): Promise<TDocument[]> {
869
784
  return await this.getAll<TDocument>(
870
- appendPredicates(typePredicate(documentType))(params),
785
+ appendPredicates(params, typePredicate(documentType)),
871
786
  );
872
787
  }
873
788
 
@@ -893,7 +808,7 @@ export class Client {
893
808
  params?: Partial<BuildQueryURLArgs>,
894
809
  ): Promise<prismicT.Query<TDocument>> {
895
810
  return await this.get<TDocument>(
896
- appendPredicates(tagsPredicate(tag))(params),
811
+ appendPredicates(params, everyTagPredicate(tag)),
897
812
  );
898
813
  }
899
814
 
@@ -919,57 +834,111 @@ export class Client {
919
834
  params?: Partial<Omit<BuildQueryURLArgs, "page">>,
920
835
  ): Promise<TDocument[]> {
921
836
  return await this.getAll<TDocument>(
922
- appendPredicates(tagsPredicate(tag))(params),
837
+ appendPredicates(params, everyTagPredicate(tag)),
923
838
  );
924
839
  }
925
840
 
926
841
  /**
927
- * Queries documents from the Prismic repository with a specific 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.
928
844
  *
929
845
  * @example
930
846
  *
931
847
  * ```ts
932
- * const response = await client.getAllByTag("food");
848
+ * const response = await client.getByEveryTag(["food", "fruit"]);
933
849
  * ```
934
850
  *
935
851
  * @typeParam TDocument - Type of Prismic documents returned.
936
852
  * @param tags - A list of tags that must be included on a document.
937
853
  * @param params - Parameters to filter, sort, and paginate the results.
938
854
  *
939
- * @returns A paginated response containing documents with the tag.
855
+ * @returns A paginated response containing documents with the tags.
940
856
  */
941
- async getByTags<TDocument extends prismicT.PrismicDocument>(
857
+ async getByEveryTag<TDocument extends prismicT.PrismicDocument>(
942
858
  tags: string[],
943
859
  params?: Partial<BuildQueryURLArgs>,
944
860
  ): Promise<prismicT.Query<TDocument>> {
945
861
  return await this.get<TDocument>(
946
- appendPredicates(tagsPredicate(tags))(params),
862
+ appendPredicates(params, everyTagPredicate(tags)),
947
863
  );
948
864
  }
949
865
 
950
866
  /**
951
- * 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.
952
869
  *
953
870
  * This method may make multiple network requests to query all matching content.
954
871
  *
955
872
  * @example
956
873
  *
957
874
  * ```ts
958
- * const response = await client.getAllByTag("food");
875
+ * const response = await client.getAllByEveryTag(["food", "fruit"]);
959
876
  * ```
960
877
  *
961
878
  * @typeParam TDocument - Type of Prismic documents returned.
962
879
  * @param tags - A list of tags that must be included on a document.
963
880
  * @param params - Parameters to filter, sort, and paginate the results.
964
881
  *
965
- * @returns A list of all documents with the tag.
882
+ * @returns A list of all documents with the tags.
966
883
  */
967
- async getAllByTags<TDocument extends prismicT.PrismicDocument>(
884
+ async getAllByEveryTag<TDocument extends prismicT.PrismicDocument>(
968
885
  tags: string[],
969
886
  params?: Partial<Omit<BuildQueryURLArgs, "page">>,
970
887
  ): Promise<TDocument[]> {
971
888
  return await this.getAll<TDocument>(
972
- appendPredicates(tagsPredicate(tags))(params),
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.
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">>,
939
+ ): Promise<TDocument[]> {
940
+ return await this.getAll<TDocument>(
941
+ appendPredicates(params, someTagsPredicate(tags)),
973
942
  );
974
943
  }
975
944
 
@@ -980,17 +949,7 @@ export class Client {
980
949
  * @returns Repository metadata.
981
950
  */
982
951
  async getRepository(): Promise<prismicT.Repository> {
983
- // TODO: Uncomment when the Authorization header can be used
984
- // @see Related issue - {@link https://github.com/prismicio/issue-tracker-wroom/issues/351}
985
- // return await this.fetch<Repository>(this.endpoint);
986
-
987
- const url = new URL(this.endpoint);
988
-
989
- if (this.accessToken) {
990
- url.searchParams.set("access_token", this.accessToken);
991
- }
992
-
993
- return await this.fetch<prismicT.Repository>(url.toString());
952
+ return await this.fetch<prismicT.Repository>(this.endpoint);
994
953
  }
995
954
 
996
955
  /**
@@ -1003,9 +962,9 @@ export class Client {
1003
962
  * @returns A list of all refs for the Prismic repository.
1004
963
  */
1005
964
  async getRefs(): Promise<prismicT.Ref[]> {
1006
- const res = await this.getRepository();
965
+ const repository = await this.getRepository();
1007
966
 
1008
- return res.refs;
967
+ return repository.refs;
1009
968
  }
1010
969
 
1011
970
  /**
@@ -1018,7 +977,7 @@ export class Client {
1018
977
  async getRefByID(id: string): Promise<prismicT.Ref> {
1019
978
  const refs = await this.getRefs();
1020
979
 
1021
- return findRef(refs, (ref) => ref.id === id);
980
+ return findRefByID(refs, id);
1022
981
  }
1023
982
 
1024
983
  /**
@@ -1031,7 +990,7 @@ export class Client {
1031
990
  async getRefByLabel(label: string): Promise<prismicT.Ref> {
1032
991
  const refs = await this.getRefs();
1033
992
 
1034
- return findRef(refs, (ref) => ref.label === label);
993
+ return findRefByLabel(refs, label);
1035
994
  }
1036
995
 
1037
996
  /**
@@ -1043,7 +1002,7 @@ export class Client {
1043
1002
  async getMasterRef(): Promise<prismicT.Ref> {
1044
1003
  const refs = await this.getRefs();
1045
1004
 
1046
- return findRef(refs, (ref) => ref.isMasterRef);
1005
+ return findMasterRef(refs);
1047
1006
  }
1048
1007
 
1049
1008
  /**
@@ -1068,7 +1027,7 @@ export class Client {
1068
1027
  async getReleaseByID(id: string): Promise<prismicT.Ref> {
1069
1028
  const releases = await this.getReleases();
1070
1029
 
1071
- return findRef(releases, (ref) => ref.id === id);
1030
+ return findRefByID(releases, id);
1072
1031
  }
1073
1032
 
1074
1033
  /**
@@ -1081,7 +1040,7 @@ export class Client {
1081
1040
  async getReleaseByLabel(label: string): Promise<prismicT.Ref> {
1082
1041
  const releases = await this.getReleases();
1083
1042
 
1084
- return findRef(releases, (ref) => ref.label === label);
1043
+ return findRefByLabel(releases, label);
1085
1044
  }
1086
1045
 
1087
1046
  /**
@@ -1095,9 +1054,9 @@ export class Client {
1095
1054
 
1096
1055
  return await this.fetch<string[]>(tagsForm.action);
1097
1056
  } catch {
1098
- const res = await this.getRepository();
1057
+ const repository = await this.getRepository();
1099
1058
 
1100
- return res.tags;
1059
+ return repository.tags;
1101
1060
  }
1102
1061
  }
1103
1062
 
@@ -1111,28 +1070,19 @@ export class Client {
1111
1070
  async buildQueryURL(
1112
1071
  params: Partial<BuildQueryURLArgs> = {},
1113
1072
  ): Promise<string> {
1114
- // TODO: Uncomment when the Authorization header can be used
1115
- // @see Related issue - {@link https://github.com/prismicio/issue-tracker-wroom/issues/351}
1116
- // const {
1117
- // ref = await this.getResolvedRefString(),
1118
- // accessToken: _accessToken,
1119
- // ...actualParams
1120
- // } = params;
1121
- const {
1122
- ref = await this.getResolvedRefString(),
1123
- integrationFieldsRef = await this.getResolvedIntegrationFieldsRef(),
1124
- accessToken = this.accessToken,
1125
- routes = this.routes,
1126
- ...actualParams
1127
- } = params;
1073
+ const ref = params.ref || (await this.getResolvedRefString());
1074
+ const integrationFieldsRef =
1075
+ params.integrationFieldsRef ||
1076
+ (await this.getCachedRepository()).integrationFieldsRef ||
1077
+ undefined;
1128
1078
 
1129
1079
  return buildQueryURL(this.endpoint, {
1130
1080
  ...this.defaultParams,
1131
- ...actualParams,
1132
- accessToken,
1081
+ ...params,
1133
1082
  ref,
1134
1083
  integrationFieldsRef,
1135
- routes,
1084
+ routes: params.routes || this.routes,
1085
+ accessToken: undefined,
1136
1086
  });
1137
1087
  }
1138
1088
 
@@ -1161,15 +1111,14 @@ export class Client {
1161
1111
 
1162
1112
  if (typeof globalThis.location !== "undefined") {
1163
1113
  const searchParams = new URLSearchParams(globalThis.location.search);
1114
+
1164
1115
  documentID = documentID || searchParams.get("documentId") || undefined;
1165
1116
  previewToken = previewToken || searchParams.get("token") || undefined;
1166
- } else if (this.refMode.httpRequest?.query) {
1167
- if (typeof this.refMode.httpRequest.query.documentId === "string") {
1168
- documentID = documentID || this.refMode.httpRequest.query.documentId;
1169
- }
1170
- if (typeof this.refMode.httpRequest.query.token === "string") {
1171
- previewToken = previewToken || this.refMode.httpRequest.query.token;
1172
- }
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);
1173
1122
  }
1174
1123
 
1175
1124
  if (documentID != null) {
@@ -1179,10 +1128,7 @@ export class Client {
1179
1128
 
1180
1129
  // We know we have a valid field to resolve since we are using prismicH.documentToLinkField
1181
1130
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1182
- return prismicH.asLink(
1183
- prismicH.documentToLinkField(document),
1184
- args.linkResolver,
1185
- )!;
1131
+ return prismicH.asLink(document, args.linkResolver)!;
1186
1132
  } else {
1187
1133
  return args.defaultURL;
1188
1134
  }
@@ -1201,10 +1147,7 @@ export class Client {
1201
1147
  * ```
1202
1148
  */
1203
1149
  queryLatestContent(): void {
1204
- this.refMode = {
1205
- ...this.refMode,
1206
- type: RefStateType.Master,
1207
- };
1150
+ this.refState.mode = RefStateMode.Master;
1208
1151
  }
1209
1152
 
1210
1153
  /**
@@ -1223,10 +1166,10 @@ export class Client {
1223
1166
  * @param id - The ID of the Release.
1224
1167
  */
1225
1168
  queryContentFromReleaseByID(releaseID: string): void {
1226
- this.refMode = {
1227
- ...this.refMode,
1228
- type: RefStateType.ReleaseByID,
1229
- payload: { releaseID: releaseID },
1169
+ this.refState = {
1170
+ ...this.refState,
1171
+ mode: RefStateMode.ReleaseID,
1172
+ releaseID,
1230
1173
  };
1231
1174
  }
1232
1175
 
@@ -1246,10 +1189,10 @@ export class Client {
1246
1189
  * @param label - The label of the Release.
1247
1190
  */
1248
1191
  queryContentFromReleaseByLabel(releaseLabel: string): void {
1249
- this.refMode = {
1250
- ...this.refMode,
1251
- type: RefStateType.ReleaseByLabel,
1252
- payload: { releaseLabel },
1192
+ this.refState = {
1193
+ ...this.refState,
1194
+ mode: RefStateMode.ReleaseLabel,
1195
+ releaseLabel,
1253
1196
  };
1254
1197
  }
1255
1198
 
@@ -1270,10 +1213,10 @@ export class Client {
1270
1213
  * @param ref - The ref or a function that returns the ref from which to query content.
1271
1214
  */
1272
1215
  queryContentFromRef(ref: RefStringOrThunk): void {
1273
- this.refMode = {
1274
- ...this.refMode,
1275
- type: RefStateType.Manual,
1276
- payload: { refStringOrFn: ref },
1216
+ this.refState = {
1217
+ ...this.refState,
1218
+ mode: RefStateMode.Manual,
1219
+ ref,
1277
1220
  };
1278
1221
  }
1279
1222
 
@@ -1283,20 +1226,15 @@ export class Client {
1283
1226
  * @returns Cached repository metadata.
1284
1227
  */
1285
1228
  private async getCachedRepository(): Promise<prismicT.Repository> {
1286
- const cacheKey = this.endpoint;
1287
-
1288
- const cachedRepository =
1289
- this.internalCache.get<prismicT.Repository>(cacheKey);
1290
-
1291
- if (cachedRepository) {
1292
- return cachedRepository;
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();
1293
1235
  }
1294
1236
 
1295
- const repository = await this.getRepository();
1296
-
1297
- this.internalCache.set(cacheKey, repository, REPOSITORY_CACHE_TTL);
1298
-
1299
- return repository;
1237
+ return this.cachedRepository;
1300
1238
  }
1301
1239
 
1302
1240
  /**
@@ -1313,60 +1251,16 @@ export class Client {
1313
1251
  const form = cachedRepository.forms[name];
1314
1252
 
1315
1253
  if (!form) {
1316
- 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
+ );
1317
1259
  }
1318
1260
 
1319
1261
  return form;
1320
1262
  }
1321
1263
 
1322
- /**
1323
- * Returns the preview ref for the client, if one exists.
1324
- *
1325
- * If this method is used in the browser, the browser's cookies will be read.
1326
- * If this method is used on the server, the cookies from the saved HTTP
1327
- * Request will be read, if an HTTP Request was given.
1328
- *
1329
- * @returns The preview ref as a string, if one exists.
1330
- */
1331
- private getPreviewRefString(): string | undefined {
1332
- if (globalThis.document?.cookie) {
1333
- return getCookie(cookie.preview, globalThis.document.cookie);
1334
- } else if (this.refMode.httpRequest?.headers?.cookie) {
1335
- return getCookie(cookie.preview, this.refMode.httpRequest.headers.cookie);
1336
- }
1337
- }
1338
-
1339
- /**
1340
- * Returns the Integration Fields ref for the client, if one exists. This ref
1341
- * is used to fetch the latest content from a Integration Field's API.
1342
- *
1343
- * @returns The repository's Integration Fields ref.
1344
- */
1345
- private async getIntegrationFieldsRef(): Promise<string | undefined> {
1346
- const repository = await this.getCachedRepository();
1347
-
1348
- return repository.integrationFieldsRef || undefined;
1349
- }
1350
-
1351
- /**
1352
- * Returns the Integration Fields ref neeed to query based on the client's
1353
- * configuration. This method may make a network request to fetch a ref or
1354
- * resolve the user's Integration Field ref thunk.
1355
- *
1356
- * @returns The repository's Integration Fields ref, if one is available.
1357
- */
1358
- private async getResolvedIntegrationFieldsRef(): Promise<string | undefined> {
1359
- const thisIntegrationFieldsRefThunk = castThunk(this.integrationFieldsRef);
1360
-
1361
- const res = await thisIntegrationFieldsRefThunk();
1362
-
1363
- if (typeof res === "string") {
1364
- return res;
1365
- } else {
1366
- return await this.getIntegrationFieldsRef();
1367
- }
1368
- }
1369
-
1370
1264
  /**
1371
1265
  * Returns the ref needed to query based on the client's current state. This
1372
1266
  * method may make a network request to fetch a ref or resolve the user's ref thunk.
@@ -1389,75 +1283,41 @@ export class Client {
1389
1283
  * @returns The ref to use during a query.
1390
1284
  */
1391
1285
  private async getResolvedRefString(): Promise<string> {
1392
- if (this.refMode.autoPreviewsEnabled) {
1393
- 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
+ }
1394
1297
 
1395
1298
  if (previewRef) {
1396
1299
  return previewRef;
1397
1300
  }
1398
1301
  }
1399
1302
 
1400
- switch (this.refMode.type) {
1401
- case RefStateType.ReleaseByID: {
1402
- const releaseID = this.refMode.payload.releaseID;
1403
- const repository = await this.getCachedRepository();
1404
- const ref = findRef(repository.refs, (ref) => ref.id === releaseID);
1405
-
1406
- return ref.ref;
1407
- }
1408
-
1409
- case RefStateType.ReleaseByLabel: {
1410
- const releaseLabel = this.refMode.payload.releaseLabel;
1411
- const repository = await this.getCachedRepository();
1412
- const ref = findRef(
1413
- repository.refs,
1414
- (ref) => ref.label === releaseLabel,
1415
- );
1416
-
1417
- return ref.ref;
1418
- }
1419
-
1420
- case RefStateType.Manual: {
1421
- const thisRefThunk = castThunk(this.refMode.payload.refStringOrFn);
1422
-
1423
- const res = await thisRefThunk();
1424
-
1425
- if (typeof res === "string") {
1426
- return res;
1427
- }
1428
- }
1429
-
1430
- case RefStateType.Master:
1431
- default: {
1432
- const repository = await this.getCachedRepository();
1433
- const ref = findRef(repository.refs, (ref) => ref.isMasterRef);
1303
+ const cachedRepository = await this.getCachedRepository();
1434
1304
 
1435
- 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;
1436
1316
  }
1437
1317
  }
1438
- }
1439
1318
 
1440
- /**
1441
- * Returns the network request options required by the Prismic repository.
1442
- *
1443
- * It currently only includes an Authorization header if an access token is provided.
1444
- *
1445
- * @param params - Parameters for the query, including an access token.
1446
- *
1447
- * @returns Request options that can be used to make a network request to
1448
- * query the repository.
1449
- */
1450
- // TODO: Uncomment when the Authorization header can be used
1451
- // @see Related issue - {@link https://github.com/prismicio/issue-tracker-wroom/issues/351}
1452
- // private buildRequestOptions(
1453
- // params?: Partial<BuildQueryURLArgs>
1454
- // ): RequestInitLike {
1455
- // const accessToken = params?.accessToken || this.accessToken;
1456
-
1457
- // return accessToken
1458
- // ? { headers: { Authorization: `Token ${accessToken}` } }
1459
- // : {};
1460
- // }
1319
+ return findMasterRef(cachedRepository.refs).ref;
1320
+ }
1461
1321
 
1462
1322
  /**
1463
1323
  * Performs a network request using the configured `fetch` function. It
@@ -1472,15 +1332,14 @@ export class Client {
1472
1332
  */
1473
1333
  private async fetch<T = unknown>(
1474
1334
  url: string,
1475
- // TODO: Uncomment when the Authorization header can be used
1476
- // @see Related issue - {@link https://github.com/prismicio/issue-tracker-wroom/issues/351}
1477
- // params?: Partial<BuildQueryURLArgs>
1335
+ params?: Partial<BuildQueryURLArgs>,
1478
1336
  ): Promise<T> {
1479
- // TODO: Uncomment when the Authorization header can be used
1480
- // @see Related issue - {@link https://github.com/prismicio/issue-tracker-wroom/issues/351}
1481
- // const options = this.buildRequestOptions(params);
1482
- // const res = await this.fetchFn(url, options);
1483
- const res = await this.fetchFn(url);
1337
+ const accessToken = (params && params.accessToken) || this.accessToken;
1338
+ const options = accessToken
1339
+ ? { headers: { Authorization: `Token ${accessToken}` } }
1340
+ : {};
1341
+
1342
+ const res = await this.fetchFn(url, options);
1484
1343
 
1485
1344
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1486
1345
  let json: any;
@@ -1489,7 +1348,7 @@ export class Client {
1489
1348
  // Content Type. If not, this will throw, signaling an invalid response.
1490
1349
  json = await res.json();
1491
1350
  } catch {
1492
- throw new PrismicError(undefined, { url });
1351
+ throw new PrismicError(undefined, url, undefined);
1493
1352
  }
1494
1353
 
1495
1354
  switch (res.status) {
@@ -1502,14 +1361,7 @@ export class Client {
1502
1361
  // - Invalid predicate syntax
1503
1362
  // - Ref not provided (ignored)
1504
1363
  case 400: {
1505
- if (isParsingErrorAPIResponse(json)) {
1506
- throw new ParsingError(json.message, {
1507
- url,
1508
- response: json,
1509
- });
1510
- }
1511
-
1512
- break;
1364
+ throw new ParsingError(json.message, url, json);
1513
1365
  }
1514
1366
 
1515
1367
  // Unauthorized
@@ -1520,18 +1372,14 @@ export class Client {
1520
1372
  // - Missing access token for query endpoint
1521
1373
  // - Incorrect access token for query endpoint
1522
1374
  case 403: {
1523
- if (isForbiddenErrorAPIResponse(json)) {
1524
- throw new ForbiddenError(
1525
- "error" in json ? json.error : json.message,
1526
- {
1527
- url,
1528
- response: json,
1529
- },
1530
- );
1531
- }
1375
+ throw new ForbiddenError(
1376
+ "error" in json ? json.error : json.message,
1377
+ url,
1378
+ json,
1379
+ );
1532
1380
  }
1533
1381
  }
1534
1382
 
1535
- throw new PrismicError(undefined, { url, response: json });
1383
+ throw new PrismicError(undefined, url, json);
1536
1384
  }
1537
1385
  }