@prismicio/client 6.0.0-alpha.9 → 6.0.0-beta.3

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