prismic-ts-codegen 0.1.21 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/_node_modules/@prismicio/client/dist/BaseClient.cjs +97 -0
  2. package/dist/_node_modules/@prismicio/client/dist/BaseClient.cjs.map +1 -0
  3. package/dist/_node_modules/@prismicio/client/dist/BaseClient.js +97 -0
  4. package/dist/_node_modules/@prismicio/client/dist/BaseClient.js.map +1 -0
  5. package/dist/_node_modules/@prismicio/client/dist/Client.cjs +1179 -0
  6. package/dist/_node_modules/@prismicio/client/dist/Client.cjs.map +1 -0
  7. package/dist/_node_modules/@prismicio/client/dist/Client.js +1179 -0
  8. package/dist/_node_modules/@prismicio/client/dist/Client.js.map +1 -0
  9. package/dist/_node_modules/@prismicio/client/dist/buildQueryURL.cjs +7 -0
  10. package/dist/_node_modules/@prismicio/client/dist/buildQueryURL.cjs.map +1 -1
  11. package/dist/_node_modules/@prismicio/client/dist/buildQueryURL.js +7 -0
  12. package/dist/_node_modules/@prismicio/client/dist/buildQueryURL.js.map +1 -1
  13. package/dist/_node_modules/@prismicio/client/dist/createClient.cjs +2 -1172
  14. package/dist/_node_modules/@prismicio/client/dist/createClient.cjs.map +1 -1
  15. package/dist/_node_modules/@prismicio/client/dist/createClient.js +1 -1171
  16. package/dist/_node_modules/@prismicio/client/dist/createClient.js.map +1 -1
  17. package/dist/_node_modules/@prismicio/client/dist/errors/PrismicError.cjs +1 -4
  18. package/dist/_node_modules/@prismicio/client/dist/errors/PrismicError.cjs.map +1 -1
  19. package/dist/_node_modules/@prismicio/client/dist/errors/PrismicError.js +1 -4
  20. package/dist/_node_modules/@prismicio/client/dist/errors/PrismicError.js.map +1 -1
  21. package/dist/_node_modules/@prismicio/client/dist/getRepositoryName.cjs +7 -2
  22. package/dist/_node_modules/@prismicio/client/dist/getRepositoryName.cjs.map +1 -1
  23. package/dist/_node_modules/@prismicio/client/dist/getRepositoryName.js +7 -2
  24. package/dist/_node_modules/@prismicio/client/dist/getRepositoryName.js.map +1 -1
  25. package/dist/_node_modules/@prismicio/client/dist/helpers/documentToLinkField.cjs +1 -0
  26. package/dist/_node_modules/@prismicio/client/dist/helpers/documentToLinkField.cjs.map +1 -1
  27. package/dist/_node_modules/@prismicio/client/dist/helpers/documentToLinkField.js +1 -0
  28. package/dist/_node_modules/@prismicio/client/dist/helpers/documentToLinkField.js.map +1 -1
  29. package/dist/_node_modules/@prismicio/client/dist/lib/pLimit.cjs +49 -0
  30. package/dist/_node_modules/@prismicio/client/dist/lib/pLimit.cjs.map +1 -0
  31. package/dist/_node_modules/@prismicio/client/dist/lib/pLimit.js +49 -0
  32. package/dist/_node_modules/@prismicio/client/dist/lib/pLimit.js.map +1 -0
  33. package/dist/_node_modules/@prismicio/client/dist/package.json.cjs +1 -1
  34. package/dist/_node_modules/@prismicio/client/dist/package.json.cjs.map +1 -1
  35. package/dist/_node_modules/@prismicio/client/dist/package.json.js +1 -1
  36. package/dist/_node_modules/@prismicio/client/dist/package.json.js.map +1 -1
  37. package/dist/generateTypes.cjs +12 -0
  38. package/dist/generateTypes.cjs.map +1 -1
  39. package/dist/generateTypes.js +12 -0
  40. package/dist/generateTypes.js.map +1 -1
  41. package/package.json +2 -2
  42. package/src/generateTypes.ts +24 -0
