@prismicio/client 7.20.0-alpha.0 → 7.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/Client.cjs +111 -95
  2. package/dist/Client.cjs.map +1 -1
  3. package/dist/Client.d.ts +66 -27
  4. package/dist/Client.js +111 -95
  5. package/dist/Client.js.map +1 -1
  6. package/dist/WriteClient.cjs +156 -101
  7. package/dist/WriteClient.cjs.map +1 -1
  8. package/dist/WriteClient.d.ts +2 -26
  9. package/dist/WriteClient.js +156 -101
  10. package/dist/WriteClient.js.map +1 -1
  11. package/dist/errors/InvalidDataError.cjs +7 -0
  12. package/dist/errors/InvalidDataError.cjs.map +1 -0
  13. package/dist/errors/InvalidDataError.d.ts +3 -0
  14. package/dist/errors/InvalidDataError.js +7 -0
  15. package/dist/errors/InvalidDataError.js.map +1 -0
  16. package/dist/errors/ParsingError.cjs.map +1 -1
  17. package/dist/errors/ParsingError.d.ts +6 -4
  18. package/dist/errors/ParsingError.js.map +1 -1
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/request.cjs +43 -0
  23. package/dist/lib/request.cjs.map +1 -0
  24. package/dist/lib/request.d.ts +73 -0
  25. package/dist/lib/request.js +43 -0
  26. package/dist/lib/request.js.map +1 -0
  27. package/dist/package.json.cjs +3 -1
  28. package/dist/package.json.cjs.map +1 -1
  29. package/dist/package.json.js +3 -1
  30. package/dist/package.json.js.map +1 -1
  31. package/dist/types/{integration.d.ts → api/integration.d.ts} +1 -1
  32. package/package.json +1 -1
  33. package/src/Client.ts +201 -171
  34. package/src/WriteClient.ts +220 -157
  35. package/src/errors/InvalidDataError.ts +5 -0
  36. package/src/errors/ParsingError.ts +6 -4
  37. package/src/index.ts +13 -11
  38. package/src/lib/request.ts +166 -0
  39. package/src/types/{integration.ts → api/integration.ts} +1 -1
  40. package/dist/BaseClient.cjs +0 -108
  41. package/dist/BaseClient.cjs.map +0 -1
  42. package/dist/BaseClient.d.ts +0 -152
  43. package/dist/BaseClient.js +0 -108
  44. package/dist/BaseClient.js.map +0 -1
  45. package/src/BaseClient.ts +0 -330
package/dist/Client.js CHANGED
@@ -8,7 +8,8 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot
8
8
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
9
  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);
10
10
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
- var _repositoryName;
11
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
12
+ var _repositoryName, _Client_instances, request_fn;
12
13
  import { appendFilters } from "./lib/appendFilters.js";
13
14
  import { castThunk } from "./lib/castThunk.js";
14
15
  import { devMsg } from "./lib/devMsg.js";
@@ -18,6 +19,7 @@ import { findRefByID } from "./lib/findRefByID.js";
18
19
  import { findRefByLabel } from "./lib/findRefByLabel.js";
19
20
  import { getPreviewCookie } from "./lib/getPreviewCookie.js";
20
21
  import { minifyGraphQLQuery } from "./lib/minifyGraphQLQuery.js";
22
+ import { request } from "./lib/request.js";
21
23
  import { someTagsFilter } from "./lib/someTagsFilter.js";
22
24
  import { throttledLog } from "./lib/throttledLog.js";
23
25
  import { typeFilter } from "./lib/typeFilter.js";
@@ -30,7 +32,6 @@ import { RefExpiredError } from "./errors/RefExpiredError.js";
30
32
  import { RefNotFoundError } from "./errors/RefNotFoundError.js";
