@prismicio/client 7.9.0 → 7.10.0

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