@prismicio/client 6.1.1 → 6.4.0

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.js CHANGED
@@ -1,8 +1,49 @@
1
1
  import * as prismicH from '@prismicio/helpers';
2
2
 
3
- const getEndpoint = (repositoryName) => `https://${repositoryName}.cdn.prismic.io/api/v2`;
3
+ const isRepositoryName = (input) => {
4
+ return /^[a-zA-Z0-9][-a-zA-Z0-9]{2,}[a-zA-Z0-9]$/.test(input);
5
+ };
6
+
7
+ class PrismicError extends Error {
8
+ constructor(message = "An invalid API response was returned", url, response) {
9
+ super(message);
10
+ this.url = url;
11
+ this.response = response;
12
+ }
13
+ }
14
+
15
+ const getRepositoryEndpoint = (repositoryName) => {
16
+ if (isRepositoryName(repositoryName)) {
17
+ return `https://${repositoryName}.cdn.prismic.io/api/v2`;
18
+ } else {
19
+ throw new PrismicError(`An invalid Prismic repository name was given: ${repositoryName}`, void 0, void 0);
20
+ }
21
+ };
22
+
23
+ const getRepositoryName = (repositoryEndpoint) => {
24
+ try {
25
+ return new URL(repositoryEndpoint).hostname.split(".")[0];
26
+ } catch (e) {
27
+ throw new PrismicError(`An invalid Prismic Rest API V2 endpoint was provided: ${repositoryEndpoint}`, void 0, void 0);
28
+ }
29
+ };
4
30
 
5
- const getGraphQLEndpoint = (repositoryName) => `https://${repositoryName}.cdn.prismic.io/graphql`;
31
+ const getGraphQLEndpoint = (repositoryName) => {
32
+ if (isRepositoryName(repositoryName)) {
33
+ return `https://${repositoryName}.cdn.prismic.io/graphql`;
34
+ } else {
35
+ throw new PrismicError(`An invalid Prismic repository name was given: ${repositoryName}`, void 0, void 0);
36
+ }
37
+ };
38
+
39
+ const isRepositoryEndpoint = (input) => {
40
+ try {
41
+ new URL(input);
42
+ return true;
43
+ } catch (e) {
44
+ return false;
45
+ }
46
+ };
6
47
 
7
48
  const castArray = (a) => Array.isArray(a) ? a : [a];
8
49
 
