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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js DELETED
@@ -1,540 +0,0 @@
1
- import * as prismicH from '@prismicio/helpers';
2
-
3
- const getEndpoint = (repositoryName) => `https://${repositoryName}.cdn.prismic.io/api/v2`;
4
-
5
- const castArray = (a) => Array.isArray(a) ? a : [a];
6
-
7
- const RENAMED_PARAMS = {
8
- accessToken: "access_token"
9
- };
10
- const castOrderingToString = (ordering) => typeof ordering === "string" ? ordering : [
11
- ordering.field,
12
- ordering.direction === "desc" ? ordering.direction : void 0
13
- ].filter(Boolean).join(" ");
14
- const buildQueryURL = (endpoint, args) => {
15
- var _a;
16
- const { ref, predicates, ...params } = args;
17
- const url = new URL(`documents/search`, `${endpoint}/`);
18
- url.searchParams.set("ref", ref);
19
- if (predicates) {
20
- for (const predicate of castArray(predicates)) {
21
- url.searchParams.append("q", `[${predicate}]`);
22
- }
23
- }
24
- for (const k in params) {
25
- const name = (_a = RENAMED_PARAMS[k]) != null ? _a : k;
26
- let value = params[k];
27
- if (name === "orderings") {
28
- const scopedValue = params[name];
29
- if (scopedValue != null) {
30
- const v = castArray(scopedValue).map((ordering) => castOrderingToString(ordering)).join(",");
31
- value = `[${v}]`;
32
- }
33
- } else if (name === "routes") {
34
- if (typeof params[name] === "object") {
35
- value = JSON.stringify(castArray(params[name]));
36
- }
37
- }
38
- if (value != null) {
39
- url.searchParams.set(name, castArray(value).join(","));
40
- }
41
- }
42
- return url.toString();
43
- };
44
-
45
- const appendPredicates = (...predicates) => (objWithPredicates = {}) => ({
46
- ...objWithPredicates,
47
- predicates: [objWithPredicates.predicates || [], ...predicates].flat()
48
- });
49
-
50
- const readValue = (value) => {
51
- return value.replace(/%3B/g, ";");
52
- };
53
- const parse = (cookieString) => {
54
- const result = {};
55
- const cookies = cookieString.split("; ");
56
- for (const cookie of cookies) {
57
- const parts = cookie.split("=");
58
- const value = parts.slice(1).join("=");
59
- const name = readValue(parts[0]).replace(/%3D/g, "=");
60
- result[name] = readValue(value);
61
- }
62
- return result;
63
- };
64
- const getAll = (cookieStore) => parse(cookieStore);
65
- const getCookie = (name, cookieStore) => getAll(cookieStore)[name];
66
-
67
- const isForbiddenErrorAPIResponse = (input) => {
68
- return typeof input === "object" && input !== null && ("error" in input || "message" in input) && "oauth_initiate" in input && "oauth_token" in input;
69
- };
70
- class ForbiddenError extends Error {
71
- constructor(message, args) {
72
- super(message);
73
- this.url = args.url;
74
- this.oauth_initiate = args.response.oauth_initiate;
75
- this.oauth_token = args.response.oauth_token;
76
- }
77
- }
78
-
79
- const isParsingErrorAPIResponse = (input) => {
80
- return typeof input === "object" && input !== null && "message" in input && "type" in input;
81
- };
82
- class ParsingError extends Error {
83
- constructor(message, args) {
84
- super(message);
85
- this.url = args.url;
86
- this.line = args.response.line;
87
- this.column = args.response.column;
88
- this.id = args.response.id;
89
- this.location = args.response.location;
90
- }
91
- }
92
-
93
- class PrismicError extends Error {
94
- constructor(message, args) {
95
- super(message || "An invalid API response was returned");
96
- this.url = args.url;
97
- this.response = args.response;
98
- }
99
- }
100
-
101
- const preview = "io.prismic.preview";
102
-
103
- var cookie = /*#__PURE__*/Object.freeze({
104
- __proto__: null,
105
- preview: preview
106
- });
107
-
108
- const formatValue = (value) => {
109
- if (Array.isArray(value)) {
110
- return `[${value.map(formatValue).join(", ")}]`;
111
- }
112
- if (typeof value === "string") {
113
- return `"${value}"`;
114
- }
115
- if (value instanceof Date) {
116
- return `${value.getTime()}`;
117
- }
118
- return `${value}`;
119
- };
120
- const pathWithArgsPredicate = (name) => {
121
- const fn = (path, ...args) => {
122
- const formattedArgs = args.map(formatValue).join(", ");
123
- const joiner = path && args.length ? ", " : "";
124
- return `[${name}(${path}${joiner}${formattedArgs})]`;
125
- };
126
- return fn;
127
- };
128
- const pathPredicate = (name) => {
129
- const predicateFn = pathWithArgsPredicate(name);
130
- const fn = (path) => {
131
- return predicateFn(path);
132
- };
133
- return fn;
134
- };
135
- const argsPredicate = (name) => {
136
- const predicateFn = pathWithArgsPredicate(name);
137
- const fn = (...args) => {
138
- return predicateFn("", ...args);
139
- };
140
- return fn;
141
- };
142
- const at = pathWithArgsPredicate("at");
143
- const not = pathWithArgsPredicate("not");
144
- const any = pathWithArgsPredicate("any");
145
- const _in = pathWithArgsPredicate("in");
146
- const fulltext = pathWithArgsPredicate("fulltext");
147
- const has = pathPredicate("has");
148
- const missing = pathPredicate("missing");
149
- const similar = argsPredicate("similar");
150
- const geopointNear = pathWithArgsPredicate("geopoint.near");
151
- const numberLessThan = pathWithArgsPredicate("number.lt");
152
- const numberGreaterThan = pathWithArgsPredicate("number.gt");
153
- const numberInRange = pathWithArgsPredicate("number.inRange");
154
- const dateAfter = pathWithArgsPredicate("date.after");
155
- const dateBefore = pathWithArgsPredicate("date.before");
156
- const dateBetween = pathWithArgsPredicate("date.between");
157
- const dateDayOfMonth = pathWithArgsPredicate("date.day-of-month");
158
- const dateDayOfMonthAfter = pathWithArgsPredicate("date.day-of-month-after");
159
- const dateDayOfMonthBefore = pathWithArgsPredicate("date.day-of-month-before");
160
- const dateDayOfWeek = pathWithArgsPredicate("date.day-of-week");
161
- const dateDayOfWeekAfter = pathWithArgsPredicate("date.day-of-week-after");
162
- const dateDayOfWeekBefore = pathWithArgsPredicate("date.day-of-week-before");
163
- const dateMonth = pathWithArgsPredicate("date.month");
164
- const dateMonthAfter = pathWithArgsPredicate("date.month-after");
165
- const dateMonthBefore = pathWithArgsPredicate("date.month-before");
166
- const dateYear = pathWithArgsPredicate("date.year");
167
- const dateHour = pathWithArgsPredicate("date.hour");
168
- const dateHourAfter = pathWithArgsPredicate("date.hour-after");
169
- const dateHourBefore = pathWithArgsPredicate("date.hour-before");
170
-
171
- var predicate = /*#__PURE__*/Object.freeze({
172
- __proto__: null,
173
- at: at,
174
- not: not,
175
- any: any,
176
- 'in': _in,
177
- fulltext: fulltext,
178
- has: has,
179
- missing: missing,
180
- similar: similar,
181
- geopointNear: geopointNear,
182
- numberLessThan: numberLessThan,
183
- numberGreaterThan: numberGreaterThan,
184
- numberInRange: numberInRange,
185
- dateAfter: dateAfter,
186
- dateBefore: dateBefore,
187
- dateBetween: dateBetween,
188
- dateDayOfMonth: dateDayOfMonth,
189
- dateDayOfMonthAfter: dateDayOfMonthAfter,
190
- dateDayOfMonthBefore: dateDayOfMonthBefore,
191
- dateDayOfWeek: dateDayOfWeek,
192
- dateDayOfWeekAfter: dateDayOfWeekAfter,
193
- dateDayOfWeekBefore: dateDayOfWeekBefore,
194
- dateMonth: dateMonth,
195
- dateMonthAfter: dateMonthAfter,
196
- dateMonthBefore: dateMonthBefore,
197
- dateYear: dateYear,
198
- dateHour: dateHour,
199
- dateHourAfter: dateHourAfter,
200
- dateHourBefore: dateHourBefore
201
- });
202
-
203
- const createSimpleTTLCache = () => {
204
- const cache = new Map();
205
- return {
206
- get(key) {
207
- const cacheValue = cache.get(key);
208
- if (cacheValue) {
209
- if (new Date().getTime() < cacheValue.expiresAt) {
210
- return cacheValue.value;
211
- }
212
- }
213
- },
214
- set(key, value, ttl) {
215
- cache.set(key, { expiresAt: new Date().getTime() + ttl, value });
216
- }
217
- };
218
- };
219
- const MAX_PAGE_SIZE = 100;
220
- const REPOSITORY_CACHE_TTL = 5e3;
221
- var RefStateType;
222
- (function(RefStateType2) {
223
- RefStateType2[RefStateType2["Master"] = 0] = "Master";
224
- RefStateType2[RefStateType2["ReleaseByID"] = 1] = "ReleaseByID";
225
- RefStateType2[RefStateType2["ReleaseByLabel"] = 2] = "ReleaseByLabel";
226
- RefStateType2[RefStateType2["Manual"] = 3] = "Manual";
227
- })(RefStateType || (RefStateType = {}));
228
- const typePredicate = (documentType) => at("document.type", documentType);
229
- const tagsPredicate = (tags) => at("document.tags", tags);
230
- const findRef = (refs, predicate2) => {
231
- const ref = refs.find((ref2) => predicate2(ref2));
232
- if (!ref) {
233
- throw new Error("Ref could not be found.");
234
- }
235
- return ref;
236
- };
237
- const createClient = (...args) => new Client(...args);
238
- class Client {
239
- constructor(endpoint, options = {}) {
240
- this.query = this.get.bind(this);
241
- this.endpoint = endpoint;
242
- this.accessToken = options.accessToken;
243
- this.defaultParams = options.defaultParams;
244
- this.internalCache = createSimpleTTLCache();
245
- this.refMode = {
246
- type: 0,
247
- autoPreviewsEnabled: true
248
- };
249
- if (options.ref) {
250
- this.queryContentFromRef(options.ref);
251
- }
252
- if (typeof options.fetch === "function") {
253
- this.fetchFn = options.fetch;
254
- } else if (typeof globalThis.fetch === "function") {
255
- this.fetchFn = globalThis.fetch;
256
- } else {
257
- 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.");
258
- }
259
- if (this.fetchFn === globalThis.fetch) {
260
- this.fetchFn = this.fetchFn.bind(globalThis);
261
- }
262
- }
263
- enableAutoPreviews() {
264
- this.refMode.autoPreviewsEnabled = true;
265
- }
266
- enableAutoPreviewsFromReq(req) {
267
- this.refMode.httpRequest = req;
268
- this.refMode.autoPreviewsEnabled = true;
269
- }
270
- disableAutoPreviews() {
271
- this.refMode.autoPreviewsEnabled = false;
272
- }
273
- async get(params) {
274
- const url = await this.buildQueryURL(params);
275
- return await this.fetch(url);
276
- }
277
- async getFirst(params) {
278
- const result = await this.get(params);
279
- const firstResult = result.results[0];
280
- if (firstResult) {
281
- return firstResult;
282
- }
283
- throw new Error("No documents were returned");
284
- }
285
- async getAll(params = {}) {
286
- const { limit = Infinity, ...actualParams } = params;
287
- const resolvedParams = { pageSize: MAX_PAGE_SIZE, ...actualParams };
288
- const result = await this.get(resolvedParams);
289
- let page = result.page;
290
- let documents = result.results;
291
- while (page < result.total_pages && documents.length < limit) {
292
- page += 1;
293
- const result2 = await this.get({ ...resolvedParams, page });
294
- documents = [...documents, ...result2.results];
295
- }
296
- return documents.slice(0, limit);
297
- }
298
- async getByID(id, params) {
299
- return await this.getFirst(appendPredicates(at("document.id", id))(params));
300
- }
301
- async getByIDs(ids, params) {
302
- return await this.get(appendPredicates(_in("document.id", ids))(params));
303
- }
304
- async getAllByIDs(ids, params) {
305
- return await this.getAll(appendPredicates(_in("document.id", ids))(params));
306
- }
307
- async getByUID(documentType, uid, params) {
308
- return await this.getFirst(appendPredicates(typePredicate(documentType), at(`my.${documentType}.uid`, uid))(params));
309
- }
310
- async getSingle(documentType, params) {
311
- return await this.getFirst(appendPredicates(typePredicate(documentType))(params));
312
- }
313
- async getByType(documentType, params) {
314
- return await this.get(appendPredicates(typePredicate(documentType))(params));
315
- }
316
- async getAllByType(documentType, params) {
317
- return await this.getAll(appendPredicates(typePredicate(documentType))(params));
318
- }
319
- async getByTag(tag, params) {
320
- return await this.get(appendPredicates(tagsPredicate(tag))(params));
321
- }
322
- async getAllByTag(tag, params) {
323
- return await this.getAll(appendPredicates(tagsPredicate(tag))(params));
324
- }
325
- async getByTags(tags, params) {
326
- return await this.get(appendPredicates(tagsPredicate(tags))(params));
327
- }
328
- async getAllByTags(tags, params) {
329
- return await this.getAll(appendPredicates(tagsPredicate(tags))(params));
330
- }
331
- async getRepository() {
332
- const url = new URL(this.endpoint);
333
- if (this.accessToken) {
334
- url.searchParams.set("access_token", this.accessToken);
335
- }
336
- return await this.fetch(url.toString());
337
- }
338
- async getRefs() {
339
- const res = await this.getRepository();
340
- return res.refs;
341
- }
342
- async getRefById(id) {
343
- const refs = await this.getRefs();
344
- return findRef(refs, (ref) => ref.id === id);
345
- }
346
- async getRefByLabel(label) {
347
- const refs = await this.getRefs();
348
- return findRef(refs, (ref) => ref.label === label);
349
- }
350
- async getMasterRef() {
351
- const refs = await this.getRefs();
352
- return findRef(refs, (ref) => ref.isMasterRef);
353
- }
354
- async getReleases() {
355
- const refs = await this.getRefs();
356
- return refs.filter((ref) => !ref.isMasterRef);
357
- }
358
- async getReleaseByID(id) {
359
- const releases = await this.getReleases();
360
- return findRef(releases, (ref) => ref.id === id);
361
- }
362
- async getReleaseByLabel(label) {
363
- const releases = await this.getReleases();
364
- return findRef(releases, (ref) => ref.label === label);
365
- }
366
- async getTags() {
367
- try {
368
- const tagsForm = await this.getCachedRepositoryForm("tags");
369
- return await this.fetch(tagsForm.action);
370
- } catch (e) {
371
- const res = await this.getRepository();
372
- return res.tags;
373
- }
374
- }
375
- async buildQueryURL(params = {}) {
376
- const {
377
- ref = await this.getResolvedRefString(),
378
- accessToken = this.accessToken,
379
- ...actualParams
380
- } = params;
381
- return buildQueryURL(this.endpoint, {
382
- ...this.defaultParams,
383
- ...actualParams,
384
- accessToken,
385
- ref
386
- });
387
- }
388
- async resolvePreviewURL(args) {
389
- var _a;
390
- let documentId = args.documentId;
391
- let previewToken = args.previewToken;
392
- if (typeof globalThis.location !== "undefined") {
393
- const searchParams = new URLSearchParams(globalThis.location.search);
394
- documentId = documentId || searchParams.get("documentId") || void 0;
395
- previewToken = previewToken || searchParams.get("token") || void 0;
396
- } else if ((_a = this.refMode.httpRequest) == null ? void 0 : _a.query) {
397
- if (typeof this.refMode.httpRequest.query.documentId === "string") {
398
- documentId = documentId || this.refMode.httpRequest.query.documentId;
399
- }
400
- if (typeof this.refMode.httpRequest.query.token === "string") {
401
- previewToken = previewToken || this.refMode.httpRequest.query.token;
402
- }
403
- }
404
- if (documentId != null) {
405
- const document = await this.getByID(documentId, {
406
- ref: previewToken
407
- });
408
- return prismicH.asLink(prismicH.documentToLinkField(document), args.linkResolver);
409
- } else {
410
- return args.defaultURL;
411
- }
412
- }
413
- queryLatestContent() {
414
- this.refMode = {
415
- ...this.refMode,
416
- type: 0
417
- };
418
- }
419
- queryContentFromReleaseByID(releaseId) {
420
- this.refMode = {
421
- ...this.refMode,
422
- type: 1,
423
- payload: { releaseId }
424
- };
425
- }
426
- queryContentFromReleaseByLabel(releaseLabel) {
427
- this.refMode = {
428
- ...this.refMode,
429
- type: 2,
430
- payload: { releaseLabel }
431
- };
432
- }
433
- queryContentFromRef(ref) {
434
- this.refMode = {
435
- ...this.refMode,
436
- type: 3,
437
- payload: { refStringOrFn: ref }
438
- };
439
- }
440
- async getCachedRepository() {
441
- const cacheKey = this.endpoint;
442
- const cachedRepository = this.internalCache.get(cacheKey);
443
- if (cachedRepository) {
444
- return cachedRepository;
445
- }
446
- const repository = await this.getRepository();
447
- this.internalCache.set(cacheKey, repository, REPOSITORY_CACHE_TTL);
448
- return repository;
449
- }
450
- async getCachedRepositoryForm(name) {
451
- const cachedRepository = await this.getCachedRepository();
452
- const form = cachedRepository.forms[name];
453
- if (!form) {
454
- throw new Error(`Form with name "${name}" could not be found`);
455
- }
456
- return form;
457
- }
458
- getPreviewRefString() {
459
- var _a, _b, _c;
460
- if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
461
- return getCookie(preview, globalThis.document.cookie);
462
- } else if ((_c = (_b = this.refMode.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
463
- return getCookie(preview, this.refMode.httpRequest.headers.cookie);
464
- }
465
- }
466
- async getResolvedRefString() {
467
- if (this.refMode.autoPreviewsEnabled) {
468
- const previewRef = this.getPreviewRefString();
469
- if (previewRef) {
470
- return previewRef;
471
- }
472
- }
473
- switch (this.refMode.type) {
474
- case 1: {
475
- const releaseId = this.refMode.payload.releaseId;
476
- const repository = await this.getCachedRepository();
477
- const ref = findRef(repository.refs, (ref2) => ref2.id === releaseId);
478
- return ref.ref;
479
- }
480
- case 2: {
481
- const releaseLabel = this.refMode.payload.releaseLabel;
482
- const repository = await this.getCachedRepository();
483
- const ref = findRef(repository.refs, (ref2) => ref2.label === releaseLabel);
484
- return ref.ref;
485
- }
486
- case 3: {
487
- const thisRefStringOrFn = this.refMode.payload.refStringOrFn;
488
- if (typeof thisRefStringOrFn === "function") {
489
- const res = await thisRefStringOrFn();
490
- if (typeof res === "string") {
491
- return res;
492
- }
493
- } else if (thisRefStringOrFn) {
494
- return thisRefStringOrFn;
495
- }
496
- }
497
- case 0:
498
- default: {
499
- const repository = await this.getCachedRepository();
500
- const ref = findRef(repository.refs, (ref2) => ref2.isMasterRef);
501
- return ref.ref;
502
- }
503
- }
504
- }
505
- async fetch(url) {
506
- const res = await this.fetchFn(url);
507
- let json;
508
- try {
509
- json = await res.json();
510
- } catch (e) {
511
- throw new PrismicError(void 0, { url });
512
- }
513
- switch (res.status) {
514
- case 200: {
515
- return json;
516
- }
517
- case 400: {
518
- if (isParsingErrorAPIResponse(json)) {
519
- throw new ParsingError(json.message, {
520
- url,
521
- response: json
522
- });
523
- }
524
- break;
525
- }
526
- case 401:
527
- case 403: {
528
- if (isForbiddenErrorAPIResponse(json)) {
529
- throw new ForbiddenError("error" in json ? json.error : json.message, {
530
- url,
531
- response: json
532
- });
533
- }
534
- }
535
- }
536
- throw new PrismicError(void 0, { url, response: json });
537
- }
538
- }
539
-
540
- export { Client, ForbiddenError, ParsingError, PrismicError, buildQueryURL, cookie, createClient, getEndpoint, predicate };