@@ -0,0 +1,1179 @@
1
+ import { appendFilters } from "./lib/appendFilters.js";
2
+ import { castThunk } from "./lib/castThunk.js";
3
+ import { devMsg } from "./lib/devMsg.js";
4
+ import { everyTagFilter } from "./lib/everyTagFilter.js";
5
+ import { findMasterRef } from "./lib/findMasterRef.js";
6
+ import { findRefByID } from "./lib/findRefByID.js";
7
+ import { findRefByLabel } from "./lib/findRefByLabel.js";
8
+ import { getPreviewCookie } from "./lib/getPreviewCookie.js";
9
+ import { minifyGraphQLQuery } from "./lib/minifyGraphQLQuery.js";
10
+ import { someTagsFilter } from "./lib/someTagsFilter.js";
11
+ import { typeFilter } from "./lib/typeFilter.js";
12
+ import { ForbiddenError } from "./errors/ForbiddenError.js";
13
+ import { NotFoundError } from "./errors/NotFoundError.js";
14
+ import { ParsingError } from "./errors/ParsingError.js";
15
+ import { PreviewTokenExpiredError } from "./errors/PreviewTokenExpired.js";
16
+ import { PrismicError } from "./errors/PrismicError.js";
17
+ import { RefExpiredError } from "./errors/RefExpiredError.js";
18
+ import { RefNotFoundError } from "./errors/RefNotFoundError.js";
19
+ import { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError.js";
20
+ import { asLink } from "./helpers/asLink.js";
21
+ import { BaseClient } from "./BaseClient.js";
22
+ import { buildQueryURL } from "./buildQueryURL.js";
23
+ import { filter } from "./filter.js";
24
+ import { getRepositoryEndpoint } from "./getRepositoryEndpoint.js";
25
+ import { getRepositoryName } from "./getRepositoryName.js";
26
+ import { isRepositoryEndpoint } from "./isRepositoryEndpoint.js";
27
+ var __defProp = Object.defineProperty;
28
+ var __typeError = (msg) => {
29
+ throw TypeError(msg);
30
+ };
31
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
32
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
33
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
34
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
35
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
36
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
37
+ var _repositoryName;
38
+ const MAX_PAGE_SIZE = 100;
39
+ const REPOSITORY_CACHE_TTL = 5e3;
40
+ const GET_ALL_QUERY_DELAY = 500;
41
+ const DEFUALT_RETRY_AFTER_MS = 1e3;
42
+ var RefStateMode;
43
+ (function(RefStateMode2) {
44
+ RefStateMode2["Master"] = "Master";
45
+ RefStateMode2["ReleaseID"] = "ReleaseID";
46
+ RefStateMode2["ReleaseLabel"] = "ReleaseLabel";
47
+ RefStateMode2["Manual"] = "Manual";
48
+ })(RefStateMode || (RefStateMode = {}));
49
+ class Client extends BaseClient {
50
+ /**
51
+ * Creates a Prismic client that can be used to query a repository.
52
+ *
53
+ * If used in an environment where a global `fetch` function is unavailable,
54
+ * such as in some Node.js versions, the `fetch` option must be provided as
55
+ * part of the `options` parameter.
56
+ *
57
+ * @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
58
+ * API V2 endpoint for the repository.
59
+ * @param options - Configuration that determines how content will be queried
60
+ * from the Prismic repository.
61
+ *
62
+ * @returns A client that can query content from the repository.
63
+ */
64
+ constructor(repositoryNameOrEndpoint, options = {}) {
65
+ super(options);
66
+ __privateAdd(this, _repositoryName);
67
+ __publicField(this, "documentAPIEndpoint");
68
+ __publicField(this, "accessToken");
69
+ __publicField(this, "routes");
70
+ __publicField(this, "brokenRoute");
71
+ __publicField(this, "defaultParams");
72
+ __publicField(this, "refState", {
73
+ mode: RefStateMode.Master,
74
+ autoPreviewsEnabled: true
75
+ });
76
+ __publicField(this, "cachedRepository");
77
+ __publicField(this, "cachedRepositoryExpiration", 0);
78
+ if ((options.documentAPIEndpoint || isRepositoryEndpoint(repositoryNameOrEndpoint)) && process.env.NODE_ENV === "development") {
79
+ const documentAPIEndpoint = options.documentAPIEndpoint || repositoryNameOrEndpoint;
80
+ if (/\.prismic\.io\/(?!api\/v2\/?)/i.test(documentAPIEndpoint)) {
81
+ throw new PrismicError("@prismicio/client only supports Prismic Rest API V2. Please provide only the repository name to the first createClient() parameter or use the getRepositoryEndpoint() helper to generate a valid Rest API V2 endpoint URL.", void 0, void 0);
82
+ }
83
+ const hostname = new URL(documentAPIEndpoint).hostname.toLowerCase();
84
+ if (hostname.endsWith(".prismic.io") && !hostname.endsWith(".cdn.prismic.io")) {
85
+ console.warn(`[@prismicio/client] The client was created with a non-CDN endpoint. Convert it to the CDN endpoint for better performance. For more details, see ${devMsg("endpoint-must-use-cdn")}`);
86
+ }
87
+ if (options.documentAPIEndpoint && isRepositoryEndpoint(repositoryNameOrEndpoint) && repositoryNameOrEndpoint !== options.documentAPIEndpoint) {
88
+ console.warn(`[@prismicio/client] Multiple incompatible endpoints were provided. Create the client using a repository name to prevent this error. For more details, see ${devMsg("prefer-repository-name")}`);
89
+ }
90
+ }
91
+ if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
92
+ this.documentAPIEndpoint = repositoryNameOrEndpoint;
93
+ try {
94
+ this.repositoryName = getRepositoryName(repositoryNameOrEndpoint);
95
+ } catch (error) {
96
+ console.warn(`[@prismicio/client] A repository name could not be inferred from the provided endpoint (\`${repositoryNameOrEndpoint}\`). Some methods will be disabled. Create the client using a repository name to prevent this warning. For more details, see ${devMsg("prefer-repository-name")}`);
97
+ }
98
+ } else {
99
+ this.documentAPIEndpoint = options.documentAPIEndpoint || getRepositoryEndpoint(repositoryNameOrEndpoint);
100
+ this.repositoryName = repositoryNameOrEndpoint;
101
+ }
102
+ this.accessToken = options.accessToken;
103
+ this.routes = options.routes;
104
+ this.brokenRoute = options.brokenRoute;
105
+ this.defaultParams = options.defaultParams;
106
+ if (options.ref) {
107
+ this.queryContentFromRef(options.ref);
108
+ }
109
+ this.graphQLFetch = this.graphQLFetch.bind(this);
110
+ }
111
+ /**
112
+ * The Prismic repository's name.
113
+ */
114
+ set repositoryName(value) {
115
+ __privateSet(this, _repositoryName, value);
116
+ }
117
+ /**
118
+ * The Prismic repository's name.
119
+ */
120
+ get repositoryName() {
121
+ if (!__privateGet(this, _repositoryName)) {
122
+ throw new PrismicError(`A repository name is required for this method but one could not be inferred from the provided API endpoint (\`${this.documentAPIEndpoint}\`). To fix this error, provide a repository name when creating the client. For more details, see ${devMsg("prefer-repository-name")}`, void 0, void 0);
123
+ }
124
+ return __privateGet(this, _repositoryName);
125
+ }
126
+ /**
127
+ * The Prismic REST API V2 endpoint for the repository (use
128
+ * `prismic.getRepositoryEndpoint` for the default endpoint).
129
+ *
130
+ * @deprecated Use `documentAPIEndpoint` instead.
131
+ */
132
+ // TODO: Remove in v8.
133
+ set endpoint(value) {
134
+ this.documentAPIEndpoint = value;
135
+ }
136
+ /**
137
+ * The Prismic REST API V2 endpoint for the repository (use
138
+ * `prismic.getRepositoryEndpoint` for the default endpoint).
139
+ *
140
+ * @deprecated Use `documentAPIEndpoint` instead.
141
+ */
142
+ // TODO: Remove in v8.
143
+ get endpoint() {
144
+ return this.documentAPIEndpoint;
145
+ }
146
+ /**
147
+ * Enables the client to automatically query content from a preview session if
148
+ * one is active in browser environments. This is enabled by default in the
149
+ * browser.
150
+ *
151
+ * For server environments, use `enableAutoPreviewsFromReq`.
152
+ *
153
+ * @example
154
+ *
155
+ * ```ts
156
+ * client.enableAutoPreviews()
157
+ * ```
158
+ *
159
+ * @see enableAutoPreviewsFromReq
160
+ */
161
+ enableAutoPreviews() {
162
+ this.refState.autoPreviewsEnabled = true;
163
+ }
164
+ /**
165
+ * Enables the client to automatically query content from a preview session if
166
+ * one is active in server environments. This is disabled by default on the
167
+ * server.
168
+ *
169
+ * For browser environments, use `enableAutoPreviews`.
170
+ *
171
+ * @example
172
+ *
173
+ * ```ts
174
+ * // In an express app
175
+ * app.get("/", function (req, res) {
176
+ * client.enableAutoPreviewsFromReq(req)
177
+ * })
178
+ * ```
179
+ *
180
+ * @param req - An HTTP server request object containing the request's
181
+ * cookies.
182
+ */
183
+ enableAutoPreviewsFromReq(req) {
184
+ this.refState.httpRequest = req;
185
+ this.refState.autoPreviewsEnabled = true;
186
+ }
187
+ /**
188
+ * Disables the client from automatically querying content from a preview
189
+ * session if one is active.
190
+ *
191
+ * Automatic preview content querying is enabled by default unless this method
192
+ * is called.
193
+ *
194
+ * @example
195
+ *
196
+ * ```ts
197
+ * client.disableAutoPreviews()
198
+ * ```
199
+ */
200
+ disableAutoPreviews() {
201
+ this.refState.autoPreviewsEnabled = false;
202
+ }
203
+ /**
204
+ * Queries content from the Prismic repository.
205
+ *
206
+ * @example
207
+ *
208
+ * ```ts
209
+ * const response = await client.get()
210
+ * ```
211
+ *
212
+ * @typeParam TDocument - Type of Prismic documents returned.
213
+ *
214
+ * @param params - Parameters to filter, sort, and paginate results.
215
+ *
216
+ * @returns A paginated response containing the result of the query.
217
+ */
218
+ async get(params) {
219
+ const url = await this.buildQueryURL(params);
220
+ return await this.fetch(url, params);
221
+ }
222
+ /**
223
+ * Queries content from the Prismic repository and returns only the first
224
+ * result, if any.
225
+ *
226
+ * @example
227
+ *
228
+ * ```ts
229
+ * const document = await client.getFirst()
230
+ * ```
231
+ *
232
+ * @typeParam TDocument - Type of the Prismic document returned.
233
+ *
234
+ * @param params - Parameters to filter, sort, and paginate results. @returns
235
+ * The first result of the query, if any.
236
+ */
237
+ async getFirst(params) {
238
+ var _a;
239
+ const actualParams = { ...params };
240
+ if (!(params && params.page) && !(params == null ? void 0 : params.pageSize)) {
241
+ actualParams.pageSize = ((_a = this.defaultParams) == null ? void 0 : _a.pageSize) ?? 1;
242
+ }
243
+ const url = await this.buildQueryURL(actualParams);
244
+ const result = await this.fetch(url, params);
245
+ const firstResult = result.results[0];
246
+ if (firstResult) {
247
+ return firstResult;
248
+ }
249
+ throw new NotFoundError("No documents were returned", url, void 0);
250
+ }
251
+ /**
252
+ * **IMPORTANT**: Avoid using `dangerouslyGetAll` as it may be slower and
253
+ * require more resources than other methods. Prefer using other methods that
254
+ * filter by filters such as `getAllByType`.
255
+ *
256
+ * Queries content from the Prismic repository and returns all matching
257
+ * content. If no filters are provided, all documents will be fetched.
258
+ *
259
+ * This method may make multiple network requests to query all matching
260
+ * content.
261
+ *
262
+ * @example
263
+ *
264
+ * ```ts
265
+ * const response = await client.dangerouslyGetAll()
266
+ * ```
267
+ *
268
+ * @typeParam TDocument - Type of Prismic documents returned.
269
+ *
270
+ * @param params - Parameters to filter, sort, and paginate results.
271
+ *
272
+ * @returns A list of documents matching the query.
273
+ */
274
+ async dangerouslyGetAll(params = {}) {
275
+ var _a;
276
+ const { limit = Infinity, ...actualParams } = params;
277
+ const resolvedParams = {
278
+ ...actualParams,
279
+ pageSize: Math.min(limit, actualParams.pageSize || ((_a = this.defaultParams) == null ? void 0 : _a.pageSize) || MAX_PAGE_SIZE)
280
+ };
281
+ const documents = [];
282
+ let latestResult;
283
+ while ((!latestResult || latestResult.next_page) && documents.length < limit) {
284
+ const page = latestResult ? latestResult.page + 1 : void 0;
285
+ latestResult = await this.get({ ...resolvedParams, page });
286
+ documents.push(...latestResult.results);
287
+ if (latestResult.next_page) {
288
+ await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY));
289
+ }
290
+ }
291
+ return documents.slice(0, limit);
292
+ }
293
+ /**
294
+ * Queries a document from the Prismic repository with a specific ID.
295
+ *
296
+ * @remarks
297
+ * A document's UID is different from its ID. An ID is automatically generated
298
+ * for all documents and is made available on its `id` property. A UID is
299
+ * provided in the Prismic editor and is unique among all documents of its
300
+ * custom type.
301
+ *
302
+ * @example
303
+ *
304
+ * ```ts
305
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
306
+ * ```
307
+ *
308
+ * @typeParam TDocument- Type of the Prismic document returned.
309
+ *
310
+ * @param id - ID of the document.
311
+ * @param params - Parameters to filter, sort, and paginate the results.
312
+ *
313
+ * @returns The document with an ID matching the `id` parameter, if a matching
314
+ * document exists.
315
+ */
316
+ async getByID(id, params) {
317
+ return await this.getFirst(appendFilters(params, filter.at("document.id", id)));
318
+ }
319
+ /**
320
+ * Queries documents from the Prismic repository with specific IDs.
321
+ *
322
+ * @remarks
323
+ * A document's UID is different from its ID. An ID is automatically generated
324
+ * for all documents and is made available on its `id` property. A UID is
325
+ * provided in the Prismic editor and is unique among all documents of its
326
+ * custom type.
327
+ *
328
+ * @example
329
+ *
330
+ * ```ts
331
+ * const response = await client.getByIDs([
332
+ * "WW4bKScAAMAqmluX",
333
+ * "U1kTRgEAAC8A5ldS",
334
+ * ])
335
+ * ```
336
+ *
337
+ * @typeParam TDocument - Type of Prismic documents returned.
338
+ *
339
+ * @param ids - A list of document IDs.
340
+ * @param params - Parameters to filter, sort, and paginate the results.
341
+ *
342
+ * @returns A paginated response containing documents with IDs matching the
343
+ * `ids` parameter.
344
+ */
345
+ async getByIDs(ids, params) {
346
+ return await this.get(appendFilters(params, filter.in("document.id", ids)));
347
+ }
348
+ /**
349
+ * Queries all documents from the Prismic repository with specific IDs.
350
+ *
351
+ * This method may make multiple network requests to query all matching
352
+ * content.
353
+ *
354
+ * @remarks
355
+ * A document's UID is different from its ID. An ID is automatically generated
356
+ * for all documents and is made available on its `id` property. A UID is
357
+ * provided in the Prismic editor and is unique among all documents of its
358
+ * custom type.
359
+ *
360
+ * @example
361
+ *
362
+ * ```ts
363
+ * const response = await client.getAllByIDs([
364
+ * "WW4bKScAAMAqmluX",
365
+ * "U1kTRgEAAC8A5ldS",
366
+ * ])
367
+ * ```
368
+ *
369
+ * @typeParam TDocument - Type of Prismic documents returned.
370
+ *
371
+ * @param ids - A list of document IDs.
372
+ * @param params - Parameters to filter, sort, and paginate the results.
373
+ *
374
+ * @returns A list of documents with IDs matching the `ids` parameter.
375
+ */
376
+ async getAllByIDs(ids, params) {
377
+ return await this.dangerouslyGetAll(appendFilters(params, filter.in("document.id", ids)));
378
+ }
379
+ /**
380
+ * Queries a document from the Prismic repository with a specific UID and
381
+ * custom type.
382
+ *
383
+ * @remarks
384
+ * A document's UID is different from its ID. An ID is automatically generated
385
+ * for all documents and is made available on its `id` property. A UID is
386
+ * provided in the Prismic editor and is unique among all documents of its
387
+ * custom type.
388
+ *
389
+ * @example
390
+ *
391
+ * ```ts
392
+ * const document = await client.getByUID("blog_post", "my-first-post")
393
+ * ```
394
+ *
395
+ * @typeParam TDocument - Type of the Prismic document returned.
396
+ *
397
+ * @param documentType - The API ID of the document's custom type.
398
+ * @param uid - UID of the document.
399
+ * @param params - Parameters to filter, sort, and paginate the results.
400
+ *
401
+ * @returns The document with a UID matching the `uid` parameter, if a
402
+ * matching document exists.
403
+ */
404
+ async getByUID(documentType, uid, params) {
405
+ return await this.getFirst(appendFilters(params, [
406
+ typeFilter(documentType),
407
+ filter.at(`my.${documentType}.uid`, uid)
408
+ ]));
409
+ }
410
+ /**
411
+ * Queries document from the Prismic repository with specific UIDs and Custom
412
+ * Type.
413
+ *
414
+ * @remarks
415
+ * A document's UID is different from its ID. An ID is automatically generated
416
+ * for all documents and is made available on its `id` property. A UID is
417
+ * provided in the Prismic editor and is unique among all documents of its
418
+ * custom type.
419
+ *
420
+ * @example
421
+ *
422
+ * ```ts
423
+ * const document = await client.getByUIDs("blog_post", [
424
+ * "my-first-post",
425
+ * "my-second-post",
426
+ * ])
427
+ * ```
428
+ *
429
+ * @typeParam TDocument - Type of the Prismic document returned.
430
+ *
431
+ * @param documentType - The API ID of the document's custom type.
432
+ * @param uids - A list of document UIDs.
433
+ * @param params - Parameters to filter, sort, and paginate the results.
434
+ *
435
+ * @returns A paginated response containing documents with UIDs matching the
436
+ * `uids` parameter.
437
+ */
438
+ async getByUIDs(documentType, uids, params) {
439
+ return await this.get(appendFilters(params, [
440
+ typeFilter(documentType),
441
+ filter.in(`my.${documentType}.uid`, uids)
442
+ ]));
443
+ }
444
+ /**
445
+ * Queries all documents from the Prismic repository with specific UIDs and
446
+ * custom type.
447
+ *
448
+ * This method may make multiple network requests to query all matching
449
+ * content.
450
+ *
451
+ * @remarks
452
+ * A document's UID is different from its ID. An ID is automatically generated
453
+ * for all documents and is made available on its `id` property. A UID is
454
+ * provided in the Prismic editor and is unique among all documents of its
455
+ * custom type.
456
+ *
457
+ * @example
458
+ *
459
+ * ```ts
460
+ * const response = await client.getAllByUIDs([
461
+ * "my-first-post",
462
+ * "my-second-post",
463
+ * ])
464
+ * ```
465
+ *
466
+ * @typeParam TDocument - Type of Prismic documents returned.
467
+ *
468
+ * @param documentType - The API ID of the document's custom type.
469
+ * @param uids - A list of document UIDs.
470
+ * @param params - Parameters to filter, sort, and paginate the results.
471
+ *
472
+ * @returns A list of documents with UIDs matching the `uids` parameter.
473
+ */
474
+ async getAllByUIDs(documentType, uids, params) {
475
+ return await this.dangerouslyGetAll(appendFilters(params, [
476
+ typeFilter(documentType),
477
+ filter.in(`my.${documentType}.uid`, uids)
478
+ ]));
479
+ }
480
+ /**
481
+ * Queries a singleton document from the Prismic repository for a specific
482
+ * custom type.
483
+ *
484
+ * @remarks
485
+ * A singleton document is one that is configured in Prismic to only allow one
486
+ * instance. For example, a repository may be configured to contain just one
487
+ * Settings document. This is in contrast to a repeatable custom type which
488
+ * allows multiple instances of itself.
489
+ *
490
+ * @example
491
+ *
492
+ * ```ts
493
+ * const document = await client.getSingle("settings")
494
+ * ```
495
+ *
496
+ * @typeParam TDocument - Type of the Prismic document returned.
497
+ *
498
+ * @param documentType - The API ID of the singleton custom type.
499
+ * @param params - Parameters to filter, sort, and paginate the results.
500
+ *
501
+ * @returns The singleton document for the custom type, if a matching document
502
+ * exists.
503
+ */
504
+ async getSingle(documentType, params) {
505
+ return await this.getFirst(appendFilters(params, typeFilter(documentType)));
506
+ }
507
+ /**
508
+ * Queries documents from the Prismic repository for a specific custom type.
509
+ *
510
+ * Use `getAllByType` instead if you need to query all documents for a
511
+ * specific custom type.
512
+ *
513
+ * @example
514
+ *
515
+ * ```ts
516
+ * const response = await client.getByType("blog_post")
517
+ * ```
518
+ *
519
+ * @typeParam TDocument - Type of Prismic documents returned.
520
+ *
521
+ * @param documentType - The API ID of the custom type.
522
+ * @param params - Parameters to filter, sort, and paginate the results.
523
+ *
524
+ * @returns A paginated response containing documents of the custom type.
525
+ */
526
+ async getByType(documentType, params) {
527
+ return await this.get(appendFilters(params, typeFilter(documentType)));
528
+ }
529
+ /**
530
+ * Queries all documents from the Prismic repository for a specific Custom
531
+ * Type.
532
+ *
533
+ * This method may make multiple network requests to query all matching
534
+ * content.
535
+ *
536
+ * @example
537
+ *
538
+ * ```ts
539
+ * const response = await client.getByType("blog_post")
540
+ * ```
541
+ *
542
+ * @typeParam TDocument - Type of Prismic documents returned.
543
+ *
544
+ * @param documentType - The API ID of the custom type.
545
+ * @param params - Parameters to filter, sort, and paginate the results.
546
+ *
547
+ * @returns A list of all documents of the custom type.
548
+ */
549
+ async getAllByType(documentType, params) {
550
+ return await this.dangerouslyGetAll(appendFilters(params, typeFilter(documentType)));
551
+ }
552
+ /**
553
+ * Queries documents from the Prismic repository with a specific tag.
554
+ *
555
+ * Use `getAllByTag` instead if you need to query all documents with a
556
+ * specific tag.
557
+ *
558
+ * @example
559
+ *
560
+ * ```ts
561
+ * const response = await client.getByTag("food")
562
+ * ```
563
+ *
564
+ * @typeParam TDocument - Type of Prismic documents returned.
565
+ *
566
+ * @param tag - The tag that must be included on a document.
567
+ * @param params - Parameters to filter, sort, and paginate the results.
568
+ *
569
+ * @returns A paginated response containing documents with the tag.
570
+ */
571
+ async getByTag(tag, params) {
572
+ return await this.get(appendFilters(params, someTagsFilter(tag)));
573
+ }
574
+ /**
575
+ * Queries all documents from the Prismic repository with a specific tag.
576
+ *
577
+ * This method may make multiple network requests to query all matching
578
+ * content.
579
+ *
580
+ * @example
581
+ *
582
+ * ```ts
583
+ * const response = await client.getAllByTag("food")
584
+ * ```
585
+ *
586
+ * @typeParam TDocument - Type of Prismic documents returned.
587
+ *
588
+ * @param tag - The tag that must be included on a document.
589
+ * @param params - Parameters to filter, sort, and paginate the results.
590
+ *
591
+ * @returns A list of all documents with the tag.
592
+ */
593
+ async getAllByTag(tag, params) {
594
+ return await this.dangerouslyGetAll(appendFilters(params, someTagsFilter(tag)));
595
+ }
596
+ /**
597
+ * Queries documents from the Prismic repository with specific tags. A
598
+ * document must be tagged with all of the queried tags to be included.
599
+ *
600
+ * @example
601
+ *
602
+ * ```ts
603
+ * const response = await client.getByEveryTag(["food", "fruit"])
604
+ * ```
605
+ *
606
+ * @typeParam TDocument - Type of Prismic documents returned.
607
+ *
608
+ * @param tags - A list of tags that must be included on a document.
609
+ * @param params - Parameters to filter, sort, and paginate the results.
610
+ *
611
+ * @returns A paginated response containing documents with the tags.
612
+ */
613
+ async getByEveryTag(tags, params) {
614
+ return await this.get(appendFilters(params, everyTagFilter(tags)));
615
+ }
616
+ /**
617
+ * Queries documents from the Prismic repository with specific tags. A
618
+ * document must be tagged with all of the queried tags to be included.
619
+ *
620
+ * This method may make multiple network requests to query all matching
621
+ * content.
622
+ *
623
+ * @example
624
+ *
625
+ * ```ts
626
+ * const response = await client.getAllByEveryTag(["food", "fruit"])
627
+ * ```
628
+ *
629
+ * @typeParam TDocument - Type of Prismic documents returned.
630
+ *
631
+ * @param tags - A list of tags that must be included on a document.
632
+ * @param params - Parameters to filter, sort, and paginate the results.
633
+ *
634
+ * @returns A list of all documents with the tags.
635
+ */
636
+ async getAllByEveryTag(tags, params) {
637
+ return await this.dangerouslyGetAll(appendFilters(params, everyTagFilter(tags)));
638
+ }
639
+ /**
640
+ * Queries documents from the Prismic repository with specific tags. A
641
+ * document must be tagged with at least one of the queried tags to be
642
+ * included.
643
+ *
644
+ * @example
645
+ *
646
+ * ```ts
647
+ * const response = await client.getByEveryTag(["food", "fruit"])
648
+ * ```
649
+ *
650
+ * @typeParam TDocument - Type of Prismic documents returned.
651
+ *
652
+ * @param tags - A list of tags that must be included on a document.
653
+ * @param params - Parameters to filter, sort, and paginate the results.
654
+ *
655
+ * @returns A paginated response containing documents with at least one of the
656
+ * tags.
657
+ */
658
+ async getBySomeTags(tags, params) {
659
+ return await this.get(appendFilters(params, someTagsFilter(tags)));
660
+ }
661
+ /**
662
+ * Queries documents from the Prismic repository with specific tags. A
663
+ * document must be tagged with at least one of the queried tags to be
664
+ * included.
665
+ *
666
+ * This method may make multiple network requests to query all matching
667
+ * content.
668
+ *
669
+ * @example
670
+ *
671
+ * ```ts
672
+ * const response = await client.getAllBySomeTags(["food", "fruit"])
673
+ * ```
674
+ *
675
+ * @typeParam TDocument - Type of Prismic documents returned.
676
+ *
677
+ * @param tags - A list of tags that must be included on a document.
678
+ * @param params - Parameters to filter, sort, and paginate the results.
679
+ *
680
+ * @returns A list of all documents with at least one of the tags.
681
+ */
682
+ async getAllBySomeTags(tags, params) {
683
+ return await this.dangerouslyGetAll(appendFilters(params, someTagsFilter(tags)));
684
+ }
685
+ /**
686
+ * Returns metadata about the Prismic repository, such as its refs, releases,
687
+ * and custom types.
688
+ *
689
+ * @returns Repository metadata.
690
+ */
691
+ async getRepository(params) {
692
+ const url = new URL(this.documentAPIEndpoint);
693
+ if (this.accessToken) {
694
+ url.searchParams.set("access_token", this.accessToken);
695
+ }
696
+ return await this.fetch(url.toString(), params);
697
+ }
698
+ /**
699
+ * Returns a list of all refs for the Prismic repository.
700
+ *
701
+ * Refs are used to identify which version of the repository's content should
702
+ * be queried. All repositories will have at least one ref pointing to the
703
+ * latest published content called the "master ref".
704
+ *
705
+ * @returns A list of all refs for the Prismic repository.
706
+ */
707
+ async getRefs(params) {
708
+ const repository = await this.getRepository(params);
709
+ return repository.refs;
710
+ }
711
+ /**
712
+ * Returns a ref for the Prismic repository with a matching ID.
713
+ *
714
+ * @param id - ID of the ref.
715
+ *
716
+ * @returns The ref with a matching ID, if it exists.
717
+ */
718
+ async getRefByID(id, params) {
719
+ const refs = await this.getRefs(params);
720
+ return findRefByID(refs, id);
721
+ }
722
+ /**
723
+ * Returns a ref for the Prismic repository with a matching label.
724
+ *
725
+ * @param label - Label of the ref.
726
+ *
727
+ * @returns The ref with a matching label, if it exists.
728
+ */
729
+ async getRefByLabel(label, params) {
730
+ const refs = await this.getRefs(params);
731
+ return findRefByLabel(refs, label);
732
+ }
733
+ /**
734
+ * Returns the master ref for the Prismic repository. The master ref points to
735
+ * the repository's latest published content.
736
+ *
737
+ * @returns The repository's master ref.
738
+ */
739
+ async getMasterRef(params) {
740
+ const refs = await this.getRefs(params);
741
+ return findMasterRef(refs);
742
+ }
743
+ /**
744
+ * Returns a list of all Releases for the Prismic repository. Releases are
745
+ * used to group content changes before publishing.
746
+ *
747
+ * @returns A list of all Releases for the Prismic repository.
748
+ */
749
+ async getReleases(params) {
750
+ const refs = await this.getRefs(params);
751
+ return refs.filter((ref) => !ref.isMasterRef);
752
+ }
753
+ /**
754
+ * Returns a Release for the Prismic repository with a matching ID.
755
+ *
756
+ * @param id - ID of the Release.
757
+ *
758
+ * @returns The Release with a matching ID, if it exists.
759
+ */
760
+ async getReleaseByID(id, params) {
761
+ const releases = await this.getReleases(params);
762
+ return findRefByID(releases, id);
763
+ }
764
+ /**
765
+ * Returns a Release for the Prismic repository with a matching label.
766
+ *
767
+ * @param label - Label of the ref.
768
+ *
769
+ * @returns The ref with a matching label, if it exists.
770
+ */
771
+ async getReleaseByLabel(label, params) {
772
+ const releases = await this.getReleases(params);
773
+ return findRefByLabel(releases, label);
774
+ }
775
+ /**
776
+ * Returns a list of all tags used in the Prismic repository.
777
+ *
778
+ * @returns A list of all tags used in the repository.
779
+ */
780
+ async getTags(params) {
781
+ try {
782
+ const tagsForm = await this.getCachedRepositoryForm("tags", params);
783
+ const url = new URL(tagsForm.action);
784
+ if (this.accessToken) {
785
+ url.searchParams.set("access_token", this.accessToken);
786
+ }
787
+ return await this.fetch(url.toString(), params);
788
+ } catch {
789
+ const repository = await this.getRepository(params);
790
+ return repository.tags;
791
+ }
792
+ }
793
+ /**
794
+ * Builds a URL used to query content from the Prismic repository.
795
+ *
796
+ * @param params - Parameters to filter, sort, and paginate the results.
797
+ *
798
+ * @returns A URL string that can be requested to query content.
799
+ */
800
+ async buildQueryURL({ signal, fetchOptions, ...params } = {}) {
801
+ const ref = params.ref || await this.getResolvedRefString({ signal, fetchOptions });
802
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository({ signal, fetchOptions })).integrationFieldsRef || void 0;
803
+ return buildQueryURL(this.documentAPIEndpoint, {
804
+ ...this.defaultParams,
805
+ ...params,
806
+ ref,
807
+ integrationFieldsRef,
808
+ routes: params.routes || this.routes,
809
+ brokenRoute: params.brokenRoute || this.brokenRoute,
810
+ accessToken: params.accessToken || this.accessToken
811
+ });
812
+ }
813
+ /**
814
+ * Determines the URL for a previewed document during an active preview
815
+ * session. The result of this method should be used to redirect the user to
816
+ * the document's URL.
817
+ *
818
+ * @example
819
+ *
820
+ * ```ts
821
+ * const url = client.resolvePreviewURL({
822
+ * linkResolver: (document) => `/${document.uid}`
823
+ * defaultURL: '/'
824
+ * })
825
+ * ```
826
+ *
827
+ * @param args - Arguments to configure the URL resolving.
828
+ *
829
+ * @returns The URL for the previewed document during an active preview
830
+ * session. The user should be redirected to this URL.
831
+ */
832
+ async resolvePreviewURL(args) {
833
+ var _a, _b;
834
+ let documentID = args.documentID;
835
+ let previewToken = args.previewToken;
836
+ if (typeof globalThis.location !== "undefined") {
837
+ const searchParams = new URLSearchParams(globalThis.location.search);
838
+ documentID = documentID || searchParams.get("documentId");
839
+ previewToken = previewToken || searchParams.get("token");
840
+ } else if (this.refState.httpRequest) {
841
+ if ("query" in this.refState.httpRequest) {
842
+ documentID = documentID || ((_a = this.refState.httpRequest.query) == null ? void 0 : _a.documentId);
843
+ previewToken = previewToken || ((_b = this.refState.httpRequest.query) == null ? void 0 : _b.token);
844
+ } else if ("url" in this.refState.httpRequest && this.refState.httpRequest.url) {
845
+ const searchParams = new URL(this.refState.httpRequest.url, "missing-host://").searchParams;
846
+ documentID = documentID || searchParams.get("documentId");
847
+ previewToken = previewToken || searchParams.get("token");
848
+ }
849
+ }
850
+ if (documentID != null && previewToken != null) {
851
+ const document = await this.getByID(documentID, {
852
+ ref: previewToken,
853
+ lang: "*",
854
+ signal: args.signal,
855
+ fetchOptions: args.fetchOptions
856
+ });
857
+ const url = asLink(document, { linkResolver: args.linkResolver });
858
+ if (typeof url === "string") {
859
+ return url;
860
+ }
861
+ }
862
+ return args.defaultURL;
863
+ }
864
+ /**
865
+ * Configures the client to query the latest published content for all future
866
+ * queries.
867
+ *
868
+ * If the `ref` parameter is provided during a query, it takes priority for
869
+ * that query.
870
+ *
871
+ * @example
872
+ *
873
+ * ```ts
874
+ * await client.queryLatestContent()
875
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
876
+ * ```
877
+ */
878
+ queryLatestContent() {
879
+ this.refState.mode = RefStateMode.Master;
880
+ }
881
+ /**
882
+ * Configures the client to query content from a specific Release identified
883
+ * by its ID for all future queries.
884
+ *
885
+ * If the `ref` parameter is provided during a query, it takes priority for
886
+ * that query.
887
+ *
888
+ * @example
889
+ *
890
+ * ```ts
891
+ * await client.queryContentFromReleaseByID("YLB7OBAAACMA7Cpa")
892
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
893
+ * ```
894
+ *
895
+ * @param releaseID - The ID of the Release.
896
+ */
897
+ queryContentFromReleaseByID(releaseID) {
898
+ this.refState = {
899
+ ...this.refState,
900
+ mode: RefStateMode.ReleaseID,
901
+ releaseID
902
+ };
903
+ }
904
+ /**
905
+ * Configures the client to query content from a specific Release identified
906
+ * by its label for all future queries.
907
+ *
908
+ * If the `ref` parameter is provided during a query, it takes priority for
909
+ * that query.
910
+ *
911
+ * @example
912
+ *
913
+ * ```ts
914
+ * await client.queryContentFromReleaseByLabel("My Release")
915
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
916
+ * ```
917
+ *
918
+ * @param releaseLabel - The label of the Release.
919
+ */
920
+ queryContentFromReleaseByLabel(releaseLabel) {
921
+ this.refState = {
922
+ ...this.refState,
923
+ mode: RefStateMode.ReleaseLabel,
924
+ releaseLabel
925
+ };
926
+ }
927
+ /**
928
+ * Configures the client to query content from a specific ref. The ref can be
929
+ * provided as a string or a function.
930
+ *
931
+ * If a function is provided, the ref is fetched lazily before each query. The
932
+ * function may also be asynchronous.
933
+ *
934
+ * @example
935
+ *
936
+ * ```ts
937
+ * await client.queryContentFromRef("my-ref")
938
+ * const document = await client.getByID("WW4bKScAAMAqmluX")
939
+ * ```
940
+ *
941
+ * @param ref - The ref or a function that returns the ref from which to query
942
+ * content.
943
+ */
944
+ queryContentFromRef(ref) {
945
+ this.refState = {
946
+ ...this.refState,
947
+ mode: RefStateMode.Manual,
948
+ ref
949
+ };
950
+ }
951
+ /**
952
+ * A `fetch()` function to be used with GraphQL clients configured for
953
+ * Prismic's GraphQL API. It automatically applies the necessary `prismic-ref`
954
+ * and Authorization headers. Queries will automatically be minified by
955
+ * removing whitespace where possible.
956
+ *
957
+ * @example
958
+ *
959
+ * ```ts
960
+ * const graphQLClient = new ApolloClient({
961
+ * link: new HttpLink({
962
+ * uri: prismic.getGraphQLEndpoint(repositoryName),
963
+ * // Provide `client.graphQLFetch` as the fetch implementation.
964
+ * fetch: client.graphQLFetch,
965
+ * // Using GET is required.
966
+ * useGETForQueries: true,
967
+ * }),
968
+ * cache: new InMemoryCache(),
969
+ * })
970
+ * ```
971
+ *
972
+ * @param input - The `fetch()` `input` parameter. Only strings are supported.
973
+ * @param init - The `fetch()` `init` parameter. Only plain objects are
974
+ * supported.
975
+ *
976
+ * @returns The `fetch()` Response for the request.
977
+ *
978
+ * @experimental
979
+ */
980
+ async graphQLFetch(input, init) {
981
+ const cachedRepository = await this.getCachedRepository();
982
+ const ref = await this.getResolvedRefString();
983
+ const unsanitizedHeaders = {
984
+ "Prismic-ref": ref,
985
+ Authorization: this.accessToken ? `Token ${this.accessToken}` : "",
986
+ // Asserting `init.headers` is a Record since popular GraphQL
987
+ // libraries pass this as a Record. Header objects as input
988
+ // are unsupported.
989
+ ...init ? init.headers : {}
990
+ };
991
+ if (cachedRepository.integrationFieldsRef) {
992
+ unsanitizedHeaders["Prismic-integration-field-ref"] = cachedRepository.integrationFieldsRef;
993
+ }
994
+ const headers = {};
995
+ for (const key in unsanitizedHeaders) {
996
+ if (unsanitizedHeaders[key]) {
997
+ headers[key.toLowerCase()] = unsanitizedHeaders[key];
998
+ }
999
+ }
1000
+ const url = new URL(
1001
+ // Asserting `input` is a string since popular GraphQL
1002
+ // libraries pass this as a string. Request objects as
1003
+ // input are unsupported.
1004
+ input
1005
+ );
1006
+ url.searchParams.set("ref", ref);
1007
+ const query = url.searchParams.get("query");
1008
+ if (query) {
1009
+ url.searchParams.set(
1010
+ "query",
1011
+ // Compress the GraphQL query (if it exists) by
1012
+ // removing whitespace. This is done to
1013
+ // optimize the query size and avoid
1014
+ // hitting the upper limit of GET requests
1015
+ // (2048 characters).
1016
+ minifyGraphQLQuery(query)
1017
+ );
1018
+ }
1019
+ return await this.fetchFn(url.toString(), {
1020
+ ...init,
1021
+ headers
1022
+ });
1023
+ }
1024
+ /**
1025
+ * Returns a cached version of `getRepository` with a TTL.
1026
+ *
1027
+ * @returns Cached repository metadata.
1028
+ */
1029
+ async getCachedRepository(params) {
1030
+ if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
1031
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1032
+ this.cachedRepository = await this.getRepository(params);
1033
+ }
1034
+ return this.cachedRepository;
1035
+ }
1036
+ /**
1037
+ * Returns a cached Prismic repository form. Forms are used to determine API
1038
+ * endpoints for types of repository data.
1039
+ *
1040
+ * @param name - Name of the form.
1041
+ *
1042
+ * @returns The repository form.
1043
+ *
1044
+ * @throws If a matching form cannot be found.
1045
+ */
1046
+ async getCachedRepositoryForm(name, params) {
1047
+ const cachedRepository = await this.getCachedRepository(params);
1048
+ const form = cachedRepository.forms[name];
1049
+ if (!form) {
1050
+ throw new PrismicError(`Form with name "${name}" could not be found`, void 0, void 0);
1051
+ }
1052
+ return form;
1053
+ }
1054
+ /**
1055
+ * Returns the ref needed to query based on the client's current state. This
1056
+ * method may make a network request to fetch a ref or resolve the user's ref
1057
+ * thunk.
1058
+ *
1059
+ * If auto previews are enabled, the preview ref takes priority if available.
1060
+ *
1061
+ * The following strategies are used depending on the client's state:
1062
+ *
1063
+ * - If the user called `queryLatestContent`: Use the repository's master ref.
1064
+ * The ref is cached for 5 seconds. After 5 seconds, a new master ref is
1065
+ * fetched.
1066
+ * - If the user called `queryContentFromReleaseByID`: Use the release's ref.
1067
+ * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1068
+ * release is fetched.
1069
+ * - If the user called `queryContentFromReleaseByLabel`: Use the release's ref.
1070
+ * The ref is cached for 5 seconds. After 5 seconds, a new ref for the
1071
+ * release is fetched.
1072
+ * - If the user called `queryContentFromRef`: Use the provided ref. Fall back
1073
+ * to the master ref if the ref is not a string.
1074
+ *
1075
+ * @returns The ref to use during a query.
1076
+ */
1077
+ async getResolvedRefString(params) {
1078
+ var _a, _b;
1079
+ if (this.refState.autoPreviewsEnabled) {
1080
+ let previewRef;
1081
+ let cookieJar;
1082
+ if ((_a = this.refState.httpRequest) == null ? void 0 : _a.headers) {
1083
+ if ("get" in this.refState.httpRequest.headers && typeof this.refState.httpRequest.headers.get === "function") {
1084
+ cookieJar = this.refState.httpRequest.headers.get("cookie");
1085
+ } else if ("cookie" in this.refState.httpRequest.headers) {
1086
+ cookieJar = this.refState.httpRequest.headers.cookie;
1087
+ }
1088
+ } else if ((_b = globalThis.document) == null ? void 0 : _b.cookie) {
1089
+ cookieJar = globalThis.document.cookie;
1090
+ }
1091
+ if (cookieJar) {
1092
+ previewRef = getPreviewCookie(cookieJar);
1093
+ }
1094
+ if (previewRef) {
1095
+ return previewRef;
1096
+ }
1097
+ }
1098
+ const cachedRepository = await this.getCachedRepository(params);
1099
+ const refModeType = this.refState.mode;
1100
+ if (refModeType === RefStateMode.ReleaseID) {
1101
+ return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
1102
+ } else if (refModeType === RefStateMode.ReleaseLabel) {
1103
+ return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel).ref;
1104
+ } else if (refModeType === RefStateMode.Manual) {
1105
+ const res = await castThunk(this.refState.ref)();
1106
+ if (typeof res === "string") {
1107
+ return res;
1108
+ }
1109
+ }
1110
+ return findMasterRef(cachedRepository.refs).ref;
1111
+ }
1112
+ /**
1113
+ * Performs a network request using the configured `fetch` function. It
1114
+ * assumes all successful responses will have a JSON content type. It also
1115
+ * normalizes unsuccessful network requests.
1116
+ *
1117
+ * @typeParam T - The JSON response.
1118
+ *
1119
+ * @param url - URL to the resource to fetch.
1120
+ * @param params - Prismic REST API parameters for the network request.
1121
+ *
1122
+ * @returns The JSON response from the network request.
1123
+ */
1124
+ async fetch(url, params = {}) {
1125
+ const res = await super.fetch(url, params);
1126
+ if (res.status !== 404 && res.status !== 429 && res.json == null) {
1127
+ throw new PrismicError(void 0, url, res.json || res.text);
1128
+ }
1129
+ switch (res.status) {
1130
+ case 200:
1131
+ case 201: {
1132
+ return res.json;
1133
+ }
1134
+ case 400: {
1135
+ throw new ParsingError(res.json.message, url, res.json);
1136
+ }
1137
+ case 401:
1138
+ case 403: {
1139
+ throw new ForbiddenError(res.json.error || res.json.message, url, res.json);
1140
+ }
1141
+ case 404: {
1142
+ if (res.json === void 0) {
1143
+ throw new RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url, url.startsWith(this.documentAPIEndpoint) ? void 0 : res.text);
1144
+ }
1145
+ if (res.json.type === "api_notfound_error") {
1146
+ throw new RefNotFoundError(res.json.message, url, res.json);
1147
+ }
1148
+ if (res.json.type === "api_security_error" && /preview token.*expired/i.test(res.json.message)) {
1149
+ throw new PreviewTokenExpiredError(res.json.message, url, res.json);
1150
+ }
1151
+ throw new NotFoundError(res.json.message, url, res.json);
1152
+ }
1153
+ case 410: {
1154
+ throw new RefExpiredError(res.json.message, url, res.json);
1155
+ }
1156
+ case 429: {
1157
+ const parsedRetryAfter = Number(res.headers.get("retry-after"));
1158
+ const delay = Number.isNaN(parsedRetryAfter) ? DEFUALT_RETRY_AFTER_MS : parsedRetryAfter;
1159
+ return await new Promise((resolve, reject) => {
1160
+ setTimeout(async () => {
1161
+ try {
1162
+ resolve(await this.fetch(url, params));
1163
+ } catch (error) {
1164
+ reject(error);
1165
+ }
1166
+ }, delay);
1167
+ });
1168
+ }
1169
+ }
1170
+ throw new PrismicError(void 0, url, res.json);
1171
+ }
1172
+ }
1173
+ _repositoryName = /* @__PURE__ */ new WeakMap();
1174
+ export {
1175
+ Client,
1176
+ GET_ALL_QUERY_DELAY,
1177
+ REPOSITORY_CACHE_TTL
1178
+ };
1179
+ //# sourceMappingURL=Client.js.map