@prismicio/client 6.0.0-beta.0 → 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
@@ -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
- }
106
- }
107
-
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
- }
125
+ class ForbiddenError extends PrismicError {
120
126
  }
121
127
 
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
+ class ParsingError extends PrismicError {
128
129
  }
129
130
 
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,68 @@ 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
+ };
195
+
196
+ const preview = "io.prismic.preview";
199
197
 
200
- const predicate = /*#__PURE__*/Object.freeze({
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
+ 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);
266
215
  const createClient = (...args) => new Client(...args);
267
216
  class Client {
268
217
  constructor(endpoint, options = {}) {
269
- this.query = this.get.bind(this);
218
+ this.refState = {
219
+ mode: RefStateMode.Master,
220
+ autoPreviewsEnabled: true
221
+ };
222
+ this.cachedRepositoryExpiration = 0;
270
223
  this.endpoint = endpoint;
271
224
  this.accessToken = options.accessToken;
272
- this.integrationFieldsRef = options.integrationFieldsRef;
273
225
  this.routes = options.routes;
274
226
  this.defaultParams = options.defaultParams;
275
- this.internalCache = createSimpleTTLCache();
276
- this.refMode = {
277
- type: 0,
278
- autoPreviewsEnabled: true
279
- };
280
227
  if (options.ref) {
281
228
  this.queryContentFromRef(options.ref);
282
229
  }
@@ -285,37 +232,45 @@ class Client {
285
232
  } else if (typeof globalThis.fetch === "function") {
286
233
  this.fetchFn = globalThis.fetch;
287
234
  } 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.");
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);
289
236
  }
290
237
  if (this.fetchFn === globalThis.fetch) {
291
238
  this.fetchFn = this.fetchFn.bind(globalThis);
292
239
  }
293
240
  }
294
241
  enableAutoPreviews() {
295
- this.refMode.autoPreviewsEnabled = true;
242
+ this.refState.autoPreviewsEnabled = true;
296
243
  }
297
244
  enableAutoPreviewsFromReq(req) {
298
- this.refMode.httpRequest = req;
299
- this.refMode.autoPreviewsEnabled = true;
245
+ this.refState.httpRequest = req;
246
+ this.refState.autoPreviewsEnabled = true;
300
247
  }
301
248
  disableAutoPreviews() {
302
- 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);
303
254
  }
304
255
  async get(params) {
305
256
  const url = await this.buildQueryURL(params);
306
- return await this.fetch(url);
257
+ return await this.fetch(url, params);
307
258
  }
308
259
  async getFirst(params) {
309
- const result = await this.get(params);
260
+ const url = await this.buildQueryURL(params);
261
+ const result = await this.fetch(url, params);
310
262
  const firstResult = result.results[0];
311
263
  if (firstResult) {
312
264
  return firstResult;
313
265
  }
314
- throw new Error("No documents were returned");
266
+ throw new PrismicError("No documents were returned", url, void 0);
315
267
  }
316
268
  async getAll(params = {}) {
317
269
  const { limit = Infinity, ...actualParams } = params;
318
- const resolvedParams = { pageSize: MAX_PAGE_SIZE, ...actualParams };
270
+ const resolvedParams = {
271
+ ...actualParams,
272
+ pageSize: actualParams.pageSize || MAX_PAGE_SIZE
273
+ };
319
274
  const result = await this.get(resolvedParams);
320
275
  let page = result.page;
321
276
  let documents = result.results;
@@ -327,66 +282,77 @@ class Client {
327
282
  return documents.slice(0, limit);
328
283
  }
329
284
  async getByID(id, params) {
330
- return await this.getFirst(appendPredicates(at("document.id", id))(params));
285
+ return await this.getFirst(appendPredicates(params, predicate.at("document.id", id)));
331
286
  }
332
287
  async getByIDs(ids, params) {
333
- return await this.get(appendPredicates(_in("document.id", ids))(params));
288
+ return await this.get(appendPredicates(params, predicate.in("document.id", ids)));
334
289
  }
335
290
  async getAllByIDs(ids, params) {
336
- return await this.getAll(appendPredicates(_in("document.id", ids))(params));
291
+ return await this.getAll(appendPredicates(params, predicate.in("document.id", ids)));
337
292
  }
338
293
  async getByUID(documentType, uid, params) {
339
- 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
+ ]));
340
298
  }
341
299
  async getByUIDs(documentType, uids, params) {
342
- return await this.get(appendPredicates(typePredicate(documentType), _in(`my.${documentType}.uid`, uids))(params));
300
+ return await this.get(appendPredicates(params, [
301
+ typePredicate(documentType),
302
+ predicate.in(`my.${documentType}.uid`, uids)
303
+ ]));
343
304
  }
