@prismicio/client 6.0.0-alpha.7 → 6.0.0-beta.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.
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 && "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
+ };
195
+
196
+ const preview = "io.prismic.preview";
196
197
 
197
- const predicate = /*#__PURE__*/Object.freeze({
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
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,56 +282,77 @@ 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
  return await this.fetch(this.endpoint);
359
340
  }
360
341
  async getRefs() {
361
- const res = await this.getRepository();
362
- return res.refs;
342
+ const repository = await this.getRepository();
343
+ return repository.refs;
363
344
  }
364
- async getRefById(id) {
345
+ async getRefByID(id) {
365
346
  const refs = await this.getRefs();
366
- return findRef(refs, (ref) => ref.id === id);
347
+ return findRefByID(refs, id);
367
348
  }
368
349
  async getRefByLabel(label) {
369
350
  const refs = await this.getRefs();
370
- return findRef(refs, (ref) => ref.label === label);
351
+ return findRefByLabel(refs, label);
371
352
  }
372
353
  async getMasterRef() {
373
354
  const refs = await this.getRefs();
374
- return findRef(refs, (ref) => ref.isMasterRef);
355
+ return findMasterRef(refs);
375
356
  }
376
357
  async getReleases() {
377
358
  const refs = await this.getRefs();
@@ -379,186 +360,143 @@ class Client {
379
360
  }
380
361
  async getReleaseByID(id) {
381
362
  const releases = await this.getReleases();
382
- return findRef(releases, (ref) => ref.id === id);
363
+ return findRefByID(releases, id);
383
364
  }
384
365
  async getReleaseByLabel(label) {
385
366
  const releases = await this.getReleases();
386
- return findRef(releases, (ref) => ref.label === label);
367
+ return findRefByLabel(releases, label);
387
368
  }
388
369
  async getTags() {
389
370
  try {
390
371
  const tagsForm = await this.getCachedRepositoryForm("tags");
391
372
  return await this.fetch(tagsForm.action);
392
373
  } catch (e) {
393
- const res = await this.getRepository();
394
- return res.tags;
374
+ const repository = await this.getRepository();
375
+ return repository.tags;
395
376
  }
396
377
  }
397
378
  async buildQueryURL(params = {}) {
398
- const {
399
- ref = await this.getResolvedRefString(),
400
- accessToken: _accessToken,
401
- ...actualParams
402
- } = params;
379
+ const ref = params.ref || await this.getResolvedRefString();
380
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository()).integrationFieldsRef || void 0;
403
381
  return buildQueryURL(this.endpoint, {
404
382
  ...this.defaultParams,
405
- ...actualParams,
406
- ref
383
+ ...params,
384
+ ref,
385
+ integrationFieldsRef,
386
+ routes: params.routes || this.routes,
387
+ accessToken: void 0
407
388
  });
408
389
  }
409
390
  async resolvePreviewURL(args) {
410
391
  var _a;
411
- let documentId = args.documentId;
392
+ let documentID = args.documentID;
412
393
  let previewToken = args.previewToken;
413
394
  if (typeof globalThis.location !== "undefined") {
414
395
  const searchParams = new URLSearchParams(globalThis.location.search);
415
- documentId = documentId || searchParams.get("documentId") || void 0;
396
+ documentID = documentID || searchParams.get("documentId") || void 0;
416
397
  previewToken = previewToken || searchParams.get("token") || void 0;
417
- } else if ((_a = this.refMode.httpRequest) == null ? void 0 : _a.query) {
418
- if (typeof this.refMode.httpRequest.query.documentId === "string") {
419
- documentId = documentId || this.refMode.httpRequest.query.documentId;
420
- }
421
- if (typeof this.refMode.httpRequest.query.token === "string") {
422
- previewToken = previewToken || this.refMode.httpRequest.query.token;
423
- }
398
+ } else if ((_a = this.refState.httpRequest) == null ? void 0 : _a.query) {
399
+ documentID = documentID || this.refState.httpRequest.query.documentId;
400
+ previewToken = previewToken || this.refState.httpRequest.query.token;
424
401
  }
425
- if (documentId != null) {
426
- const document = await this.getByID(documentId, {
402
+ if (documentID != null) {
403
+ const document = await this.getByID(documentID, {
427
404
  ref: previewToken
428
405
  });
429
- return prismicH__namespace.asLink(prismicH__namespace.documentToLinkField(document), args.linkResolver);
406
+ return prismicH__namespace.asLink(document, args.linkResolver);
430
407
  } else {
431
408
  return args.defaultURL;
432
409
  }
433
410
  }
434
411
  queryLatestContent() {
435
- this.refMode = {
436
- ...this.refMode,
437
- type: 0
438
- };
412
+ this.refState.mode = RefStateMode.Master;
439
413
  }
440
- queryContentFromReleaseByID(releaseId) {
441
- this.refMode = {
442
- ...this.refMode,
443
- type: 1,
444
- payload: { releaseId }
414
+ queryContentFromReleaseByID(releaseID) {
415
+ this.refState = {
416
+ ...this.refState,
417
+ mode: RefStateMode.ReleaseID,
418
+ releaseID
445
419
  };
446
420
  }
447
421
  queryContentFromReleaseByLabel(releaseLabel) {
448
- this.refMode = {
449
- ...this.refMode,
450
- type: 2,
451
- payload: { releaseLabel }
422
+ this.refState = {
423
+ ...this.refState,
424
+ mode: RefStateMode.ReleaseLabel,
425
+ releaseLabel
452
426
  };
453
427
  }
454
428
  queryContentFromRef(ref) {
455
- this.refMode = {
456
- ...this.refMode,
457
- type: 3,
458
- payload: { refStringOrFn: ref }
429
+ this.refState = {
430
+ ...this.refState,
431
+ mode: RefStateMode.Manual,
432
+ ref
459
433
  };
460
434
  }
461
435
  async getCachedRepository() {
462
- const cacheKey = this.endpoint;
463
- const cachedRepository = this.internalCache.get(cacheKey);
464
- if (cachedRepository) {
465
- return cachedRepository;
436
+ if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
437
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
438
+ this.cachedRepository = await this.getRepository();
466
439
  }
467
- const repository = await this.getRepository();
468
- this.internalCache.set(cacheKey, repository, REPOSITORY_CACHE_TTL);
469
- return repository;
440
+ return this.cachedRepository;
470
441
  }
471
442
  async getCachedRepositoryForm(name) {
472
443
  const cachedRepository = await this.getCachedRepository();
473
444
  const form = cachedRepository.forms[name];
474
445
  if (!form) {
475
- throw new Error(`Form with name "${name}" could not be found`);
446
+ throw new PrismicError(`Form with name "${name}" could not be found`, void 0, void 0);
476
447
  }
477
448
  return form;
478
449
  }
479
- getPreviewRefString() {
480
- var _a, _b, _c;
481
- if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
482
- return getCookie(preview, globalThis.document.cookie);
483
- } else if ((_c = (_b = this.refMode.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
484
- return getCookie(preview, this.refMode.httpRequest.headers.cookie);
485
- }
486
- }
487
450
  async getResolvedRefString() {
488
- if (this.refMode.autoPreviewsEnabled) {
489
- const previewRef = this.getPreviewRefString();
451
+ var _a, _b, _c;
452
+ if (this.refState.autoPreviewsEnabled) {
453
+ let previewRef = void 0;
454
+ if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
455
+ previewRef = getCookie(preview, globalThis.document.cookie);
456
+ } else if ((_c = (_b = this.refState.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
457
+ previewRef = getCookie(preview, this.refState.httpRequest.headers.cookie);
458
+ }
490
459
  if (previewRef) {
491
460
  return previewRef;
492
461
  }
493
462
  }
494
- switch (this.refMode.type) {
495
- case 1: {
496
- const releaseId = this.refMode.payload.releaseId;
497
- const repository = await this.getCachedRepository();
498
- const ref = findRef(repository.refs, (ref2) => ref2.id === releaseId);
499
- return ref.ref;
500
- }
501
- case 2: {
502
- const releaseLabel = this.refMode.payload.releaseLabel;
503
- const repository = await this.getCachedRepository();
504
- const ref = findRef(repository.refs, (ref2) => ref2.label === releaseLabel);
505
- return ref.ref;
506
- }
507
- case 3: {
508
- const thisRefStringOrFn = this.refMode.payload.refStringOrFn;
509
- if (typeof thisRefStringOrFn === "function") {
510
- const res = await thisRefStringOrFn();
511
- if (typeof res === "string") {
512
- return res;
513
- }
514
- } else if (thisRefStringOrFn) {
515
- return thisRefStringOrFn;
516
- }
517
- }
518
- case 0:
519
- default: {
520
- const repository = await this.getCachedRepository();
521
- const ref = findRef(repository.refs, (ref2) => ref2.isMasterRef);
522
- return ref.ref;
463
+ const cachedRepository = await this.getCachedRepository();
464
+ const refModeType = this.refState.mode;
465
+ if (refModeType === RefStateMode.ReleaseID) {
466
+ return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
467
+ } else if (refModeType === RefStateMode.ReleaseLabel) {
468
+ return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel).ref;
469
+ } else if (refModeType === RefStateMode.Manual) {
470
+ const res = await castThunk(this.refState.ref)();
471
+ if (typeof res === "string") {
472
+ return res;
523
473
  }
524
474
  }
525
- }
526
- buildRequestOptions(params) {
527
- const accessToken = (params == null ? void 0 : params.accessToken) || this.accessToken;
528
- return accessToken ? { headers: { Authorization: `Token ${accessToken}` } } : {};
475
+ return findMasterRef(cachedRepository.refs).ref;
529
476
  }
530
477
  async fetch(url, params) {
531
- const options = this.buildRequestOptions(params);
478
+ const accessToken = params && params.accessToken || this.accessToken;
479
+ const options = accessToken ? { headers: { Authorization: `Token ${accessToken}` } } : {};
532
480
  const res = await this.fetchFn(url, options);
533
481
  let json;
534
482
  try {
535
483
  json = await res.json();
536
484
  } catch (e) {
537
- throw new PrismicError(void 0, { url });
485
+ throw new PrismicError(void 0, url, void 0);
538
486
  }
539
487
  switch (res.status) {
540
488
  case 200: {
541
489
  return json;
542
490
  }
543
491
  case 400: {
544
- if (isParsingErrorAPIResponse(json)) {
545
- throw new ParsingError(json.message, {
546
- url,
547
- response: json
548
- });
549
- }
550
- break;
492
+ throw new ParsingError(json.message, url, json);
551
493
  }
494
+ case 401:
552
495
  case 403: {
553
- if (isForbiddenErrorAPIResponse(json)) {
554
- throw new ForbiddenError(json.error, {
555
- url,
556
- response: json
557
- });
558
- }
496
+ throw new ForbiddenError("error" in json ? json.error : json.message, url, json);
559
497
  }
560
498
  }
561
- throw new PrismicError(void 0, { url, response: json });
499
+ throw new PrismicError(void 0, url, json);
562
500
  }
563
501
  }
564
502
 
@@ -571,3 +509,4 @@ exports.cookie = cookie;
571
509
  exports.createClient = createClient;
572
510
  exports.getEndpoint = getEndpoint;
573
511
  exports.predicate = predicate;
512
+ //# sourceMappingURL=index.cjs.map