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