@prismicio/client 6.0.0-beta.0 → 6.0.0-beta.4

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/index.cjs CHANGED
@@ -37,12 +37,8 @@ const castOrderingToString = (ordering) => typeof ordering === "string" ? orderi
37
37
  ].filter(Boolean).join(" ");
38
38
  const buildQueryURL = (endpoint, args) => {
39
39
  var _a;
40
- const { ref, integrationFieldsRef, predicates, ...params } = args;
40
+ const { predicates, ...params } = args;
41
41
  const url = new URL(`documents/search`, `${endpoint}/`);
42
- url.searchParams.set("ref", ref);
43
- if (integrationFieldsRef) {
44
- url.searchParams.set("integrationFieldsRef", integrationFieldsRef);
45
- }
46
42
  if (predicates) {
47
43
  for (const predicate of castArray(predicates)) {
48
44
  url.searchParams.append("q", `[${predicate}]`);
@@ -69,13 +65,46 @@ const buildQueryURL = (endpoint, args) => {
69
65
  return url.toString();
70
66
  };
71
67
 
72
- const appendPredicates = (...predicates) => (objWithPredicates = {}) => ({
73
- ...objWithPredicates,
74
- predicates: [objWithPredicates.predicates || [], ...predicates].flat()
75
- });
68
+ const appendPredicates = (objWithPredicates = {}, predicates) => {
69
+ return {
70
+ ...objWithPredicates,
71
+ predicates: [
72
+ ...objWithPredicates.predicates || [],
73
+ ...castArray(predicates)
74
+ ]
75
+ };
76
+ };
76
77
 
77
78
  const castThunk = (a) => typeof a === "function" ? a : () => a;
78
79
 
80
+ class PrismicError extends Error {
81
+ constructor(message = "An invalid API response was returned", url, response) {
82
+ super(message);
83
+ this.url = url;
84
+ this.response = response;
85
+ }
86
+ }
87
+
88
+ const findRef = (refs, predicate) => {
89
+ const ref = refs.find((ref2) => predicate(ref2));
90
+ if (!ref) {
91
+ throw new PrismicError("Ref could not be found.", void 0, void 0);
92
+ }
93
+ return ref;
94
+ };
95
+
96
+ const findMasterRef = (refs) => {
97
+ return findRef(refs, (ref) => ref.isMasterRef);
98
+ };
99
+
100
+ const findRefByID = (refs, id) => {
101
+ return findRef(refs, (ref) => ref.id === id);
102
+ };
103
+
104
+ const findRefByLabel = (refs, label) => {
105
+ return findRef(refs, (ref) => ref.label === label);
106
+ };
107
+
79
108
  const readValue = (value) => {
80
109
  return value.replace(/%3B/g, ";");
81
110
  };
@@ -93,47 +122,12 @@ const parse = (cookieString) => {
93
122
  const getAll = (cookieStore) => parse(cookieStore);
94
123
  const getCookie = (name, cookieStore) => getAll(cookieStore)[name];
95
124
 
96
- const isForbiddenErrorAPIResponse = (input) => {
97
- return typeof input === "object" && input !== null && ("error" in input || "message" in input) && "oauth_initiate" in input && "oauth_token" in input;
98
- };
99
- class ForbiddenError extends Error {
100
- constructor(message, args) {
101
- super(message);
102
- this.url = args.url;
103
- this.oauth_initiate = args.response.oauth_initiate;
104
- this.oauth_token = args.response.oauth_token;
105
- }
125
+ class ForbiddenError extends PrismicError {
106
126
  }
107
127
 
108
- const isParsingErrorAPIResponse = (input) => {
109
- return typeof input === "object" && input !== null && "message" in input && "type" in input;
110
- };
111
- class ParsingError extends Error {
112
- constructor(message, args) {
113
- super(message);
114
- this.url = args.url;
115
- this.line = args.response.line;
116
- this.column = args.response.column;
117
- this.id = args.response.id;
118
- this.location = args.response.location;
119
- }
128
+ class ParsingError extends PrismicError {
120
129
  }
121
130
 
122
- class PrismicError extends Error {
123
- constructor(message, args) {
124
- super(message || "An invalid API response was returned");
125
- this.url = args.url;
126
- this.response = args.response;
127
- }
128
- }
129
-
130
- const preview = "io.prismic.preview";
131
-
132
- const cookie = /*#__PURE__*/Object.freeze({
133
- __proto__: null,
134
- preview: preview
135
- });
136
-
137
131
  const formatValue = (value) => {
138
132
  if (Array.isArray(value)) {
139
133
  return `[${value.map(formatValue).join(", ")}]`;
@@ -168,115 +162,69 @@ const argsPredicate = (name) => {
168
162
  };
169
163
  return fn;
170
164
  };
171
- const at = pathWithArgsPredicate("at");
172
- const not = pathWithArgsPredicate("not");
173
- const any = pathWithArgsPredicate("any");
174
- const _in = pathWithArgsPredicate("in");
175
- const fulltext = pathWithArgsPredicate("fulltext");
176
- const has = pathPredicate("has");
177
- const missing = pathPredicate("missing");
178
- const similar = argsPredicate("similar");
179
- const geopointNear = pathWithArgsPredicate("geopoint.near");
180
- const numberLessThan = pathWithArgsPredicate("number.lt");
181
- const numberGreaterThan = pathWithArgsPredicate("number.gt");
182
- const numberInRange = pathWithArgsPredicate("number.inRange");
183
- const dateAfter = pathWithArgsPredicate("date.after");
184
- const dateBefore = pathWithArgsPredicate("date.before");
185
- const dateBetween = pathWithArgsPredicate("date.between");
186
- const dateDayOfMonth = pathWithArgsPredicate("date.day-of-month");
187
- const dateDayOfMonthAfter = pathWithArgsPredicate("date.day-of-month-after");
188
- const dateDayOfMonthBefore = pathWithArgsPredicate("date.day-of-month-before");
189
- const dateDayOfWeek = pathWithArgsPredicate("date.day-of-week");
190
- const dateDayOfWeekAfter = pathWithArgsPredicate("date.day-of-week-after");
191
- const dateDayOfWeekBefore = pathWithArgsPredicate("date.day-of-week-before");
192
- const dateMonth = pathWithArgsPredicate("date.month");
193
- const dateMonthAfter = pathWithArgsPredicate("date.month-after");
194
- const dateMonthBefore = pathWithArgsPredicate("date.month-before");
195
- const dateYear = pathWithArgsPredicate("date.year");
196
- const dateHour = pathWithArgsPredicate("date.hour");
197
- const dateHourAfter = pathWithArgsPredicate("date.hour-after");
198
- const dateHourBefore = pathWithArgsPredicate("date.hour-before");
165
+ const predicate = {
166
+ at: pathWithArgsPredicate("at"),
167
+ not: pathWithArgsPredicate("not"),
168
+ any: pathWithArgsPredicate("any"),
169
+ in: pathWithArgsPredicate("in"),
170
+ fulltext: pathWithArgsPredicate("fulltext"),
171
+ has: pathPredicate("has"),
172
+ missing: pathPredicate("missing"),
173
+ similar: argsPredicate("similar"),
174
+ geopointNear: pathWithArgsPredicate("geopoint.near"),
175
+ numberLessThan: pathWithArgsPredicate("number.lt"),
176
+ numberGreaterThan: pathWithArgsPredicate("number.gt"),
177
+ numberInRange: pathWithArgsPredicate("number.inRange"),
178
+ dateAfter: pathWithArgsPredicate("date.after"),
179
+ dateBefore: pathWithArgsPredicate("date.before"),
180
+ dateBetween: pathWithArgsPredicate("date.between"),
181
+ dateDayOfMonth: pathWithArgsPredicate("date.day-of-month"),
182
+ dateDayOfMonthAfter: pathWithArgsPredicate("date.day-of-month-after"),
183
+ dateDayOfMonthBefore: pathWithArgsPredicate("date.day-of-month-before"),
184
+ dateDayOfWeek: pathWithArgsPredicate("date.day-of-week"),
185
+ dateDayOfWeekAfter: pathWithArgsPredicate("date.day-of-week-after"),
186
+ dateDayOfWeekBefore: pathWithArgsPredicate("date.day-of-week-before"),
187
+ dateMonth: pathWithArgsPredicate("date.month"),
188
+ dateMonthAfter: pathWithArgsPredicate("date.month-after"),
189
+ dateMonthBefore: pathWithArgsPredicate("date.month-before"),
190
+ dateYear: pathWithArgsPredicate("date.year"),
191
+ dateHour: pathWithArgsPredicate("date.hour"),
192
+ dateHourAfter: pathWithArgsPredicate("date.hour-after"),
193
+ dateHourBefore: pathWithArgsPredicate("date.hour-before")
194
+ };
199
195
 
200
- const predicate = /*#__PURE__*/Object.freeze({
196
+ const preview = "io.prismic.preview";
197
+
198
+ const cookie = /*#__PURE__*/Object.freeze({
201
199
  __proto__: null,
202
- at: at,
203
- not: not,
204
- any: any,
205
- 'in': _in,
206
- fulltext: fulltext,
207
- has: has,
208
- missing: missing,
209
- similar: similar,
210
- geopointNear: geopointNear,
211
- numberLessThan: numberLessThan,
212
- numberGreaterThan: numberGreaterThan,
213
- numberInRange: numberInRange,
214
- dateAfter: dateAfter,
215
- dateBefore: dateBefore,
216
- dateBetween: dateBetween,
217
- dateDayOfMonth: dateDayOfMonth,
218
- dateDayOfMonthAfter: dateDayOfMonthAfter,
219
- dateDayOfMonthBefore: dateDayOfMonthBefore,
220
- dateDayOfWeek: dateDayOfWeek,
221
- dateDayOfWeekAfter: dateDayOfWeekAfter,
222
- dateDayOfWeekBefore: dateDayOfWeekBefore,
223
- dateMonth: dateMonth,
224
- dateMonthAfter: dateMonthAfter,
225
- dateMonthBefore: dateMonthBefore,
226
- dateYear: dateYear,
227
- dateHour: dateHour,
228
- dateHourAfter: dateHourAfter,
229
- dateHourBefore: dateHourBefore
200
+ preview: preview
230
201
  });
231
202
 
232
- const createSimpleTTLCache = () => {
233
- const cache = new Map();
234
- return {
235
- get(key) {
236
- const cacheValue = cache.get(key);
237
- if (cacheValue) {
238
- if (new Date().getTime() < cacheValue.expiresAt) {
239
- return cacheValue.value;
240
- }
241
- }
242
- },
243
- set(key, value, ttl) {
244
- cache.set(key, { expiresAt: new Date().getTime() + ttl, value });
245
- }
246
- };
247
- };
248
203
  const MAX_PAGE_SIZE = 100;
249
204
  const REPOSITORY_CACHE_TTL = 5e3;
250
- var RefStateType;
251
- (function(RefStateType2) {
252
- RefStateType2[RefStateType2["Master"] = 0] = "Master";
253
- RefStateType2[RefStateType2["ReleaseByID"] = 1] = "ReleaseByID";
254
- RefStateType2[RefStateType2["ReleaseByLabel"] = 2] = "ReleaseByLabel";
255
- RefStateType2[RefStateType2["Manual"] = 3] = "Manual";
256
- })(RefStateType || (RefStateType = {}));
257
- const typePredicate = (documentType) => at("document.type", documentType);
258
- const tagsPredicate = (tags) => at("document.tags", tags);
259
- const findRef = (refs, predicate2) => {
260
- const ref = refs.find((ref2) => predicate2(ref2));
261
- if (!ref) {
262
- throw new Error("Ref could not be found.");
263
- }
264
- return ref;
265
- };
205
+ const GET_ALL_QUERY_DELAY = 500;
206
+ var RefStateMode;
207
+ (function(RefStateMode2) {
208
+ RefStateMode2["Master"] = "Master";
209
+ RefStateMode2["ReleaseID"] = "ReleaseID";
210
+ RefStateMode2["ReleaseLabel"] = "ReleaseLabel";
211
+ RefStateMode2["Manual"] = "Manual";
212
+ })(RefStateMode || (RefStateMode = {}));
213
+ const typePredicate = (documentType) => predicate.at("document.type", documentType);
214
+ const everyTagPredicate = (tags) => predicate.at("document.tags", tags);
215
+ const someTagsPredicate = (tags) => predicate.any("document.tags", tags);
266
216
  const createClient = (...args) => new Client(...args);
267
217
  class Client {
268
218
  constructor(endpoint, options = {}) {
269
- this.query = this.get.bind(this);
219
+ this.refState = {
220
+ mode: RefStateMode.Master,
221
+ autoPreviewsEnabled: true
222
+ };
223
+ this.cachedRepositoryExpiration = 0;
270
224
  this.endpoint = endpoint;
271
225
  this.accessToken = options.accessToken;
272
- this.integrationFieldsRef = options.integrationFieldsRef;
273
226
  this.routes = options.routes;
274
227
  this.defaultParams = options.defaultParams;
275
- this.internalCache = createSimpleTTLCache();
276
- this.refMode = {
277
- type: 0,
278
- autoPreviewsEnabled: true
279
- };
280
228
  if (options.ref) {
281
229
  this.queryContentFromRef(options.ref);
282
230
  }
@@ -285,85 +233,110 @@ class Client {
285
233
  } else if (typeof globalThis.fetch === "function") {
286
234
  this.fetchFn = globalThis.fetch;
287
235
  } else {
288
- throw new Error("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.");
236
+ 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);
289
237
  }
290
238
  if (this.fetchFn === globalThis.fetch) {
291
239
  this.fetchFn = this.fetchFn.bind(globalThis);
292
240
  }
293
241
  }
294
242
  enableAutoPreviews() {
295
- this.refMode.autoPreviewsEnabled = true;
243
+ this.refState.autoPreviewsEnabled = true;
296
244
  }
297
245
  enableAutoPreviewsFromReq(req) {
298
- this.refMode.httpRequest = req;
299
- this.refMode.autoPreviewsEnabled = true;
246
+ this.refState.httpRequest = req;
247
+ this.refState.autoPreviewsEnabled = true;
300
248
  }
301
249
  disableAutoPreviews() {
302
- this.refMode.autoPreviewsEnabled = false;
250
+ this.refState.autoPreviewsEnabled = false;
251
+ }
252
+ async query(predicates, params) {
253
+ const url = await this.buildQueryURL({ ...params, predicates });
254
+ return await this.fetch(url, params);
303
255
  }
304
256
  async get(params) {
305
257
  const url = await this.buildQueryURL(params);
306
- return await this.fetch(url);
258
+ return await this.fetch(url, params);
307
259
  }
308
260
  async getFirst(params) {
309
- const result = await this.get(params);
261
+ const url = await this.buildQueryURL(params);
262
+ const result = await this.fetch(url, params);
310
263
  const firstResult = result.results[0];
311
264
  if (firstResult) {
312
265
  return firstResult;
313
266
  }
314
- throw new Error("No documents were returned");
267
+ throw new PrismicError("No documents were returned", url, void 0);
315
268
  }
316
- async getAll(params = {}) {
269
+ async dangerouslyGetAll(params = {}) {
317
270
  const { limit = Infinity, ...actualParams } = params;
318
- const resolvedParams = { pageSize: MAX_PAGE_SIZE, ...actualParams };
319
- const result = await this.get(resolvedParams);
320
- let page = result.page;
321
- let documents = result.results;
322
- while (page < result.total_pages && documents.length < limit) {
323
- page += 1;
324
- const result2 = await this.get({ ...resolvedParams, page });
325
- documents = [...documents, ...result2.results];
271
+ const resolvedParams = {
272
+ ...actualParams,
273
+ pageSize: actualParams.pageSize || MAX_PAGE_SIZE
274
+ };
275
+ const documents = [];
276
+ let latestResult;
277
+ while ((!latestResult || latestResult.next_page) && documents.length < limit) {
278
+ const page = latestResult ? latestResult.page + 1 : void 0;
279
+ latestResult = await this.get({ ...resolvedParams, page });
280
+ documents.push(...latestResult.results);
281
+ if (latestResult.next_page) {
282
+ await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY));
283
+ }
326
284
  }
327
285
  return documents.slice(0, limit);
328
286
  }
329
287
  async getByID(id, params) {
330
- return await this.getFirst(appendPredicates(at("document.id", id))(params));
288
+ return await this.getFirst(appendPredicates(params, predicate.at("document.id", id)));
331
289
  }
332
290
  async getByIDs(ids, params) {
333
- return await this.get(appendPredicates(_in("document.id", ids))(params));
291
+ return await this.get(appendPredicates(params, predicate.in("document.id", ids)));
334
292
  }
335
293
  async getAllByIDs(ids, params) {
336
- return await this.getAll(appendPredicates(_in("document.id", ids))(params));
294
+ return await this.dangerouslyGetAll(appendPredicates(params, predicate.in("document.id", ids)));
337
295
  }
338
296
  async getByUID(documentType, uid, params) {
339
- return await this.getFirst(appendPredicates(typePredicate(documentType), at(`my.${documentType}.uid`, uid))(params));
297
+ return await this.getFirst(appendPredicates(params, [
298
+ typePredicate(documentType),
299
+ predicate.at(`my.${documentType}.uid`, uid)
300
+ ]));
340
301
  }
341
302
  async getByUIDs(documentType, uids, params) {
342
- return await this.get(appendPredicates(typePredicate(documentType), _in(`my.${documentType}.uid`, uids))(params));
303
+ return await this.get(appendPredicates(params, [
304
+ typePredicate(documentType),
305
+ predicate.in(`my.${documentType}.uid`, uids)
306
+ ]));
343
307
  }
344
308
  async getAllByUIDs(documentType, uids, params) {
345
- return await this.getAll(appendPredicates(typePredicate(documentType), _in(`my.${documentType}.uid`, uids))(params));
309
+ return await this.dangerouslyGetAll(appendPredicates(params, [
310
+ typePredicate(documentType),
311
+ predicate.in(`my.${documentType}.uid`, uids)
312
+ ]));
346
313
  }
347
314
  async getSingle(documentType, params) {
348
- return await this.getFirst(appendPredicates(typePredicate(documentType))(params));
315
+ return await this.getFirst(appendPredicates(params, typePredicate(documentType)));
349
316
  }
350
317
  async getByType(documentType, params) {
351
- return await this.get(appendPredicates(typePredicate(documentType))(params));
318
+ return await this.get(appendPredicates(params, typePredicate(documentType)));
352
319
  }
353
320
  async getAllByType(documentType, params) {
354
- return await this.getAll(appendPredicates(typePredicate(documentType))(params));
321
+ return await this.dangerouslyGetAll(appendPredicates(params, typePredicate(documentType)));
355
322
  }
356
323
  async getByTag(tag, params) {
357
- return await this.get(appendPredicates(tagsPredicate(tag))(params));
324
+ return await this.get(appendPredicates(params, everyTagPredicate(tag)));
358
325
  }
359
326
  async getAllByTag(tag, params) {
360
- return await this.getAll(appendPredicates(tagsPredicate(tag))(params));
327
+ return await this.dangerouslyGetAll(appendPredicates(params, everyTagPredicate(tag)));
328
+ }
329
+ async getByEveryTag(tags, params) {
330
+ return await this.get(appendPredicates(params, everyTagPredicate(tags)));
331
+ }
332
+ async getAllByEveryTag(tags, params) {
333
+ return await this.dangerouslyGetAll(appendPredicates(params, everyTagPredicate(tags)));
361
334
  }
362
- async getByTags(tags, params) {
363
- return await this.get(appendPredicates(tagsPredicate(tags))(params));
335
+ async getBySomeTags(tags, params) {
336
+ return await this.get(appendPredicates(params, someTagsPredicate(tags)));
364
337
  }
365
- async getAllByTags(tags, params) {
366
- return await this.getAll(appendPredicates(tagsPredicate(tags))(params));
338
+ async getAllBySomeTags(tags, params) {
339
+ return await this.dangerouslyGetAll(appendPredicates(params, someTagsPredicate(tags)));
367
340
  }
368
341
  async getRepository() {
369
342
  const url = new URL(this.endpoint);
@@ -373,20 +346,20 @@ class Client {
373
346
  return await this.fetch(url.toString());
374
347
  }
375
348
  async getRefs() {
376
- const res = await this.getRepository();
377
- return res.refs;
349
+ const repository = await this.getRepository();
350
+ return repository.refs;
378
351
  }
379
352
  async getRefByID(id) {
380
353
  const refs = await this.getRefs();
381
- return findRef(refs, (ref) => ref.id === id);
354
+ return findRefByID(refs, id);
382
355
  }
383
356
  async getRefByLabel(label) {
384
357
  const refs = await this.getRefs();
385
- return findRef(refs, (ref) => ref.label === label);
358
+ return findRefByLabel(refs, label);
386
359
  }
387
360
  async getMasterRef() {
388
361
  const refs = await this.getRefs();
389
- return findRef(refs, (ref) => ref.isMasterRef);
362
+ return findMasterRef(refs);
390
363
  }
391
364
  async getReleases() {
392
365
  const refs = await this.getRefs();
@@ -394,36 +367,31 @@ class Client {
394
367
  }
395
368
  async getReleaseByID(id) {
396
369
  const releases = await this.getReleases();
397
- return findRef(releases, (ref) => ref.id === id);
370
+ return findRefByID(releases, id);
398
371
  }
399
372
  async getReleaseByLabel(label) {
400
373
  const releases = await this.getReleases();
401
- return findRef(releases, (ref) => ref.label === label);
374
+ return findRefByLabel(releases, label);
402
375
  }
403
376
  async getTags() {
404
377
  try {
405
378
  const tagsForm = await this.getCachedRepositoryForm("tags");
406
379
  return await this.fetch(tagsForm.action);
407
380
  } catch (e) {
408
- const res = await this.getRepository();
409
- return res.tags;
381
+ const repository = await this.getRepository();
382
+ return repository.tags;
410
383
  }
411
384
  }
412
385
  async buildQueryURL(params = {}) {
413
- const {
414
- ref = await this.getResolvedRefString(),
415
- integrationFieldsRef = await this.getResolvedIntegrationFieldsRef(),
416
- accessToken = this.accessToken,
417
- routes = this.routes,
418
- ...actualParams
419
- } = params;
386
+ const ref = params.ref || await this.getResolvedRefString();
387
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository()).integrationFieldsRef || void 0;
420
388
  return buildQueryURL(this.endpoint, {
421
389
  ...this.defaultParams,
422
- ...actualParams,
423
- accessToken,
390
+ ...params,
424
391
  ref,
425
392
  integrationFieldsRef,
426
- routes
393
+ routes: params.routes || this.routes,
394
+ accessToken: params.accessToken || this.accessToken
427
395
  });
428
396
  }
429
397
  async resolvePreviewURL(args) {
@@ -434,166 +402,121 @@ class Client {
434
402
  const searchParams = new URLSearchParams(globalThis.location.search);
435
403
  documentID = documentID || searchParams.get("documentId") || void 0;
436
404
  previewToken = previewToken || searchParams.get("token") || void 0;
437
- } else if ((_a = this.refMode.httpRequest) == null ? void 0 : _a.query) {
438
- if (typeof this.refMode.httpRequest.query.documentId === "string") {
439
- documentID = documentID || this.refMode.httpRequest.query.documentId;
440
- }
441
- if (typeof this.refMode.httpRequest.query.token === "string") {
442
- previewToken = previewToken || this.refMode.httpRequest.query.token;
443
- }
405
+ } else if ((_a = this.refState.httpRequest) == null ? void 0 : _a.query) {
406
+ documentID = documentID || this.refState.httpRequest.query.documentId;
407
+ previewToken = previewToken || this.refState.httpRequest.query.token;
444
408
  }
445
409
  if (documentID != null) {
446
410
  const document = await this.getByID(documentID, {
447
411
  ref: previewToken
448
412
  });
449
- return prismicH__namespace.asLink(prismicH__namespace.documentToLinkField(document), args.linkResolver);
413
+ return prismicH__namespace.asLink(document, args.linkResolver);
450
414
  } else {
451
415
  return args.defaultURL;
452
416
  }
453
417
  }
454
418
  queryLatestContent() {
455
- this.refMode = {
456
- ...this.refMode,
457
- type: 0
458
- };
419
+ this.refState.mode = RefStateMode.Master;
459
420
  }
460
421
  queryContentFromReleaseByID(releaseID) {
461
- this.refMode = {
462
- ...this.refMode,
463
- type: 1,
464
- payload: { releaseID }
422
+ this.refState = {
423
+ ...this.refState,
424
+ mode: RefStateMode.ReleaseID,
425
+ releaseID
465
426
  };
466
427
  }
467
428
  queryContentFromReleaseByLabel(releaseLabel) {
468
- this.refMode = {
469
- ...this.refMode,
470
- type: 2,
471
- payload: { releaseLabel }
429
+ this.refState = {
430
+ ...this.refState,
431
+ mode: RefStateMode.ReleaseLabel,
432
+ releaseLabel
472
433
  };
473
434
  }
474
435
  queryContentFromRef(ref) {
475
- this.refMode = {
476
- ...this.refMode,
477
- type: 3,
478
- payload: { refStringOrFn: ref }
436
+ this.refState = {
437
+ ...this.refState,
438
+ mode: RefStateMode.Manual,
439
+ ref
479
440
  };
480
441
  }
481
442
  async getCachedRepository() {
482
- const cacheKey = this.endpoint;
483
- const cachedRepository = this.internalCache.get(cacheKey);
484
- if (cachedRepository) {
485
- return cachedRepository;
443
+ if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
444
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
445
+ this.cachedRepository = await this.getRepository();
486
446
  }
487
- const repository = await this.getRepository();
488
- this.internalCache.set(cacheKey, repository, REPOSITORY_CACHE_TTL);
489
- return repository;
447
+ return this.cachedRepository;
490
448
  }
491
449
  async getCachedRepositoryForm(name) {
492
450
  const cachedRepository = await this.getCachedRepository();
493
451
  const form = cachedRepository.forms[name];
494
452
  if (!form) {
495
- throw new Error(`Form with name "${name}" could not be found`);
453
+ throw new PrismicError(`Form with name "${name}" could not be found`, void 0, void 0);
496
454
  }
497
455
  return form;
498
456
  }
499
- getPreviewRefString() {
500
- var _a, _b, _c;
501
- if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
502
- return getCookie(preview, globalThis.document.cookie);
503
- } else if ((_c = (_b = this.refMode.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
504
- return getCookie(preview, this.refMode.httpRequest.headers.cookie);
505
- }
506
- }
507
- async getIntegrationFieldsRef() {
508
- const repository = await this.getCachedRepository();
509
- return repository.integrationFieldsRef || void 0;
510
- }
511
- async getResolvedIntegrationFieldsRef() {
512
- const thisIntegrationFieldsRefThunk = castThunk(this.integrationFieldsRef);
513
- const res = await thisIntegrationFieldsRefThunk();
514
- if (typeof res === "string") {
515
- return res;
516
- } else {
517
- return await this.getIntegrationFieldsRef();
518
- }
519
- }
520
457
  async getResolvedRefString() {
521
- if (this.refMode.autoPreviewsEnabled) {
522
- const previewRef = this.getPreviewRefString();
458
+ var _a, _b, _c;
459
+ if (this.refState.autoPreviewsEnabled) {
460
+ let previewRef = void 0;
461
+ if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
462
+ previewRef = getCookie(preview, globalThis.document.cookie);
463
+ } else if ((_c = (_b = this.refState.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
464
+ previewRef = getCookie(preview, this.refState.httpRequest.headers.cookie);
465
+ }
523
466
  if (previewRef) {
524
467
  return previewRef;
525
468
  }
526
469
  }
527
- switch (this.refMode.type) {
528
- case 1: {
529
- const releaseID = this.refMode.payload.releaseID;
530
- const repository = await this.getCachedRepository();
531
- const ref = findRef(repository.refs, (ref2) => ref2.id === releaseID);
532
- return ref.ref;
533
- }
534
- case 2: {
535
- const releaseLabel = this.refMode.payload.releaseLabel;
536
- const repository = await this.getCachedRepository();
537
- const ref = findRef(repository.refs, (ref2) => ref2.label === releaseLabel);
538
- return ref.ref;
539
- }
540
- case 3: {
541
- const thisRefThunk = castThunk(this.refMode.payload.refStringOrFn);
542
- const res = await thisRefThunk();
543
- if (typeof res === "string") {
544
- return res;
545
- }
546
- }
547
- case 0:
548
- default: {
549
- const repository = await this.getCachedRepository();
550
- const ref = findRef(repository.refs, (ref2) => ref2.isMasterRef);
551
- return ref.ref;
470
+ const cachedRepository = await this.getCachedRepository();
471
+ const refModeType = this.refState.mode;
472
+ if (refModeType === RefStateMode.ReleaseID) {
473
+ return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
474
+ } else if (refModeType === RefStateMode.ReleaseLabel) {
475
+ return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel).ref;
476
+ } else if (refModeType === RefStateMode.Manual) {
477
+ const res = await castThunk(this.refState.ref)();
478
+ if (typeof res === "string") {
479
+ return res;
552
480
  }
553
481
  }
482
+ return findMasterRef(cachedRepository.refs).ref;
554
483
  }
555
- async fetch(url) {
484
+ async fetch(url, _params) {
556
485
  const res = await this.fetchFn(url);
557
486
  let json;
558
487
  try {
559
488
  json = await res.json();
560
489
  } catch (e) {
561
- throw new PrismicError(void 0, { url });
490
+ throw new PrismicError(void 0, url, void 0);
562
491
  }
563
492
  switch (res.status) {
564
493
  case 200: {
565
494
  return json;
566
495
  }
567
496
  case 400: {
568
- if (isParsingErrorAPIResponse(json)) {
569
- throw new ParsingError(json.message, {
570
- url,
571
- response: json
572
- });
573
- }
574
- break;
497
+ throw new ParsingError(json.message, url, json);
575
498
  }
576
499
  case 401:
577
500
  case 403: {
578
- if (isForbiddenErrorAPIResponse(json)) {
579
- throw new ForbiddenError("error" in json ? json.error : json.message, {
580
- url,
581
- response: json
582
- });
583
- }
501
+ throw new ForbiddenError("error" in json ? json.error : json.message, url, json);
584
502
  }
585
503
  }
586
- throw new PrismicError(void 0, { url, response: json });
504
+ throw new PrismicError(void 0, url, json);
587
505
  }
588
506
  }
589
507
 
508
+ const predicates = predicate;
509
+ const Predicates = predicate;
510
+
590
511
  exports.Client = Client;
591
512
  exports.ForbiddenError = ForbiddenError;
592
513
  exports.ParsingError = ParsingError;
514
+ exports.Predicates = Predicates;
593
515
  exports.PrismicError = PrismicError;
594
516
  exports.buildQueryURL = buildQueryURL;
595
517
  exports.cookie = cookie;
596
518
  exports.createClient = createClient;
597
519
  exports.getEndpoint = getEndpoint;
598
520
  exports.predicate = predicate;
521
+ exports.predicates = predicates;
599
522
  //# sourceMappingURL=index.cjs.map