@prismicio/client 7.21.0-pr.418.5699631 → 7.21.0-pr.419.4409b0e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Client.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  const require_filter = require('./filter.cjs');
2
2
  const require_appendFilters = require('./lib/appendFilters.cjs');
3
+ const require_castThunk = require('./lib/castThunk.cjs');
3
4
  const require_devMsg = require('./lib/devMsg.cjs');
4
5
  const require_everyTagFilter = require('./lib/everyTagFilter.cjs');
5
6
  const require_PrismicError = require('./errors/PrismicError.cjs');
@@ -53,6 +54,28 @@ const GET_ALL_QUERY_DELAY = 500;
53
54
  */
54
55
  const MAX_INVALID_REF_RETRY_ATTEMPTS = 3;
55
56
  /**
57
+ * Modes for client ref management.
58
+ */
59
+ var RefStateMode = /* @__PURE__ */ function(RefStateMode$1) {
60
+ /**
61
+ * Use the repository's master ref.
62
+ */
63
+ RefStateMode$1["Master"] = "Master";
64
+ /**
65
+ * Use a given Release identified by its ID.
66
+ */
67
+ RefStateMode$1["ReleaseID"] = "ReleaseID";
68
+ /**
69
+ * Use a given Release identified by its label.
70
+ */
71
+ RefStateMode$1["ReleaseLabel"] = "ReleaseLabel";
72
+ /**
73
+ * Use a given ref.
74
+ */
75
+ RefStateMode$1["Manual"] = "Manual";
76
+ return RefStateMode$1;
77
+ }(RefStateMode || {});
78
+ /**
56
79
  * A client that allows querying content from a Prismic repository.
57
80
  *
58
81
  * If used in an environment where a global `fetch` function is unavailable,
@@ -135,17 +158,16 @@ var Client = class {
135
158
  * be overridden on each query if needed.
136
159
  */
137
160
  defaultParams;
138
- #getRef;
139
- #autoPreviews = true;
140
- #autoPreviewsRequest;
141
- /**
142
- * Cached repository value.
143
- */
144
- cachedRepository;
145
161
  /**
146
- * Timestamp at which the cached repository data is considered stale.
162
+ * The client's ref mode state. This determines which ref is used during
163
+ * queries.
147
164
  */
148
- cachedRepositoryExpiration = 0;
165
+ refState = {
166
+ mode: RefStateMode.Master,
167
+ autoPreviewsEnabled: true
168
+ };
169
+ #cachedRepository;
170
+ #cachedRepositoryExpiration = 0;
149
171
  /**
150
172
  * Creates a Prismic client that can be used to query a repository.
151
173
  *
@@ -207,7 +229,7 @@ var Client = class {
207
229
  * @see enableAutoPreviewsFromReq
208
230
  */
209
231
  enableAutoPreviews() {
210
- this.#autoPreviews = true;
232
+ this.refState.autoPreviewsEnabled = true;
211
233
  }
212
234
  /**
213
235
  * Enables the client to automatically query content from a preview session if
@@ -228,9 +250,9 @@ var Client = class {
228
250
  * @param req - An HTTP server request object containing the request's
229
251
  * cookies.
230
252
  */