344
305
  async getAllByUIDs(documentType, uids, params) {
345
- return await this.getAll(appendPredicates(typePredicate(documentType), _in(`my.${documentType}.uid`, uids))(params));
306
+ return await this.getAll(appendPredicates(params, [
307
+ typePredicate(documentType),
308
+ predicate.in(`my.${documentType}.uid`, uids)
309
+ ]));
346
310
  }
347
311
  async getSingle(documentType, params) {
348
- return await this.getFirst(appendPredicates(typePredicate(documentType))(params));
312
+ return await this.getFirst(appendPredicates(params, typePredicate(documentType)));
349
313
  }
350
314
  async getByType(documentType, params) {
351
- return await this.get(appendPredicates(typePredicate(documentType))(params));
315
+ return await this.get(appendPredicates(params, typePredicate(documentType)));
352
316
  }
353
317
  async getAllByType(documentType, params) {
354
- return await this.getAll(appendPredicates(typePredicate(documentType))(params));
318
+ return await this.getAll(appendPredicates(params, typePredicate(documentType)));
355
319
  }
356
320
  async getByTag(tag, params) {
357
- return await this.get(appendPredicates(tagsPredicate(tag))(params));
321
+ return await this.get(appendPredicates(params, everyTagPredicate(tag)));
358
322
  }
359
323
  async getAllByTag(tag, params) {
360
- return await this.getAll(appendPredicates(tagsPredicate(tag))(params));
324
+ return await this.getAll(appendPredicates(params, everyTagPredicate(tag)));
325
+ }
326
+ async getByEveryTag(tags, params) {
327
+ return await this.get(appendPredicates(params, everyTagPredicate(tags)));
328
+ }
329
+ async getAllByEveryTag(tags, params) {
330
+ return await this.getAll(appendPredicates(params, everyTagPredicate(tags)));
361
331
  }
362
- async getByTags(tags, params) {
363
- return await this.get(appendPredicates(tagsPredicate(tags))(params));
332
+ async getBySomeTags(tags, params) {
333
+ return await this.get(appendPredicates(params, someTagsPredicate(tags)));
364
334
  }
365
- async getAllByTags(tags, params) {
366
- return await this.getAll(appendPredicates(tagsPredicate(tags))(params));
335
+ async getAllBySomeTags(tags, params) {
336
+ return await this.getAll(appendPredicates(params, someTagsPredicate(tags)));
367
337
  }
368
338
  async getRepository() {
369
- const url = new URL(this.endpoint);
370
- if (this.accessToken) {
371
- url.searchParams.set("access_token", this.accessToken);
372
- }
373
- return await this.fetch(url.toString());
339
+ return await this.fetch(this.endpoint);
374
340
  }
375
341
  async getRefs() {
376
- const res = await this.getRepository();
377
- return res.refs;
342
+ const repository = await this.getRepository();
343
+ return repository.refs;
378
344
  }
379
345
  async getRefByID(id) {
380
346
  const refs = await this.getRefs();
381
- return findRef(refs, (ref) => ref.id === id);
347
+ return findRefByID(refs, id);
382
348
  }
383
349
  async getRefByLabel(label) {
384
350
  const refs = await this.getRefs();
385
- return findRef(refs, (ref) => ref.label === label);
351
+ return findRefByLabel(refs, label);
386
352
  }
387
353
  async getMasterRef() {
388
354
  const refs = await this.getRefs();
389
- return findRef(refs, (ref) => ref.isMasterRef);
355
+ return findMasterRef(refs);
390
356
  }
391
357
  async getReleases() {
392
358
  const refs = await this.getRefs();
@@ -394,36 +360,31 @@ class Client {
394
360
  }
395
361
  async getReleaseByID(id) {
396
362
  const releases = await this.getReleases();
397
- return findRef(releases, (ref) => ref.id === id);
363
+ return findRefByID(releases, id);
398
364
  }
399
365
  async getReleaseByLabel(label) {
400
366
  const releases = await this.getReleases();
401
- return findRef(releases, (ref) => ref.label === label);
367
+ return findRefByLabel(releases, label);
402
368
  }
403
369
  async getTags() {
404
370
  try {
405
371
  const tagsForm = await this.getCachedRepositoryForm("tags");
406
372
  return await this.fetch(tagsForm.action);
407
373
  } catch (e) {
408
- const res = await this.getRepository();
409
- return res.tags;
374
+ const repository = await this.getRepository();
375
+ return repository.tags;
410
376
  }
411
377
  }
412
378
  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;
379
+ const ref = params.ref || await this.getResolvedRefString();
380
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository()).integrationFieldsRef || void 0;
420
381
  return buildQueryURL(this.endpoint, {
421
382
  ...this.defaultParams,
422
- ...actualParams,
423
- accessToken,
383
+ ...params,
424
384
  ref,
425
385
  integrationFieldsRef,
426
- routes
386
+ routes: params.routes || this.routes,
387
+ accessToken: void 0
427
388
  });
428
389
  }
429
390
  async resolvePreviewURL(args) {
@@ -434,156 +395,108 @@ class Client {
434
395
  const searchParams = new URLSearchParams(globalThis.location.search);
435
396
  documentID = documentID || searchParams.get("documentId") || void 0;
436
397
  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
- }
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;
444
401
  }
445
402
  if (documentID != null) {
446
403
  const document = await this.getByID(documentID, {
447
404
  ref: previewToken
448
405
  });
449
- return prismicH__namespace.asLink(prismicH__namespace.documentToLinkField(document), args.linkResolver);
406
+ return prismicH__namespace.asLink(document, args.linkResolver);
450
407
  } else {
451
408
  return args.defaultURL;
452
409
  }
453
410
  }