31
33
  import { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError.js";
32
34
  import { asLink } from "./helpers/asLink.js";
33
- import { BaseClient } from "./BaseClient.js";
34
35
  import { buildQueryURL } from "./buildQueryURL.js";
35
36
  import { filter } from "./filter.js";
36
37
  import { getRepositoryEndpoint } from "./getRepositoryEndpoint.js";
@@ -39,8 +40,7 @@ import { isRepositoryEndpoint } from "./isRepositoryEndpoint.js";
39
40
  const MAX_PAGE_SIZE = 100;
40
41
  const REPOSITORY_CACHE_TTL = 5e3;
41
42
  const GET_ALL_QUERY_DELAY = 500;
42
- const DEFUALT_RETRY_AFTER_MS = 1e3;
43
- const MAX_INVALID_REF_RETRY_ATTEMPS = 3;
43
+ const MAX_INVALID_REF_RETRY_ATTEMPTS = 3;
44
44
  var RefStateMode;
45
45
  (function(RefStateMode2) {
46
46
  RefStateMode2["Master"] = "Master";
@@ -48,7 +48,7 @@ var RefStateMode;
48
48
  RefStateMode2["ReleaseLabel"] = "ReleaseLabel";
49
49
  RefStateMode2["Manual"] = "Manual";
50
50
  })(RefStateMode || (RefStateMode = {}));
51
- class Client extends BaseClient {
51
+ class Client {
52
52
  /**
53
53
  * Creates a Prismic client that can be used to query a repository.
54
54
  *
@@ -64,7 +64,14 @@ class Client extends BaseClient {
64
64
  * @returns A client that can query content from the repository.
65
65
  */
66
66
  constructor(repositoryNameOrEndpoint, options = {}) {
67
- super(options);
67
+ __privateAdd(this, _Client_instances);
68
+ /**
69
+ * The function used to make network requests to the Prismic REST API. In
70
+ * environments where a global `fetch` function does not exist, such as
71
+ * Node.js, this function must be provided.
72
+ */
73
+ __publicField(this, "fetchFn");
74
+ __publicField(this, "fetchOptions");
68
75
  __privateAdd(this, _repositoryName);
69
76
  /**
70
77
  * The Prismic REST API V2 endpoint for the repository (use
@@ -115,6 +122,17 @@ class Client extends BaseClient {
115
122
  * Timestamp at which the cached repository data is considered stale.
116
123
  */
117
124
  __publicField(this, "cachedRepositoryExpiration", 0);
125
+ this.fetchOptions = options.fetchOptions;
126
+ if (typeof options.fetch === "function") {
127
+ this.fetchFn = options.fetch;
128
+ } else if (typeof globalThis.fetch === "function") {
129
+ this.fetchFn = globalThis.fetch;
130
+ } else {
131
+ 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);
132
+ }
133
+ if (this.fetchFn === globalThis.fetch) {
134
+ this.fetchFn = this.fetchFn.bind(globalThis);
135
+ }
118
136
  if ((options.documentAPIEndpoint || isRepositoryEndpoint(repositoryNameOrEndpoint)) && process.env.NODE_ENV === "development") {
119
137
  const documentAPIEndpoint = options.documentAPIEndpoint || repositoryNameOrEndpoint;
120
138
  if (/\.prismic\.io\/(?!api\/v2\/?)/i.test(documentAPIEndpoint)) {
@@ -733,7 +751,22 @@ class Client extends BaseClient {
733
751
  if (this.accessToken) {
734
752
  url.searchParams.set("access_token", this.accessToken);
735
753
  }
736
- return await this.fetch(url.toString(), params);
754
+ const response = await __privateMethod(this, _Client_instances, request_fn).call(this, url, params);
755
+ switch (response.status) {
756
+ case 200: {
757
+ return await response.json();
758
+ }
759
+ case 401: {
760
+ const json = await response.json();
761
+ throw new ForbiddenError(json.error, url.toString(), json);
762
+ }
763
+ case 404: {
764
+ throw new RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url.toString(), void 0);
765
+ }
766
+ default: {
767
+ throw new PrismicError(void 0, url.toString(), await response.text());
768
+ }
769
+ }
737
770
  }
738
771
  /**
739
772
  * Returns a list of all refs for the Prismic repository.
@@ -818,17 +851,20 @@ class Client extends BaseClient {
818
851
  * @returns A list of all tags used in the repository.
819
852
  */
820
853
  async getTags(params) {
821
- try {
822
- const tagsForm = await this.getCachedRepositoryForm("tags", params);
823
- const url = new URL(tagsForm.action);
854
+ const cachedRepository = await this.getCachedRepository(params);
855
+ const form = cachedRepository.forms.tags;
856
+ if (form) {
857
+ const url = new URL(form.action);
824
858
  if (this.accessToken) {
825
859
  url.searchParams.set("access_token", this.accessToken);
826
860
  }
827
- return await this.fetch(url.toString(), params);
828
- } catch {
829
- const repository = await this.getRepository(params);
830
- return repository.tags;
861
+ const response = await __privateMethod(this, _Client_instances, request_fn).call(this, url, params);
862
+ if (response.ok) {
863
+ return await response.json();
864
+ }
831
865
  }
866
+ const repository = await this.getRepository(params);
867
+ return repository.tags;
832
868
  }
833
869
  /**
834
870
  * Builds a URL used to query content from the Prismic repository.
@@ -1068,29 +1104,11 @@ class Client extends BaseClient {
1068
1104
  */
1069
1105
  async getCachedRepository(params) {
1070
1106
  if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
1071
- this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1072
1107
  this.cachedRepository = await this.getRepository(params);
1108
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
1073
1109
  }
1074
1110
  return this.cachedRepository;
1075
1111
  }
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(`Form with name "${name}" could not be found`, void 0, void 0);
1091
- }
1092
- return form;
1093
- }
1094
1112
  /**
1095
1113
  * Returns the ref needed to query based on the client's current state. This
1096
1114
  * method may make a network request to fetch a ref or resolve the user's ref
@@ -1169,10 +1187,52 @@ class Client extends BaseClient {
1169
1187
  var _a, _b;
1170
1188
  const url = await this.buildQueryURL(params);
1171
1189
  try {
1172
- const data = await this.fetch(url, params);
1173
- return { data, url };
1190
+ const response = await __privateMethod(this, _Client_instances, request_fn).call(this, new URL(url), params);
1191
+ switch (response.status) {
1192
+ case 200: {
1193
+ try {
1194
+ return {
1195
+ data: await response.clone().json(),
1196
+ url
1197
+ };
1198
+ } catch {
1199
+ throw new PrismicError(void 0, url, await response.text());
1200
+ }
1201
+ }
1202
+ case 400: {
1203
+ const json = await response.json();
1204
+ throw new ParsingError(json.message, url, json);
1205
+ }
1206
+ case 401: {
1207
+ const json = await response.json();
1208
+ throw new ForbiddenError(json.message, url, json);
1209
+ }
1210
+ case 404: {
1211
+ const json = await response.json();
1212
+ switch (json.type) {
1213
+ case "api_notfound_error": {
1214
+ throw new RefNotFoundError(json.message, url, json);
1215
+ }
1216
+ case "api_security_error": {
1217
+ if (/preview token.*expired/i.test(json.message)) {
1218
+ throw new PreviewTokenExpiredError(json.message, url, json);
1219
+ }
1220
+ }
1221
+ default: {
1222
+ throw new NotFoundError(json.message, url, json);
1223
+ }
1224
+ }
1225
+ }
1226
+ case 410: {
1227
+ const json = await response.json();
1228
+ throw new RefExpiredError(json.message, url, json);
1229
+ }
1230
+ default: {
1231
+ throw new PrismicError(void 0, url, await response.text());
1232
+ }
1233
+ }
1174
1234
  } catch (error) {
1175
- if (!(error instanceof RefNotFoundError || error instanceof RefExpiredError) || attemptCount >= MAX_INVALID_REF_RETRY_ATTEMPS - 1) {
1235
+ if (!(error instanceof RefNotFoundError || error instanceof RefExpiredError) || attemptCount >= MAX_INVALID_REF_RETRY_ATTEMPTS - 1) {
1176
1236
  throw error;
1177
1237
  }
1178
1238
  if (!(params == null ? void 0 : params.ref)) {
@@ -1188,68 +1248,24 @@ class Client extends BaseClient {
1188
1248
  return await this._get({ ...params, ref: masterRef }, attemptCount + 1);
1189
1249
  }
1190
1250
  }
1191
- /**
1192
- * Performs a network request using the configured `fetch` function. It
1193
- * assumes all successful responses will have a JSON content type. It also
1194
- * normalizes unsuccessful network requests.
1195
- *
1196
- * @typeParam T - The JSON response.
1197
- *
1198
- * @param url - URL to the resource to fetch.
1199
- * @param params - Prismic REST API parameters for the network request.
1200
- *
1201
- * @returns The JSON response from the network request.
1202
- */
1203
- async fetch(url, params = {}) {
1204
- const res = await super.fetch(url, params);
1205
- if (res.status !== 404 && res.status !== 429 && res.json == null) {
1206
- throw new PrismicError(void 0, url, res.json || res.text);
1207
- }
1208
- switch (res.status) {
1209
- case 200:
1210
- case 201: {
1211
- return res.json;
1212
- }
1213
- case 400: {
1214
- throw new ParsingError(res.json.message, url, res.json);
1215
- }
1216
- case 401:
1217
- case 403: {
1218
- throw new ForbiddenError(res.json.error || res.json.message, url, res.json);
1219
- }
1220
- case 404: {
1221
- if (res.json === void 0) {
1222
- throw new RepositoryNotFoundError(`Prismic repository not found. Check that "${this.documentAPIEndpoint}" is pointing to the correct repository.`, url, url.startsWith(this.documentAPIEndpoint) ? void 0 : res.text);
1223
- }
1224
- if (res.json.type === "api_notfound_error") {
1225
- throw new RefNotFoundError(res.json.message, url, res.json);
1226
- }
1227
- if (res.json.type === "api_security_error" && /preview token.*expired/i.test(res.json.message)) {
1228
- throw new PreviewTokenExpiredError(res.json.message, url, res.json);
1229
- }
1230
- throw new NotFoundError(res.json.message, url, res.json);
1231
- }
1232
- case 410: {
1233
- throw new RefExpiredError(res.json.message, url, res.json);
1234
- }
1235
- case 429: {
1236
- const parsedRetryAfter = Number(res.headers.get("retry-after"));
1237
- const delay = Number.isNaN(parsedRetryAfter) ? DEFUALT_RETRY_AFTER_MS : parsedRetryAfter;
1238
- return await new Promise((resolve, reject) => {
1239
- setTimeout(async () => {
1240
- try {
1241
- resolve(await this.fetch(url, params));
1242
- } catch (error) {
1243
- reject(error);
1244
- }
1245
- }, delay);
1246
- });
1247
- }
1248
- }
1249
- throw new PrismicError(void 0, url, res.json);
1251
+ _buildRequestInit(params) {
1252
+ var _a, _b, _c, _d;
1253
+ return {
1254
+ ...this.fetchOptions,
1255
+ ...params == null ? void 0 : params.fetchOptions,
1256
+ headers: {
1257
+ ...(_a = this.fetchOptions) == null ? void 0 : _a.headers,
1258
+ ...(_b = params == null ? void 0 : params.fetchOptions) == null ? void 0 : _b.headers
1259
+ },
1260
+ signal: ((_c = params == null ? void 0 : params.fetchOptions) == null ? void 0 : _c.signal) || (params == null ? void 0 : params.signal) || ((_d = this.fetchOptions) == null ? void 0 : _d.signal)
1261
+ };
1250
1262
  }
1251
1263
  }
1252
1264
  _repositoryName = new WeakMap();
1265
+ _Client_instances = new WeakSet();
1266
+ request_fn = async function(url, params) {
1267
+ return await request(url, this._buildRequestInit(params), this.fetchFn);
1268
+ };
1253
1269
  export {
1254
1270
  Client,
1255
1271
  GET_ALL_QUERY_DELAY,