231
- enableAutoPreviewsFromReq(request$1) {
232
- this.enableAutoPreviews();
233
- this.#autoPreviewsRequest = request$1;
253
+ enableAutoPreviewsFromReq(req) {
254
+ this.refState.httpRequest = req;
255
+ this.refState.autoPreviewsEnabled = true;
234
256
  }
235
257
  /**
236
258
  * Disables the client from automatically querying content from a preview
@@ -246,8 +268,7 @@ var Client = class {
246
268
  * ```
247
269
  */
248
270
  disableAutoPreviews() {
249
- this.#autoPreviews = false;
250
- this.#autoPreviewsRequest = void 0;
271
+ this.refState.autoPreviewsEnabled = false;
251
272
  }
252
273
  /**
253
274
  * Queries content from the Prismic repository.
@@ -265,8 +286,7 @@ var Client = class {
265
286
  * @returns A paginated response containing the result of the query.
266
287
  */
267
288
  async get(params) {
268
- const { data } = await this._get(params);
269
- return data;
289
+ return await (await this.#internalGet(params)).json();
270
290
  }
271
291
  /**
272
292
  * Queries content from the Prismic repository and returns only the first
@@ -285,15 +305,14 @@ var Client = class {
285
305
  * @returns The first result of the query, if any.
286
306
  */
287
307
  async getFirst(params) {
288
- const actualParams = { ...params };
289
- if (!(params && params.page) && !(params === null || params === void 0 ? void 0 : params.pageSize)) {
290
- var _this$defaultParams;
291
- actualParams.pageSize = ((_this$defaultParams = this.defaultParams) === null || _this$defaultParams === void 0 ? void 0 : _this$defaultParams.pageSize) ?? 1;
292
- }
293
- const { data, url } = await this._get(actualParams);
294
- const firstResult = data.results[0];
295
- if (firstResult) return firstResult;
296
- throw new require_NotFoundError.NotFoundError("No documents were returned", url, void 0);
308
+ const actualParams = (params === null || params === void 0 ? void 0 : params.page) || (params === null || params === void 0 ? void 0 : params.pageSize) ? params : {
309
+ ...params,
310
+ pageSize: 1
311
+ };
312
+ const response = await this.#internalGet(actualParams);
313
+ const { results } = await response.clone().json();
314
+ if (results[0]) return results[0];
315
+ throw new require_NotFoundError.NotFoundError("No documents were returned", response.url, void 0);
297
316
  }
298
317
  /**
299
318
  * **IMPORTANT**: Avoid using `dangerouslyGetAll` as it may be slower and
@@ -319,11 +338,11 @@ var Client = class {
319
338
  * @returns A list of documents matching the query.
320
339
  */
321
340
  async dangerouslyGetAll(params = {}) {
322
- var _this$defaultParams2;
341
+ var _this$defaultParams;
323
342
  const { limit = Infinity,...actualParams } = params;
324
343
  const resolvedParams = {
325
344
  ...actualParams,
326
- pageSize: Math.min(limit, actualParams.pageSize || ((_this$defaultParams2 = this.defaultParams) === null || _this$defaultParams2 === void 0 ? void 0 : _this$defaultParams2.pageSize) || MAX_PAGE_SIZE)
345
+ pageSize: Math.min(limit, actualParams.pageSize || ((_this$defaultParams = this.defaultParams) === null || _this$defaultParams === void 0 ? void 0 : _this$defaultParams.pageSize) || MAX_PAGE_SIZE)
327
346
  };
328
347
  const documents = [];
329
348
  let latestResult;
@@ -728,19 +747,18 @@ var Client = class {
728
747
  * @returns Repository metadata.
729
748
  */
730
749
  async getRepository(params) {
750
+ if (this.#cachedRepository && this.#cachedRepositoryExpiration > Date.now()) return this.#cachedRepository;
731
751
  const url = new URL(this.documentAPIEndpoint);
732
752
  const accessToken = (params === null || params === void 0 ? void 0 : params.accessToken) || this.accessToken;
733
753
  if (accessToken) url.searchParams.set("access_token", accessToken);
734
754
  const response = await this.#request(url, params);
735
- switch (response.status) {
736
- case 200: return await response.json();
737
- case 401: {
738
- const json = await response.json();
739
- throw new require_ForbiddenError.ForbiddenError(json.error, url.toString(), json);
740
- }
741
- case 404: throw new require_RepositoryNotFoundError.RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url.toString(), void 0);
742
- default: throw new require_PrismicError.PrismicError(void 0, url.toString(), await response.text());
755
+ if (response.ok) {
756
+ this.#cachedRepository = await response.json();
757
+ this.#cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
758
+ return this.#cachedRepository;
743
759
  }
760
+ if (response.status === 404) throw new require_RepositoryNotFoundError.RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url.toString(), void 0);
761
+ return await this.#throwContentAPIError(response, url.toString());
744
762
  }
745
763
  /**
746
764
  * Returns a list of all refs for the Prismic repository.
@@ -818,14 +836,15 @@ var Client = class {
818
836
  * @returns A list of all tags used in the repository.
819
837
  */
820
838
  async getTags(params) {
821
- const form = (await this.getCachedRepository(params)).forms.tags;
839
+ const repository = await this.getRepository(params);
840
+ const form = repository.forms.tags;
822
841
  if (form) {
823
842
  const url = new URL(form.action);
824
843
  if (this.accessToken) url.searchParams.set("access_token", this.accessToken);
825
844
  const response = await this.#request(url, params);
826
845
  if (response.ok) return await response.json();
827
846
  }
828
- return (await this.getRepository(params)).tags;
847
+ return repository.tags;
829
848
  }
830
849
  /**
831
850
  * Builds a URL used to query content from the Prismic repository.
@@ -835,12 +854,12 @@ var Client = class {
835
854
  * @returns A URL string that can be requested to query content.
836
855
  */
837
856
  async buildQueryURL({ signal, fetchOptions,...params } = {}) {
838
- const ref = params.ref || await this.#getResolvedRef({
857
+ const ref = params.ref || await this.getResolvedRefString({
839
858
  accessToken: params.accessToken,
840
859
  signal,
841
860
  fetchOptions
842
861
  });
843
- const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository({
862
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getRepository({
844
863
  accessToken: params.accessToken,
845
864
  signal,
846
865
  fetchOptions
@@ -881,13 +900,13 @@ var Client = class {
881
900
  const searchParams = new URLSearchParams(globalThis.location.search);
882
901
  documentID = documentID || searchParams.get("documentId");
883
902
  previewToken = previewToken || searchParams.get("token");
884
- } else if (this.#autoPreviewsRequest) {
885
- if ("query" in this.#autoPreviewsRequest) {
886
- var _this$autoPreviewsReq, _this$autoPreviewsReq2;
887
- documentID = documentID || ((_this$autoPreviewsReq = this.#autoPreviewsRequest.query) === null || _this$autoPreviewsReq === void 0 ? void 0 : _this$autoPreviewsReq.documentId);
888
- previewToken = previewToken || ((_this$autoPreviewsReq2 = this.#autoPreviewsRequest.query) === null || _this$autoPreviewsReq2 === void 0 ? void 0 : _this$autoPreviewsReq2.token);
889
- } else if ("url" in this.#autoPreviewsRequest && this.#autoPreviewsRequest.url) {
890
- const searchParams = new URL(this.#autoPreviewsRequest.url, "missing-host://").searchParams;
903
+ } else if (this.refState.httpRequest) {
904
+ if ("query" in this.refState.httpRequest) {
905
+ var _this$refState$httpRe, _this$refState$httpRe2;
906
+ documentID = documentID || ((_this$refState$httpRe = this.refState.httpRequest.query) === null || _this$refState$httpRe === void 0 ? void 0 : _this$refState$httpRe.documentId);
907
+ previewToken = previewToken || ((_this$refState$httpRe2 = this.refState.httpRequest.query) === null || _this$refState$httpRe2 === void 0 ? void 0 : _this$refState$httpRe2.token);
908
+ } else if ("url" in this.refState.httpRequest && this.refState.httpRequest.url) {
909
+ const searchParams = new URL(this.refState.httpRequest.url, "missing-host://").searchParams;
891
910
  documentID = documentID || searchParams.get("documentId");
892
911
  previewToken = previewToken || searchParams.get("token");
893
912
  }
@@ -918,7 +937,7 @@ var Client = class {
918
937
  * ```
919
938
  */
920
939
  queryLatestContent() {
921
- this.#getRef = void 0;
940
+ this.refState.mode = RefStateMode.Master;
922
941
  }
923
942
  /**
924
943
  * Configures the client to query content from a specific Release identified
@@ -936,9 +955,11 @@ var Client = class {
936
955
  *
937
956
  * @param releaseID - The ID of the Release.
938
957
  */
939
- queryContentFromReleaseByID(id) {
940
- this.#getRef = async (params) => {
941
- return (await this.getReleaseByID(id, params)).ref;
958
+ queryContentFromReleaseByID(releaseID) {
959
+ this.refState = {
960
+ ...this.refState,
961
+ mode: RefStateMode.ReleaseID,
962
+ releaseID
942
963
  };
943
964
  }
944
965
  /**
@@ -957,9 +978,11 @@ var Client = class {
957
978
  *
958
979
  * @param releaseLabel - The label of the Release.
959
980
  */
960
- queryContentFromReleaseByLabel(label) {
961
- this.#getRef = async (params) => {
962
- return (await this.getReleaseByLabel(label, params)).ref;
981
+ queryContentFromReleaseByLabel(releaseLabel) {
982
+ this.refState = {
983
+ ...this.refState,
984
+ mode: RefStateMode.ReleaseLabel,
985
+ releaseLabel
963
986
  };
964
987
  }
965
988
  /**
@@ -980,7 +1003,11 @@ var Client = class {
980
1003
  * content.
981
1004
  */
982
1005
  queryContentFromRef(ref) {
983
- this.#getRef = typeof ref === "string" ? () => ref : ref;
1006
+ this.refState = {
1007
+ ...this.refState,
1008
+ mode: RefStateMode.Manual,
1009
+ ref
1010
+ };
984
1011
  }
985
1012
  /**
986
1013
  * A `fetch()` function to be used with GraphQL clients configured for
@@ -1012,14 +1039,14 @@ var Client = class {
1012
1039
  * @experimental
1013
1040
  */
1014
1041
  async graphQLFetch(input, init) {
1015
- const cachedRepository = await this.getCachedRepository();
1016
- const ref = await this.#getResolvedRef();
1042
+ const repository = await this.getRepository();
1043
+ const ref = await this.getResolvedRefString();
1017
1044
  const unsanitizedHeaders = {
1018
1045
  "Prismic-ref": ref,
1019
1046
  Authorization: this.accessToken ? `Token ${this.accessToken}` : "",
1020
1047
  ...init ? init.headers : {}
1021
1048
  };
1022
- if (cachedRepository.integrationFieldsRef) unsanitizedHeaders["Prismic-integration-field-ref"] = cachedRepository.integrationFieldsRef;
1049
+ if (repository.integrationFieldsRef) unsanitizedHeaders["Prismic-integration-field-ref"] = repository.integrationFieldsRef;
1023
1050
  const headers = {};
1024
1051
  for (const key in unsanitizedHeaders) if (unsanitizedHeaders[key]) headers[key.toLowerCase()] = unsanitizedHeaders[key];
1025
1052
  const url = new URL(input);
@@ -1032,18 +1059,6 @@ var Client = class {
1032
1059
  });
1033
1060
  }
1034
1061
  /**
1035
- * Returns a cached version of `getRepository` with a TTL.
1036
- *
1037
- * @returns Cached repository metadata.
1038
- */
1039
- async getCachedRepository(params) {
1040
- if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
1041
- this.cachedRepository = await this.getRepository(params);
1042
- this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1043
- }
1044
- return this.cachedRepository;
1045
- }
1046
- /**
1047
1062
  * Returns the ref needed to query based on the client's current state. This
1048
1063
  * method may make a network request to fetch a ref or resolve the user's ref
1049
1064
  * thunk.
@@ -1066,79 +1081,72 @@ var Client = class {
1066
1081
  *
1067
1082
  * @returns The ref to use during a query.
1068
1083
  */
1069
- async #getResolvedRef(params) {
1070
- var _this$getRef;
1071
- if (this.#autoPreviews) {
1072
- var _this$autoPreviewsReq3, _globalThis$document;
1073
- const previewRef = require_getPreviewCookie.getPreviewCookie((((_this$autoPreviewsReq3 = this.#autoPreviewsRequest) === null || _this$autoPreviewsReq3 === void 0 ? void 0 : _this$autoPreviewsReq3.headers) ? "get" in this.#autoPreviewsRequest.headers ? this.#autoPreviewsRequest.headers.get("cookie") : this.#autoPreviewsRequest.headers.cookie : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.cookie) ?? "");
1084
+ async getResolvedRefString(params) {
1085
+ if (this.refState.autoPreviewsEnabled) {
1086
+ var _this$refState$httpRe3, _globalThis$document;
1087
+ let previewRef;
1088
+ let cookieJar;
1089
+ if ((_this$refState$httpRe3 = this.refState.httpRequest) === null || _this$refState$httpRe3 === void 0 ? void 0 : _this$refState$httpRe3.headers) {
1090
+ if ("get" in this.refState.httpRequest.headers && typeof this.refState.httpRequest.headers.get === "function") cookieJar = this.refState.httpRequest.headers.get("cookie");
1091
+ else if ("cookie" in this.refState.httpRequest.headers) cookieJar = this.refState.httpRequest.headers.cookie;
1092
+ } else if ((_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.cookie) cookieJar = globalThis.document.cookie;
1093
+ if (cookieJar) previewRef = require_getPreviewCookie.getPreviewCookie(cookieJar);
1074
1094
  if (previewRef) return previewRef;
1075
1095
  }
1076
- const ref = await ((_this$getRef = this.#getRef) === null || _this$getRef === void 0 ? void 0 : _this$getRef.call(this, params));
1077
- if (ref) return ref;
1078
- return (await this.getMasterRef(params)).ref;
1096
+ const repository = await this.getRepository(params);
1097
+ const refModeType = this.refState.mode;
1098
+ if (refModeType === RefStateMode.ReleaseID) return require_findRefByID.findRefByID(repository.refs, this.refState.releaseID).ref;
1099
+ else if (refModeType === RefStateMode.ReleaseLabel) return require_findRefByLabel.findRefByLabel(repository.refs, this.refState.releaseLabel).ref;
1100
+ else if (refModeType === RefStateMode.Manual) {
1101
+ const res = await require_castThunk.castThunk(this.refState.ref)();
1102
+ if (typeof res === "string") return res;
1103
+ }
1104
+ return require_findMasterRef.findMasterRef(repository.refs).ref;
1079
1105
  }
1080
- /**
1081
- * The private implementation of `this.get`. It returns the API response and
1082
- * the URL used to make the request. The URL is sometimes used in the public
1083
- * method to include in thrown errors.
1084
- *
1085
- * This method retries requests that throw `RefNotFoundError` or
1086
- * `RefExpiredError`. It contains special logic to retry with the latest
1087
- * master ref, provided in the API's error message.
1088
- *
1089
- * @typeParam TDocument - Type of Prismic documents returned.
1090
- *
1091
- * @param params - Parameters to filter, sort, and paginate results.
1092
- *
1093
- * @returns An object containing the paginated response containing the result
1094
- * of the query and the URL used to make the API request.
1095
- */
1096
- async _get(params, attemptCount = 0) {
1106
+ async #internalGet(params, attempt = 1) {
1097
1107
  const url = await this.buildQueryURL(params);
1108
+ const response = await this.#request(new URL(url), params);
1109
+ if (response.ok) return response;
1098
1110
  try {
1099
- const response = await this.#request(new URL(url), params);
1100
- switch (response.status) {
1101
- case 200: try {
1102
- return {
1103
- data: await response.clone().json(),
1104
- url
1105
- };
1106
- } catch {
1107
- throw new require_PrismicError.PrismicError(void 0, url, await response.text());
1108
- }
1109
- case 400: {
1110
- const json = await response.json();
1111
- throw new require_ParsingError.ParsingError(json.message, url, json);
1112
- }
1113
- case 401: {
1114
- const json = await response.json();
1115
- throw new require_ForbiddenError.ForbiddenError(json.message, url, json);
1116
- }
1117
- case 404: {
1118
- const json = await response.json();
1119
- switch (json.type) {
1120
- case "api_notfound_error": throw new require_RefNotFoundError.RefNotFoundError(json.message, url, json);
1121
- case "api_security_error": if (/preview token.*expired/i.test(json.message)) throw new require_PreviewTokenExpired.PreviewTokenExpiredError(json.message, url, json);
1122
- default: throw new require_NotFoundError.NotFoundError(json.message, url, json);
1123
- }
1124
- }
1125
- case 410: {
1126
- const json = await response.json();
1127
- throw new require_RefExpiredError.RefExpiredError(json.message, url, json);
1111
+ return await this.#throwContentAPIError(response, url);
1112
+ } catch (error) {
1113
+ if ((error instanceof require_RefNotFoundError.RefNotFoundError || error instanceof require_RefExpiredError.RefExpiredError) && attempt < MAX_INVALID_REF_RETRY_ATTEMPTS) {
1114
+ var _error$message$match;
1115
+ if (!(params === null || params === void 0 ? void 0 : params.ref)) this.#cachedRepository = void 0;
1116
+ const masterRef = (_error$message$match = error.message.match(/master ref is: (?<ref>.*)$/i)) === null || _error$message$match === void 0 || (_error$message$match = _error$message$match.groups) === null || _error$message$match === void 0 ? void 0 : _error$message$match.ref;
1117
+ if (!masterRef) throw error;
1118
+ require_throttledLog.throttledLog(`[@prismicio/client] The ref (${new URL(url).searchParams.get("ref")}) was ${error instanceof require_RefNotFoundError.RefNotFoundError ? "invalid" : "expired"}. Now retrying with the latest master ref (${masterRef}). If you were previewing content, the response will not include draft content.`, { level: "warn" });
1119
+ return await this.#internalGet({
1120
+ ...params,
1121
+ ref: masterRef
1122
+ }, attempt + 1);
1123
+ }
1124
+ throw error;
1125
+ }
1126
+ }
1127
+ async #throwContentAPIError(response, url) {
1128
+ switch (response.status) {
1129
+ case 400: {
1130
+ const json = await response.clone().json();
1131
+ throw new require_ParsingError.ParsingError(json.message, url, json);
1132
+ }
1133
+ case 401: {
1134
+ const json = await response.clone().json();
1135
+ throw new require_ForbiddenError.ForbiddenError(json.message, url, json);
1136
+ }
1137
+ case 404: {
1138
+ const json = await response.clone().json();
1139
+ switch (json.type) {
1140
+ case "api_notfound_error": throw new require_RefNotFoundError.RefNotFoundError(json.message, url, json);
1141
+ case "api_security_error": if (/preview token.*expired/i.test(json.message)) throw new require_PreviewTokenExpired.PreviewTokenExpiredError(json.message, url, json);
1142
+ default: throw new require_NotFoundError.NotFoundError(json.message, url, json);
1128
1143
  }
1129
- default: throw new require_PrismicError.PrismicError(void 0, url, await response.text());
1130
1144
  }
1131
- } catch (error) {
1132
- var _error$message$match;
1133
- if (!(error instanceof require_RefNotFoundError.RefNotFoundError || error instanceof require_RefExpiredError.RefExpiredError) || attemptCount >= MAX_INVALID_REF_RETRY_ATTEMPTS - 1) throw error;
1134
- if (!(params === null || params === void 0 ? void 0 : params.ref)) this.cachedRepository = void 0;
1135
- const masterRef = (_error$message$match = error.message.match(/Master ref is: (?<ref>.*)$/)) === null || _error$message$match === void 0 || (_error$message$match = _error$message$match.groups) === null || _error$message$match === void 0 ? void 0 : _error$message$match.ref;
1136
- if (!masterRef) throw error;
1137
- require_throttledLog.throttledLog(`[@prismicio/client] The ref (${new URL(url).searchParams.get("ref")}) was ${error instanceof require_RefNotFoundError.RefNotFoundError ? "invalid" : "expired"}. Now retrying with the latest master ref (${masterRef}). If you were previewing content, the response will not include draft content.`, { level: "warn" });
1138
- return await this._get({
1139
- ...params,
1140
- ref: masterRef
1141
- }, attemptCount + 1);
1145
+ case 410: {
1146
+ const json = await response.clone().json();
1147
+ throw new require_RefExpiredError.RefExpiredError(json.message, url, json);
1148
+ }
1149
+ default: throw new require_PrismicError.PrismicError(void 0, url, await response.text());
1142
1150
  }
1143
1151
  }
1144
1152
  /**