454
411
  queryLatestContent() {
455
- this.refMode = {
456
- ...this.refMode,
457
- type: 0
458
- };
412
+ this.refState.mode = RefStateMode.Master;
459
413
  }
460
414
  queryContentFromReleaseByID(releaseID) {
461
- this.refMode = {
462
- ...this.refMode,
463
- type: 1,
464
- payload: { releaseID }
415
+ this.refState = {
416
+ ...this.refState,
417
+ mode: RefStateMode.ReleaseID,
418
+ releaseID
465
419
  };
466
420
  }
467
421
  queryContentFromReleaseByLabel(releaseLabel) {
468
- this.refMode = {
469
- ...this.refMode,
470
- type: 2,
471
- payload: { releaseLabel }
422
+ this.refState = {
423
+ ...this.refState,
424
+ mode: RefStateMode.ReleaseLabel,
425
+ releaseLabel
472
426
  };
473
427
  }
474
428
  queryContentFromRef(ref) {
475
- this.refMode = {
476
- ...this.refMode,
477
- type: 3,
478
- payload: { refStringOrFn: ref }
429
+ this.refState = {
430
+ ...this.refState,
431
+ mode: RefStateMode.Manual,
432
+ ref
479
433
  };
480
434
  }
481
435
  async getCachedRepository() {
482
- const cacheKey = this.endpoint;
483
- const cachedRepository = this.internalCache.get(cacheKey);
484
- if (cachedRepository) {
485
- return cachedRepository;
436
+ if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
437
+ this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
438
+ this.cachedRepository = await this.getRepository();
486
439
  }
487
- const repository = await this.getRepository();
488
- this.internalCache.set(cacheKey, repository, REPOSITORY_CACHE_TTL);
489
- return repository;
440
+ return this.cachedRepository;
490
441
  }
491
442
  async getCachedRepositoryForm(name) {
492
443
  const cachedRepository = await this.getCachedRepository();
493
444
  const form = cachedRepository.forms[name];
494
445
  if (!form) {
495
- 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);
496
447
  }
497
448
  return form;
498
449
  }
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
450
  async getResolvedRefString() {
521
- if (this.refMode.autoPreviewsEnabled) {
522
- 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
+ }
523
459
  if (previewRef) {
524
460
  return previewRef;
525
461
  }
526
462
  }
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;
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;
552
473
  }
553
474
  }
475
+ return findMasterRef(cachedRepository.refs).ref;
554
476
  }
555
- async fetch(url) {
556
- const res = await this.fetchFn(url);
477
+ async fetch(url, params) {
478
+ const accessToken = params && params.accessToken || this.accessToken;
479
+ const options = accessToken ? { headers: { Authorization: `Token ${accessToken}` } } : {};
480
+ const res = await this.fetchFn(url, options);
557
481
  let json;
558
482
  try {
559
483
  json = await res.json();
560
484
  } catch (e) {
561
- throw new PrismicError(void 0, { url });
485
+ throw new PrismicError(void 0, url, void 0);
562
486
  }
563
487
  switch (res.status) {
564
488
  case 200: {
565
489
  return json;
566
490
  }
567
491
  case 400: {
568
- if (isParsingErrorAPIResponse(json)) {
569
- throw new ParsingError(json.message, {
570
- url,
571
- response: json
572
- });
573
- }
574
- break;
492
+ throw new ParsingError(json.message, url, json);
575
493
  }
576
494
  case 401:
577
495
  case 403: {
578
- if (isForbiddenErrorAPIResponse(json)) {
579
- throw new ForbiddenError("error" in json ? json.error : json.message, {
580
- url,
581
- response: json
582
- });
583
- }
496
+ throw new ForbiddenError("error" in json ? json.error : json.message, url, json);
584
497
  }
585
498
  }
586
- throw new PrismicError(void 0, { url, response: json });
499
+ throw new PrismicError(void 0, url, json);
587
500
  }
588
501
  }
589
502