@@ -55,14 +96,6 @@ const appendPredicates = (objWithPredicates = {}, predicates) => {
55
96
 
56
97
  const castThunk = (a) => typeof a === "function" ? a : () => a;
57
98
 
58
- class PrismicError extends Error {
59
- constructor(message = "An invalid API response was returned", url, response) {
60
- super(message);
61
- this.url = url;
62
- this.response = response;
63
- }
64
- }
65
-
66
99
  const findRef = (refs, predicate) => {
67
100
  const ref = refs.find((ref2) => predicate(ref2));
68
101
  if (!ref) {
@@ -100,9 +133,23 @@ const parse = (cookieString) => {
100
133
  const getAll = (cookieStore) => parse(cookieStore);
101
134
  const getCookie = (name, cookieStore) => getAll(cookieStore)[name];
102
135
 
136
+ const minifyGraphQLQuery = (query) => {
137
+ return query.replace(/(\n| )*( |{|})(\n| )*/gm, (_chars, _spaces, brackets) => brackets);
138
+ };
139
+
140
+ const preview = "io.prismic.preview";
141
+
142
+ var cookie = /*#__PURE__*/Object.freeze({
143
+ __proto__: null,
144
+ preview: preview
145
+ });
146
+
103
147
  class ForbiddenError extends PrismicError {
104
148
  }
105
149
 
150
+ class NotFoundError extends PrismicError {
151
+ }
152
+
106
153
  class ParsingError extends PrismicError {
107
154
  }
108
155
 
@@ -171,34 +218,29 @@ const predicate = {
171
218
  dateHourBefore: pathWithArgsPredicate("date.hour-before")
172
219
  };
173
220
 
174
- const preview = "io.prismic.preview";
175
-
176
- var cookie = /*#__PURE__*/Object.freeze({
177
- __proto__: null,
178
- preview: preview
179
- });
180
-
181
- class NotFoundError extends PrismicError {
182
- }
183
-
184
221
  const MAX_PAGE_SIZE = 100;
185
222
  const REPOSITORY_CACHE_TTL = 5e3;
186
223
  const GET_ALL_QUERY_DELAY = 500;
187
224
  const typePredicate = (documentType) => predicate.at("document.type", documentType);
188
- const everyTagPredicate = (tags) => predicate.at("document.tags", tags);
189
- const someTagsPredicate = (tags) => predicate.any("document.tags", tags);
225
+ const everyTagPredicate = (tags) => predicate.at("document.tags", castArray(tags));
226
+ const someTagsPredicate = (tags) => predicate.any("document.tags", castArray(tags));
190
227
  const createClient = (...args) => new Client(...args);
191
228
  class Client {
192
- constructor(endpoint, options = {}) {
229
+ constructor(repositoryNameOrEndpoint, options = {}) {
193
230
  this.refState = {
194
231
  mode: "Master" /* Master */,
195
232
  autoPreviewsEnabled: true
196
233
  };
197
234
  this.cachedRepositoryExpiration = 0;
198
- if (process.env.NODE_ENV === "development" && /\.prismic\.io\/(?!api\/v2\/?)/.test(endpoint)) {
199
- throw new PrismicError("@prismicio/client only supports Prismic Rest API V2. Please use the getEndpoint helper to generate a valid Rest API V2 endpoint URL.", void 0, void 0);
235
+ this.graphqlFetch = this.graphQLFetch;
236
+ if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
237
+ if (process.env.NODE_ENV === "development" && /\.prismic\.io\/(?!api\/v2\/?)/.test(repositoryNameOrEndpoint)) {
238
+ throw new PrismicError("@prismicio/client only supports Prismic Rest API V2. Please provide only the repository name to the first createClient() parameter or use the getRepositoryEndpoint() helper to generate a valid Rest API V2 endpoint URL.", void 0, void 0);
239
+ }
240
+ this.endpoint = repositoryNameOrEndpoint;
241
+ } else {
242
+ this.endpoint = getRepositoryEndpoint(repositoryNameOrEndpoint);
200
243
  }
201
- this.endpoint = endpoint;
202
244
  this.accessToken = options.accessToken;
203
245
  this.routes = options.routes;
204
246
  this.defaultParams = options.defaultParams;
@@ -215,7 +257,7 @@ class Client {
215
257
  if (this.fetchFn === globalThis.fetch) {
216
258
  this.fetchFn = this.fetchFn.bind(globalThis);
217
259
  }
218
- this.graphqlFetch = this.graphqlFetch.bind(this);
260
+ this.graphQLFetch = this.graphQLFetch.bind(this);
219
261
  }
220
262
  enableAutoPreviews() {
221
263
  this.refState.autoPreviewsEnabled = true;
@@ -245,10 +287,11 @@ class Client {
245
287
  throw new PrismicError("No documents were returned", url, void 0);
246
288
  }
247
289
  async dangerouslyGetAll(params = {}) {
290
+ var _a;
248
291
  const { limit = Infinity, ...actualParams } = params;
249
292
  const resolvedParams = {
250
293
  ...actualParams,
251
- pageSize: actualParams.pageSize || MAX_PAGE_SIZE
294
+ pageSize: actualParams.pageSize || ((_a = this.defaultParams) == null ? void 0 : _a.pageSize) || MAX_PAGE_SIZE
252
295
  };
253
296
  const documents = [];
254
297
  let latestResult;
@@ -299,10 +342,10 @@ class Client {
299
342
  return await this.dangerouslyGetAll(appendPredicates(params, typePredicate(documentType)));
300
343
  }
301
344
  async getByTag(tag, params) {
302
- return await this.get(appendPredicates(params, everyTagPredicate(tag)));
345
+ return await this.get(appendPredicates(params, someTagsPredicate(tag)));
303
346
  }
304
347
  async getAllByTag(tag, params) {
305
- return await this.dangerouslyGetAll(appendPredicates(params, everyTagPredicate(tag)));
348
+ return await this.dangerouslyGetAll(appendPredicates(params, someTagsPredicate(tag)));
306
349
  }
307
350
  async getByEveryTag(tags, params) {
308
351
  return await this.get(appendPredicates(params, everyTagPredicate(tags)));
@@ -316,53 +359,56 @@ class Client {
316
359
  async getAllBySomeTags(tags, params) {
317
360
  return await this.dangerouslyGetAll(appendPredicates(params, someTagsPredicate(tags)));
318
361
  }
319
- async getRepository() {
362
+ async getRepository(params) {
320
363
  const url = new URL(this.endpoint);
321
364
  if (this.accessToken) {
322
365
  url.searchParams.set("access_token", this.accessToken);
323
366
  }
324
- return await this.fetch(url.toString());
367
+ return await this.fetch(url.toString(), params);
325
368
  }
326
- async getRefs() {
327
- const repository = await this.getRepository();
369
+ async getRefs(params) {
370
+ const repository = await this.getRepository(params);
328
371
  return repository.refs;
329
372
  }
330
- async getRefByID(id) {
331
- const refs = await this.getRefs();
373
+ async getRefByID(id, params) {
374
+ const refs = await this.getRefs(params);
332
375
  return findRefByID(refs, id);
333
376
  }
334
- async getRefByLabel(label) {
335
- const refs = await this.getRefs();
377
+ async getRefByLabel(label, params) {
378
+ const refs = await this.getRefs(params);
336
379
  return findRefByLabel(refs, label);
337
380
  }
338
- async getMasterRef() {
339
- const refs = await this.getRefs();
381
+ async getMasterRef(params) {
382
+ const refs = await this.getRefs(params);
340
383
  return findMasterRef(refs);
341
384
  }
342
- async getReleases() {
343
- const refs = await this.getRefs();
385
+ async getReleases(params) {
386
+ const refs = await this.getRefs(params);
344
387
  return refs.filter((ref) => !ref.isMasterRef);
345
388
  }
346
- async getReleaseByID(id) {
347
- const releases = await this.getReleases();
389
+ async getReleaseByID(id, params) {
390
+ const releases = await this.getReleases(params);
348
391
  return findRefByID(releases, id);
349
392
  }
350
- async getReleaseByLabel(label) {
351
- const releases = await this.getReleases();
393
+ async getReleaseByLabel(label, params) {
394
+ const releases = await this.getReleases(params);
352
395
  return findRefByLabel(releases, label);
353
396
  }
354
- async getTags() {
397
+ async getTags(params) {
355
398
  try {
356
- const tagsForm = await this.getCachedRepositoryForm("tags");
399
+ const tagsForm = await this.getCachedRepositoryForm("tags", params);
357
400
  return await this.fetch(tagsForm.action);
358
401
  } catch (e) {
359
- const repository = await this.getRepository();
402
+ const repository = await this.getRepository(params);
360
403
  return repository.tags;
361
404
  }
362
405
  }
363
- async buildQueryURL(params = {}) {
406
+ async buildQueryURL({
407
+ signal,
408
+ ...params
409
+ } = {}) {
364
410
  const ref = params.ref || await this.getResolvedRefString();
365
- const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository()).integrationFieldsRef || void 0;
411
+ const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository({ signal })).integrationFieldsRef || void 0;
366
412
  return buildQueryURL(this.endpoint, {
367
413
  ...this.defaultParams,
368
414
  ...params,
@@ -384,15 +430,18 @@ class Client {
384
430
  documentID = documentID || this.refState.httpRequest.query.documentId;
385
431
  previewToken = previewToken || this.refState.httpRequest.query.token;
386
432
  }
387
- if (documentID != null) {
433
+ if (documentID != null && previewToken != null) {
388
434
  const document = await this.getByID(documentID, {
435
+ signal: args.signal,
389
436
  ref: previewToken,
390
437
  lang: "*"
391
438
  });
392
- return prismicH.asLink(document, args.linkResolver);
393
- } else {
394
- return args.defaultURL;
439
+ const url = prismicH.asLink(document, args.linkResolver);
440
+ if (typeof url === "string") {
441
+ return url;
442
+ }
395
443
  }
444
+ return args.defaultURL;
396
445
  }
397
446
  queryLatestContent() {
398
447
  this.refState.mode = "Master" /* Master */;
@@ -418,7 +467,7 @@ class Client {
418
467
  ref
419
468
  };
420
469
  }
421
- async graphqlFetch(input, init) {
470
+ async graphQLFetch(input, init) {
422
471
  const cachedRepository = await this.getCachedRepository();
423
472
  const ref = await this.getResolvedRefString();
424
473
  const unsanitizedHeaders = {
@@ -433,27 +482,32 @@ class Client {
433
482
  headers[key.toLowerCase()] = unsanitizedHeaders[key];
434
483
  }
435
484
  }
436
- return await this.fetchFn(input, {
485
+ const url = new URL(input);
486
+ const query = url.searchParams.get("query");
487
+ if (query) {
488
+ url.searchParams.set("query", minifyGraphQLQuery(query));
489
+ }
490
+ return await this.fetchFn(url.toString(), {
437
491
  ...init,
438
492
  headers
439
493
  });
440
494
  }
441
- async getCachedRepository() {
495
+ async getCachedRepository(params) {
442
496
  if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
443
497
  this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
444
- this.cachedRepository = await this.getRepository();
498
+ this.cachedRepository = await this.getRepository(params);
445
499
  }
446
500
  return this.cachedRepository;
447
501
  }
448
- async getCachedRepositoryForm(name) {
449
- const cachedRepository = await this.getCachedRepository();
502
+ async getCachedRepositoryForm(name, params) {
503
+ const cachedRepository = await this.getCachedRepository(params);
450
504
  const form = cachedRepository.forms[name];
451
505
  if (!form) {
452
506
  throw new PrismicError(`Form with name "${name}" could not be found`, void 0, void 0);
453
507
  }
454
508
  return form;
455
509
  }
456
- async getResolvedRefString() {
510
+ async getResolvedRefString(params) {
457
511
  var _a, _b, _c;
458
512
  if (this.refState.autoPreviewsEnabled) {
459
513
  let previewRef = void 0;
@@ -466,7 +520,7 @@ class Client {
466
520
  return previewRef;
467
521
  }
468
522
  }
469
- const cachedRepository = await this.getCachedRepository();
523
+ const cachedRepository = await this.getCachedRepository(params);
470
524
  const refModeType = this.refState.mode;
471
525
  if (refModeType === "ReleaseID" /* ReleaseID */) {
472
526
  return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
@@ -480,8 +534,10 @@ class Client {
480
534
  }
481
535
  return findMasterRef(cachedRepository.refs).ref;
482
536
  }
483
- async fetch(url, _params) {
484
- const res = await this.fetchFn(url);
537
+ async fetch(url, params = {}) {
538
+ const res = await this.fetchFn(url, {
539
+ signal: params.signal
540
+ });
485
541
  let json;
486
542
  try {
487
543
  json = await res.json();
@@ -508,8 +564,9 @@ class Client {
508
564
  }
509
565
  }
510
566
 
567
+ const getEndpoint = getRepositoryEndpoint;
511
568
  const predicates = predicate;
512
569
  const Predicates = predicate;
513
570
 
514
- export { Client, ForbiddenError, NotFoundError, ParsingError, Predicates, PrismicError, buildQueryURL, cookie, createClient, getEndpoint, getGraphQLEndpoint, predicate, predicates };
571
+ export { Client, ForbiddenError, NotFoundError, ParsingError, Predicates, PrismicError, buildQueryURL, cookie, createClient, getEndpoint, getGraphQLEndpoint, getRepositoryEndpoint, getRepositoryName, isRepositoryEndpoint, isRepositoryName, predicate, predicates };
515
572
  //# sourceMappingURL=index.js.map