@prismicio/client 6.0.0-alpha.8 → 6.0.0-beta.2

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