@prismicio/client 5.0.0-alpha.0 → 5.1.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.es.js DELETED
@@ -1,397 +0,0 @@
1
- const getEndpoint = (repositoryName) => `https://${repositoryName}.cdn.prismic.io/api/v2`;
2
-
3
- const castArray = (a) => Array.isArray(a) ? a : [a];
4
-
5
- const RENAMED_PARAMS = {
6
- accessToken: "access_token"
7
- };
8
- const castOrderingToString = (ordering) => typeof ordering === "string" ? ordering : [
9
- ordering.field,
10
- ordering.direction === "desc" ? ordering.direction : void 0
11
- ].filter(Boolean).join(" ");
12
- const buildQueryURL = (endpoint, args) => {
13
- var _a;
14
- const {ref, predicates, ...params} = args;
15
- const url = new URL(`documents/search`, `${endpoint}/`);
16
- url.searchParams.set("ref", ref);
17
- if (predicates) {
18
- for (const predicate of castArray(predicates)) {
19
- url.searchParams.append("q", `[${predicate}]`);
20
- }
21
- }
22
- for (const k in params) {
23
- const name = (_a = RENAMED_PARAMS[k]) != null ? _a : k;
24
- let value = params[k];
25
- if (name === "orderings") {
26
- const scopedValue = params[name];
27
- if (scopedValue != null) {
28
- const v = castArray(scopedValue).map((ordering) => castOrderingToString(ordering)).join(",");
29
- value = `[${v}]`;
30
- }
31
- }
32
- if (value != null) {
33
- url.searchParams.set(name, castArray(value).join(","));
34
- }
35
- }
36
- return url.toString();
37
- };
38
-
39
- const appendPredicates = (...predicates) => (objWithPredicates = {}) => ({
40
- ...objWithPredicates,
41
- predicates: [objWithPredicates.predicates || [], ...predicates].flat()
42
- });
43
-
44
- const readValue = (value) => {
45
- return value.replace(/%3B/g, ";");
46
- };
47
- const parse = (cookieString) => {
48
- const result = {};
49
- const cookies = cookieString.split("; ");
50
- for (const cookie of cookies) {
51
- const parts = cookie.split("=");
52
- const value = parts.slice(1).join("=");
53
- const name = readValue(parts[0]).replace(/%3D/g, "=");
54
- result[name] = readValue(value);
55
- }
56
- return result;
57
- };
58
- const getAll = (cookieStore) => parse(cookieStore);
59
- const getCookie = (name, cookieStore) => getAll(cookieStore)[name];
60
-
61
- class HTTPError extends Error {
62
- constructor(reason, response, url, options) {
63
- super(reason || `Network request failed with status code ${response.status}`);
64
- this.url = url;
65
- this.options = options;
66
- this.response = response;
67
- }
68
- }
69
-
70
- const preview = "io.prismic.preview";
71
-
72
- var cookie = /*#__PURE__*/Object.freeze({
73
- __proto__: null,
74
- preview: preview
75
- });
76
-
77
- const formatValue = (value) => {
78
- if (Array.isArray(value)) {
79
- return `[${value.map(formatValue).join(", ")}]`;
80
- }
81
- if (typeof value === "string") {
82
- return `"${value}"`;
83
- }
84
- if (value instanceof Date) {
85
- return `${value.getTime()}`;
86
- }
87
- return `${value}`;
88
- };
89
- const pathWithArgsPredicate = (name) => {
90
- const fn = (path, ...args) => {
91
- const formattedArgs = args.map(formatValue).join(", ");
92
- const joiner = path && args.length ? ", " : "";
93
- return `[${name}(${path}${joiner}${formattedArgs})]`;
94
- };
95
- return fn;
96
- };
97
- const pathPredicate = (name) => {
98
- const predicateFn = pathWithArgsPredicate(name);
99
- const fn = (path) => {
100
- return predicateFn(path);
101
- };
102
- return fn;
103
- };
104
- const argsPredicate = (name) => {
105
- const predicateFn = pathWithArgsPredicate(name);
106
- const fn = (...args) => {
107
- return predicateFn("", ...args);
108
- };
109
- return fn;
110
- };
111
- const at = pathWithArgsPredicate("at");
112
- const not = pathWithArgsPredicate("not");
113
- const any = pathWithArgsPredicate("any");
114
- const _in = pathWithArgsPredicate("in");
115
- const fulltext = pathWithArgsPredicate("fulltext");
116
- const has = pathPredicate("has");
117
- const missing = pathPredicate("missing");
118
- const similar = argsPredicate("similar");
119
- const geopointNear = pathWithArgsPredicate("geopoint.near");
120
- const numberLessThan = pathWithArgsPredicate("number.lt");
121
- const numberGreaterThan = pathWithArgsPredicate("number.gt");
122
- const numberInRange = pathWithArgsPredicate("number.inRange");
123
- const dateAfter = pathWithArgsPredicate("date.after");
124
- const dateBefore = pathWithArgsPredicate("date.before");
125
- const dateBetween = pathWithArgsPredicate("date.between");
126
- const dateDayOfMonth = pathWithArgsPredicate("date.day-of-month");
127
- const dateDayOfMonthAfter = pathWithArgsPredicate("date.day-of-month-after");
128
- const dateDayOfMonthBefore = pathWithArgsPredicate("date.day-of-month-before");
129
- const dateDayOfWeek = pathWithArgsPredicate("date.day-of-week");
130
- const dateDayOfWeekAfter = pathWithArgsPredicate("date.day-of-week-after");
131
- const dateDayOfWeekBefore = pathWithArgsPredicate("date.day-of-week-before");
132
- const dateMonth = pathWithArgsPredicate("date.month");
133
- const dateMonthAfter = pathWithArgsPredicate("date.month-after");
134
- const dateMonthBefore = pathWithArgsPredicate("date.month-before");
135
- const dateYear = pathWithArgsPredicate("date.year");
136
- const dateHour = pathWithArgsPredicate("date.hour");
137
- const dateHourAfter = pathWithArgsPredicate("date.hour-after");
138
- const dateHourBefore = pathWithArgsPredicate("date.hour-before");
139
-
140
- var predicate = /*#__PURE__*/Object.freeze({
141
- __proto__: null,
142
- at: at,
143
- not: not,
144
- any: any,
145
- 'in': _in,
146
- fulltext: fulltext,
147
- has: has,
148
- missing: missing,
149
- similar: similar,
150
- geopointNear: geopointNear,
151
- numberLessThan: numberLessThan,
152
- numberGreaterThan: numberGreaterThan,
153
- numberInRange: numberInRange,
154
- dateAfter: dateAfter,
155
- dateBefore: dateBefore,
156
- dateBetween: dateBetween,
157
- dateDayOfMonth: dateDayOfMonth,
158
- dateDayOfMonthAfter: dateDayOfMonthAfter,
159
- dateDayOfMonthBefore: dateDayOfMonthBefore,
160
- dateDayOfWeek: dateDayOfWeek,
161
- dateDayOfWeekAfter: dateDayOfWeekAfter,
162
- dateDayOfWeekBefore: dateDayOfWeekBefore,
163
- dateMonth: dateMonth,
164
- dateMonthAfter: dateMonthAfter,
165
- dateMonthBefore: dateMonthBefore,
166
- dateYear: dateYear,
167
- dateHour: dateHour,
168
- dateHourAfter: dateHourAfter,
169
- dateHourBefore: dateHourBefore
170
- });
171
-
172
- const MAX_PAGE_SIZE = 100;
173
- const typePredicate = (documentType) => at("document.type", documentType);
174
- const tagsPredicate = (tags) => at("document.tags", tags);
175
- const findRef = (refs, predicate2) => {
176
- const ref = refs.find((ref2) => predicate2(ref2));
177
- if (!ref) {
178
- throw new Error("Ref could not be found.");
179
- }
180
- return ref;
181
- };
182
- const createClient = (...args) => new Client(...args);
183
- class Client {
184
- constructor(endpoint, options = {}) {
185
- this.query = this.get.bind(this);
186
- this.endpoint = endpoint;
187
- this.accessToken = options.accessToken;
188
- this.ref = options.ref;
189
- this.defaultParams = options.defaultParams;
190
- this.autoPreviewsEnabled = true;
191
- if (options.fetch) {
192
- this.fetchFn = options.fetch;
193
- } else if (typeof globalThis.fetch === "function") {
194
- this.fetchFn = globalThis.fetch;
195
- } else {
196
- throw new Error("A 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.");
197
- }
198
- }
199
- enableAutoPreviews() {
200
- this.autoPreviewsEnabled = true;
201
- }
202
- enableAutoPreviewsFromReq(req) {
203
- this.httpRequest = req;
204
- this.autoPreviewsEnabled = true;
205
- }
206
- disableAutoPreviews() {
207
- this.autoPreviewsEnabled = false;
208
- }
209
- async get(params) {
210
- const url = await this.buildQueryURL(params);
211
- return await this.fetch(url, params);
212
- }
213
- async getFirst(params) {
214
- const result = await this.get(params);
215
- const firstResult = result.results[0];
216
- if (firstResult) {
217
- return firstResult;
218
- }
219
- throw new Error("No documents were returned");
220
- }
221
- async getAll(params = {}) {
222
- const {limit = Infinity, ...actualParams} = params;
223
- const resolvedParams = {pageSize: MAX_PAGE_SIZE, ...actualParams};
224
- const result = await this.get(resolvedParams);
225
- let page = result.page;
226
- let documents = result.results;
227
- while (page < result.total_pages && documents.length < limit) {
228
- page += 1;
229
- const result2 = await this.get({...resolvedParams, page});
230
- documents = [...documents, ...result2.results];
231
- }
232
- return documents.slice(0, limit);
233
- }
234
- async getByID(id, params) {
235
- return await this.getFirst(appendPredicates(at("document.id", id))(params));
236
- }
237
- async getByIDs(ids, params) {
238
- return await this.get(appendPredicates(at("document.id", ids))(params));
239
- }
240
- async getAllByIDs(ids, params) {
241
- return await this.getAll(appendPredicates(at("document.id", ids))(params));
242
- }
243
- async getByUID(documentType, uid, params) {
244
- return await this.getFirst(appendPredicates(typePredicate(documentType), at(`my.${documentType}.uid`, uid))(params));
245
- }
246
- async getSingle(documentType, params) {
247
- return await this.getFirst(appendPredicates(typePredicate(documentType))(params));
248
- }
249
- async getByType(documentType, params) {
250
- return await this.get(appendPredicates(typePredicate(documentType))(params));
251
- }
252
- async getAllByType(documentType, params) {
253
- return await this.getAll(appendPredicates(typePredicate(documentType))(params));
254
- }
255
- async getByTag(tag, params) {
256
- return await this.get(appendPredicates(tagsPredicate(tag))(params));
257
- }
258
- async getAllByTag(tag, params) {
259
- return await this.getAll(appendPredicates(tagsPredicate(tag))(params));
260
- }
261
- async getByTags(tags, params) {
262
- return await this.get(appendPredicates(tagsPredicate(tags))(params));
263
- }
264
- async getAllByTags(tags, params) {
265
- return await this.getAll(appendPredicates(tagsPredicate(tags))(params));
266
- }
267
- async getRefs() {
268
- const res = await this.fetch(this.endpoint);
269
- return res.refs;
270
- }
271
- async getRefById(id) {
272
- const refs = await this.getRefs();
273
- return findRef(refs, (ref) => ref.id === id);
274
- }
275
- async getRefByLabel(label) {
276
- const refs = await this.getRefs();
277
- return findRef(refs, (ref) => ref.label === label);
278
- }
279
- async getMasterRef() {
280
- const refs = await this.getRefs();
281
- return findRef(refs, (ref) => ref.isMasterRef);
282
- }
283
- async getReleases() {
284
- const refs = await this.getRefs();
285
- return refs.filter((ref) => !ref.isMasterRef);
286
- }
287
- async getReleaseById(id) {
288
- const releases = await this.getReleases();
289
- return findRef(releases, (ref) => ref.id === id);
290
- }
291
- async getReleaseByLabel(label) {
292
- const releases = await this.getReleases();
293
- return findRef(releases, (ref) => ref.label === label);
294
- }
295
- async getTags() {
296
- const res = await this.fetch(this.endpoint);
297
- return res.tags;
298
- }
299
- async buildQueryURL(params = {}) {
300
- const {
301
- ref = await this.getResolvedRefString(),
302
- accessToken: _accessToken,
303
- ...actualParams
304
- } = params;
305
- return buildQueryURL(this.endpoint, {
306
- ...this.defaultParams,
307
- ...actualParams,
308
- ref
309
- });
310
- }
311
- async resolvePreviewUrl(args) {
312
- var _a;
313
- let documentId = args.documentId;
314
- let previewToken = args.previewToken;
315
- if (typeof globalThis.location !== "undefined") {
316
- const searchParams = new URLSearchParams(globalThis.location.search);
317
- documentId = documentId || searchParams.get("documentId") || void 0;
318
- previewToken = previewToken || searchParams.get("token") || void 0;
319
- } else if ((_a = this.httpRequest) == null ? void 0 : _a.query) {
320
- if (typeof this.httpRequest.query.documentId === "string") {
321
- documentId = documentId || this.httpRequest.query.documentId;
322
- }
323
- if (typeof this.httpRequest.query.token === "string") {
324
- previewToken = previewToken || this.httpRequest.query.token;
325
- }
326
- }
327
- if (documentId != null) {
328
- const document = await this.getByID(documentId, {
329
- ref: previewToken
330
- });
331
- return args.linkResolver(document);
332
- } else {
333
- return args.defaultUrl;
334
- }
335
- }
336
- async queryCurrentContent() {
337
- const masterRef = await this.getMasterRef();
338
- this.ref = masterRef.ref;
339
- return masterRef;
340
- }
341
- async queryContentFromReleaseByID(id) {
342
- const releaseRef = await this.getReleaseById(id);
343
- this.ref = releaseRef.ref;
344
- return releaseRef;
345
- }
346
- async queryContentFromReleaseByLabel(label) {
347
- const releaseRef = await this.getReleaseByLabel(label);
348
- this.ref = releaseRef.ref;
349
- return releaseRef;
350
- }
351
- getPreviewRefString() {
352
- var _a, _b, _c;
353
- if ((_a = globalThis.document) == null ? void 0 : _a.cookie) {
354
- return getCookie(preview, globalThis.document.cookie);
355
- } else if ((_c = (_b = this.httpRequest) == null ? void 0 : _b.headers) == null ? void 0 : _c.cookie) {
356
- return getCookie(preview, this.httpRequest.headers.cookie);
357
- }
358
- }
359
- async getResolvedRefString() {
360
- if (this.autoPreviewsEnabled) {
361
- const previewRef = this.getPreviewRefString();
362
- if (previewRef) {
363
- return previewRef;
364
- }
365
- }
366
- const thisRefStringOrFn = this.ref;
367
- if (typeof thisRefStringOrFn === "function") {
368
- const res = await thisRefStringOrFn();
369
- if (typeof res === "string") {
370
- return res;
371
- }
372
- } else if (thisRefStringOrFn) {
373
- return thisRefStringOrFn;
374
- }
375
- const masterRef = await this.getMasterRef();
376
- this.ref = masterRef.ref;
377
- return masterRef.ref;
378
- }
379
- buildRequestOptions(params) {
380
- const accessToken = (params == null ? void 0 : params.accessToken) || this.accessToken;
381
- return accessToken ? {headers: {Authorization: `Token ${accessToken}`}} : {};
382
- }
383
- async fetch(url, params) {
384
- const options = this.buildRequestOptions(params);
385
- const rawRes = await this.fetchFn(url, options);
386
- const res = rawRes.clone();
387
- if (res.status === 200) {
388
- return await res.json();
389
- } else if (rawRes.status === 401) {
390
- throw new HTTPError("Invalid access token", rawRes, url, options);
391
- } else {
392
- throw new HTTPError(void 0, rawRes, url, options);
393
- }
394
- }
395
- }
396
-
397
- export { Client, HTTPError, buildQueryURL, cookie, createClient, getEndpoint, predicate };