@prismicio/client 5.1.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.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/cjs/@prismicio/client.js +1200 -1200
  3. package/cjs/@prismicio/client.js.map +1 -1
  4. package/cjs/@prismicio/client.min.js.map +1 -1
  5. package/esm/@prismicio/client.min.mjs.map +1 -1
  6. package/esm/@prismicio/client.mjs +1200 -1200
  7. package/esm/@prismicio/client.mjs.map +1 -1
  8. package/package.json +1 -1
  9. package/types/Api.d.ts +27 -27
  10. package/types/ApiSearchResponse.d.ts +11 -11
  11. package/types/Cookies.d.ts +9 -9
  12. package/types/HttpClient.d.ts +16 -16
  13. package/types/LazySearchForm.d.ts +24 -24
  14. package/types/Predicates.d.ts +58 -58
  15. package/types/PreviewResolver.d.ts +9 -9
  16. package/types/ResolvedApi.d.ts +126 -126
  17. package/types/SearchForm.d.ts +47 -47
  18. package/types/TagsForm.d.ts +7 -7
  19. package/types/cache.d.ts +17 -17
  20. package/types/client.d.ts +34 -34
  21. package/types/documents.d.ts +20 -20
  22. package/types/experiments.d.ts +22 -22
  23. package/types/form.d.ts +25 -25
  24. package/types/index.d.ts +129 -129
  25. package/types/lru.d.ts +25 -25
  26. package/types/request.d.ts +13 -13
  27. package/umd/@prismicio/client.js +1200 -1200
  28. package/umd/@prismicio/client.js.map +1 -1
  29. package/umd/@prismicio/client.min.js.map +1 -1
  30. package/cjs/prismic-javascript.js +0 -1282
  31. package/cjs/prismic-javascript.js.map +0 -1
  32. package/cjs/prismic-javascript.min.js +0 -16
  33. package/cjs/prismic-javascript.min.js.map +0 -1
  34. package/esm/prismic-javascript.min.mjs +0 -16
  35. package/esm/prismic-javascript.min.mjs.map +0 -1
  36. package/esm/prismic-javascript.mjs +0 -1278
  37. package/esm/prismic-javascript.mjs.map +0 -1
  38. package/umd/prismic-javascript.js +0 -1286
  39. package/umd/prismic-javascript.js.map +0 -1
  40. package/umd/prismic-javascript.min.js +0 -17
  41. package/umd/prismic-javascript.min.js.map +0 -1
@@ -40,1236 +40,1236 @@ var __assign = function() {
40
40
  return __assign.apply(this, arguments);
41
41
  };
42
42
 
43
- var Variation = /** @class */ (function () {
44
- function Variation(data) {
45
- this.data = {};
46
- this.data = data;
47
- }
48
- Variation.prototype.id = function () {
49
- return this.data.id;
50
- };
51
- Variation.prototype.ref = function () {
52
- return this.data.ref;
53
- };
54
- Variation.prototype.label = function () {
55
- return this.data.label;
56
- };
57
- return Variation;
58
- }());
59
- var Experiment = /** @class */ (function () {
60
- function Experiment(data) {
61
- this.data = {};
62
- this.data = data;
63
- this.variations = (data.variations || []).map(function (v) {
64
- return new Variation(v);
65
- });
66
- }
67
- Experiment.prototype.id = function () {
68
- return this.data.id;
69
- };
70
- Experiment.prototype.googleId = function () {
71
- return this.data.googleId;
72
- };
73
- Experiment.prototype.name = function () {
74
- return this.data.name;
75
- };
76
- return Experiment;
77
- }());
78
- var Experiments = /** @class */ (function () {
79
- function Experiments(data) {
80
- if (data) {
81
- this.drafts = (data.drafts || []).map(function (exp) {
82
- return new Experiment(exp);
83
- });
84
- this.running = (data.running || []).map(function (exp) {
85
- return new Experiment(exp);
86
- });
87
- }
88
- }
89
- Experiments.prototype.current = function () {
90
- if (this.running.length > 0) {
91
- return this.running[0];
92
- }
93
- else {
94
- return null;
95
- }
96
- };
97
- Experiments.prototype.refFromCookie = function (cookie) {
98
- if (!cookie || cookie.trim() === '')
99
- return null;
100
- var splitted = cookie.trim().split(' ');
101
- if (splitted.length < 2)
102
- return null;
103
- var expId = splitted[0];
104
- var varIndex = parseInt(splitted[1], 10);
105
- var exp = this.running.filter(function (exp) {
106
- return exp.googleId() === expId && exp.variations.length > varIndex;
107
- })[0];
108
- return exp ? exp.variations[varIndex].ref() : null;
109
- };
110
- return Experiments;
43
+ var Variation = /** @class */ (function () {
44
+ function Variation(data) {
45
+ this.data = {};
46
+ this.data = data;
47
+ }
48
+ Variation.prototype.id = function () {
49
+ return this.data.id;
50
+ };
51
+ Variation.prototype.ref = function () {
52
+ return this.data.ref;
53
+ };
54
+ Variation.prototype.label = function () {
55
+ return this.data.label;
56
+ };
57
+ return Variation;
58
+ }());
59
+ var Experiment = /** @class */ (function () {
60
+ function Experiment(data) {
61
+ this.data = {};
62
+ this.data = data;
63
+ this.variations = (data.variations || []).map(function (v) {
64
+ return new Variation(v);
65
+ });
66
+ }
67
+ Experiment.prototype.id = function () {
68
+ return this.data.id;
69
+ };
70
+ Experiment.prototype.googleId = function () {
71
+ return this.data.googleId;
72
+ };
73
+ Experiment.prototype.name = function () {
74
+ return this.data.name;
75
+ };
76
+ return Experiment;
77
+ }());
78
+ var Experiments = /** @class */ (function () {
79
+ function Experiments(data) {
80
+ if (data) {
81
+ this.drafts = (data.drafts || []).map(function (exp) {
82
+ return new Experiment(exp);
83
+ });
84
+ this.running = (data.running || []).map(function (exp) {
85
+ return new Experiment(exp);
86
+ });
87
+ }
88
+ }
89
+ Experiments.prototype.current = function () {
90
+ if (this.running.length > 0) {
91
+ return this.running[0];
92
+ }
93
+ else {
94
+ return null;
95
+ }
96
+ };
97
+ Experiments.prototype.refFromCookie = function (cookie) {
98
+ if (!cookie || cookie.trim() === '')
99
+ return null;
100
+ var splitted = cookie.trim().split(' ');
101
+ if (splitted.length < 2)
102
+ return null;
103
+ var expId = splitted[0];
104
+ var varIndex = parseInt(splitted[1], 10);
105
+ var exp = this.running.filter(function (exp) {
106
+ return exp.googleId() === expId && exp.variations.length > varIndex;
107
+ })[0];
108
+ return exp ? exp.variations[varIndex].ref() : null;
109
+ };
110
+ return Experiments;
111
111
  }());
112
112
 
113
- var Form = /** @class */ (function () {
114
- function Form(form, httpClient) {
115
- this.httpClient = httpClient;
116
- this.form = form;
117
- this.data = {};
118
- for (var field in form.fields) {
119
- if (form.fields[field]['default']) {
120
- this.data[field] = [form.fields[field]['default']];
121
- }
122
- }
123
- }
124
- Form.prototype.set = function (field, value) {
125
- var fieldDesc = this.form.fields[field];
126
- if (!fieldDesc)
127
- throw new Error('Unknown field ' + field);
128
- var checkedValue = value === '' || value === undefined ? null : value;
129
- var values = this.data[field] || [];
130
- if (fieldDesc.multiple) {
131
- values = checkedValue ? values.concat([checkedValue]) : values;
132
- }
133
- else {
134
- values = checkedValue ? [checkedValue] : values;
135
- }
136
- this.data[field] = values;
137
- };
138
- Form.prototype.url = function () {
139
- var url = this.form.action;
140
- if (this.data) {
141
- var sep = (url.indexOf('?') > -1 ? '&' : '?');
142
- for (var key in this.data) {
143
- if (Object.prototype.hasOwnProperty.call(this.data, key)) {
144
- var values = this.data[key];
145
- if (values) {
146
- for (var i = 0; i < values.length; i++) {
147
- url += sep + key + '=' + encodeURIComponent(values[i]);
148
- sep = '&';
149
- }
150
- }
151
- }
152
- }
153
- }
154
- return url;
155
- };
156
- /**
157
- * Submits the query, and calls the callback function.
158
- */
159
- Form.prototype.submit = function (cb) {
160
- return this.httpClient.cachedRequest(this.url()).then(function (response) {
161
- cb && cb(null, response);
162
- return response;
163
- }).catch(function (error) {
164
- cb && cb(error);
165
- throw error;
166
- });
167
- };
168
- return Form;
113
+ var Form = /** @class */ (function () {
114
+ function Form(form, httpClient) {
115
+ this.httpClient = httpClient;
116
+ this.form = form;
117
+ this.data = {};
118
+ for (var field in form.fields) {
119
+ if (form.fields[field]['default']) {
120
+ this.data[field] = [form.fields[field]['default']];
121
+ }
122
+ }
123
+ }
124
+ Form.prototype.set = function (field, value) {
125
+ var fieldDesc = this.form.fields[field];
126
+ if (!fieldDesc)
127
+ throw new Error('Unknown field ' + field);
128
+ var checkedValue = value === '' || value === undefined ? null : value;
129
+ var values = this.data[field] || [];
130
+ if (fieldDesc.multiple) {
131
+ values = checkedValue ? values.concat([checkedValue]) : values;
132
+ }
133
+ else {
134
+ values = checkedValue ? [checkedValue] : values;
135
+ }
136
+ this.data[field] = values;
137
+ };
138
+ Form.prototype.url = function () {
139
+ var url = this.form.action;
140
+ if (this.data) {
141
+ var sep = (url.indexOf('?') > -1 ? '&' : '?');
142
+ for (var key in this.data) {
143
+ if (Object.prototype.hasOwnProperty.call(this.data, key)) {
144
+ var values = this.data[key];
145
+ if (values) {
146
+ for (var i = 0; i < values.length; i++) {
147
+ url += sep + key + '=' + encodeURIComponent(values[i]);
148
+ sep = '&';
149
+ }
150
+ }
151
+ }
152
+ }
153
+ }
154
+ return url;
155
+ };
156
+ /**
157
+ * Submits the query, and calls the callback function.
158
+ */
159
+ Form.prototype.submit = function (cb) {
160
+ return this.httpClient.cachedRequest(this.url()).then(function (response) {
161
+ cb && cb(null, response);
162
+ return response;
163
+ }).catch(function (error) {
164
+ cb && cb(error);
165
+ throw error;
166
+ });
167
+ };
168
+ return Form;
169
169
  }());
170
170
 
171
- var SearchForm = /** @class */ (function (_super) {
172
- __extends(SearchForm, _super);
173
- function SearchForm(form, httpClient) {
174
- return _super.call(this, form, httpClient) || this;
175
- }
176
- SearchForm.prototype.set = function (field, value) {
177
- _super.prototype.set.call(this, field, value);
178
- return this;
179
- };
180
- /**
181
- * Sets a ref to query on for this SearchForm. This is a mandatory
182
- * method to call before calling submit(), and api.form('everything').submit()
183
- * will not work.
184
- */
185
- SearchForm.prototype.ref = function (ref) {
186
- return this.set('ref', ref);
187
- };
188
- /**
189
- * Sets a predicate-based query for this SearchForm. This is where you
190
- * paste what you compose in your prismic.io API browser.
191
- */
192
- SearchForm.prototype.query = function (query) {
193
- if (typeof query === 'string') {
194
- return this.query([query]);
195
- }
196
- else if (Array.isArray(query)) {
197
- return this.set('q', "[" + query.join('') + "]");
198
- }
199
- else {
200
- throw new Error("Invalid query : " + query);
201
- }
202
- };
203
- /**
204
- * Sets a page size to query for this SearchForm. This is an optional method.
205
- *
206
- * @param {number} size - The page size
207
- * @returns {SearchForm} - The SearchForm itself
208
- */
209
- SearchForm.prototype.pageSize = function (size) {
210
- return this.set('pageSize', size);
211
- };
212
- /**
213
- * Sets the graphquery to query for this SearchForm. This is an optional method.
214
- */
215
- SearchForm.prototype.graphQuery = function (query) {
216
- return this.set('graphQuery', query);
217
- };
218
- /**
219
- * Sets the language to query for this SearchForm. This is an optional method.
220
- */
221
- SearchForm.prototype.lang = function (langCode) {
222
- return this.set('lang', langCode);
223
- };
224
- /**
225
- * Sets the page number to query for this SearchForm. This is an optional method.
226
- */
227
- SearchForm.prototype.page = function (p) {
228
- return this.set('page', p);
229
- };
230
- /**
231
- * Remove all the documents except for those after the specified document in the list. This is an optional method.
232
- */
233
- SearchForm.prototype.after = function (documentId) {
234
- return this.set('after', documentId);
235
- };
236
- /**
237
- * Sets the orderings to query for this SearchForm. This is an optional method.
238
- */
239
- SearchForm.prototype.orderings = function (orderings) {
240
- if (!orderings) {
241
- return this;
242
- }
243
- else {
244
- return this.set('orderings', "[" + orderings.join(',') + "]");
245
- }
246
- };
247
- return SearchForm;
171
+ var SearchForm = /** @class */ (function (_super) {
172
+ __extends(SearchForm, _super);
173
+ function SearchForm(form, httpClient) {
174
+ return _super.call(this, form, httpClient) || this;
175
+ }
176
+ SearchForm.prototype.set = function (field, value) {
177
+ _super.prototype.set.call(this, field, value);
178
+ return this;
179
+ };
180
+ /**
181
+ * Sets a ref to query on for this SearchForm. This is a mandatory
182
+ * method to call before calling submit(), and api.form('everything').submit()
183
+ * will not work.
184
+ */
185
+ SearchForm.prototype.ref = function (ref) {
186
+ return this.set('ref', ref);
187
+ };
188
+ /**
189
+ * Sets a predicate-based query for this SearchForm. This is where you
190
+ * paste what you compose in your prismic.io API browser.
191
+ */
192
+ SearchForm.prototype.query = function (query) {
193
+ if (typeof query === 'string') {
194
+ return this.query([query]);
195
+ }
196
+ else if (Array.isArray(query)) {
197
+ return this.set('q', "[" + query.join('') + "]");
198
+ }
199
+ else {
200
+ throw new Error("Invalid query : " + query);
201
+ }
202
+ };
203
+ /**
204
+ * Sets a page size to query for this SearchForm. This is an optional method.
205
+ *
206
+ * @param {number} size - The page size
207
+ * @returns {SearchForm} - The SearchForm itself
208
+ */
209
+ SearchForm.prototype.pageSize = function (size) {
210
+ return this.set('pageSize', size);
211
+ };
212
+ /**
213
+ * Sets the graphquery to query for this SearchForm. This is an optional method.
214
+ */
215
+ SearchForm.prototype.graphQuery = function (query) {
216
+ return this.set('graphQuery', query);
217
+ };
218
+ /**
219
+ * Sets the language to query for this SearchForm. This is an optional method.
220
+ */
221
+ SearchForm.prototype.lang = function (langCode) {
222
+ return this.set('lang', langCode);
223
+ };
224
+ /**
225
+ * Sets the page number to query for this SearchForm. This is an optional method.
226
+ */
227
+ SearchForm.prototype.page = function (p) {
228
+ return this.set('page', p);
229
+ };
230
+ /**
231
+ * Remove all the documents except for those after the specified document in the list. This is an optional method.
232
+ */
233
+ SearchForm.prototype.after = function (documentId) {
234
+ return this.set('after', documentId);
235
+ };
236
+ /**
237
+ * Sets the orderings to query for this SearchForm. This is an optional method.
238
+ */
239
+ SearchForm.prototype.orderings = function (orderings) {
240
+ if (!orderings) {
241
+ return this;
242
+ }
243
+ else {
244
+ return this.set('orderings', "[" + orderings.join(',') + "]");
245
+ }
246
+ };
247
+ return SearchForm;
248
248
  }(Form));
249
249
 
250
- var TagsForm = /** @class */ (function (_super) {
251
- __extends(TagsForm, _super);
252
- function TagsForm(form, httpClient) {
253
- return _super.call(this, form, httpClient) || this;
254
- }
255
- return TagsForm;
250
+ var TagsForm = /** @class */ (function (_super) {
251
+ __extends(TagsForm, _super);
252
+ function TagsForm(form, httpClient) {
253
+ return _super.call(this, form, httpClient) || this;
254
+ }
255
+ return TagsForm;
256
256
  }(Form));
257
257
 
258
- var OPERATOR = {
259
- at: 'at',
260
- not: 'not',
261
- missing: 'missing',
262
- has: 'has',
263
- any: 'any',
264
- in: 'in',
265
- fulltext: 'fulltext',
266
- similar: 'similar',
267
- numberGt: 'number.gt',
268
- numberLt: 'number.lt',
269
- numberInRange: 'number.inRange',
270
- dateBefore: 'date.before',
271
- dateAfter: 'date.after',
272
- dateBetween: 'date.between',
273
- dateDayOfMonth: 'date.day-of-month',
274
- dateDayOfMonthAfter: 'date.day-of-month-after',
275
- dateDayOfMonthBefore: 'date.day-of-month-before',
276
- dateDayOfWeek: 'date.day-of-week',
277
- dateDayOfWeekAfter: 'date.day-of-week-after',
278
- dateDayOfWeekBefore: 'date.day-of-week-before',
279
- dateMonth: 'date.month',
280
- dateMonthBefore: 'date.month-before',
281
- dateMonthAfter: 'date.month-after',
282
- dateYear: 'date.year',
283
- dateHour: 'date.hour',
284
- dateHourBefore: 'date.hour-before',
285
- dateHourAfter: 'date.hour-after',
286
- GeopointNear: 'geopoint.near',
287
- };
288
- function encode(value) {
289
- if (typeof value === 'string') {
290
- return "\"" + value + "\"";
291
- }
292
- else if (typeof value === 'number') {
293
- return value.toString();
294
- }
295
- else if (value instanceof Date) {
296
- return value.getTime().toString();
297
- }
298
- else if (Array.isArray(value)) {
299
- return "[" + value.map(function (v) { return encode(v); }).join(',') + "]";
300
- }
301
- else if (typeof value === "boolean") {
302
- return value.toString();
303
- }
304
- else {
305
- throw new Error("Unable to encode " + value + " of type " + typeof value);
306
- }
307
- }
308
- var geopoint = {
309
- near: function (fragment, latitude, longitude, radius) {
310
- return "[" + OPERATOR.GeopointNear + "(" + fragment + ", " + latitude + ", " + longitude + ", " + radius + ")]";
311
- },
312
- };
313
- var date = {
314
- before: function (fragment, before) {
315
- return "[" + OPERATOR.dateBefore + "(" + fragment + ", " + encode(before) + ")]";
316
- },
317
- after: function (fragment, after) {
318
- return "[" + OPERATOR.dateAfter + "(" + fragment + ", " + encode(after) + ")]";
319
- },
320
- between: function (fragment, before, after) {
321
- return "[" + OPERATOR.dateBetween + "(" + fragment + ", " + encode(before) + ", " + encode(after) + ")]";
322
- },
323
- dayOfMonth: function (fragment, day) {
324
- return "[" + OPERATOR.dateDayOfMonth + "(" + fragment + ", " + day + ")]";
325
- },
326
- dayOfMonthAfter: function (fragment, day) {
327
- return "[" + OPERATOR.dateDayOfMonthAfter + "(" + fragment + ", " + day + ")]";
328
- },
329
- dayOfMonthBefore: function (fragment, day) {
330
- return "[" + OPERATOR.dateDayOfMonthBefore + "(" + fragment + ", " + day + ")]";
331
- },
332
- dayOfWeek: function (fragment, day) {
333
- return "[" + OPERATOR.dateDayOfWeek + "(" + fragment + ", " + encode(day) + ")]";
334
- },
335
- dayOfWeekAfter: function (fragment, day) {
336
- return "[" + OPERATOR.dateDayOfWeekAfter + "(" + fragment + ", " + encode(day) + ")]";
337
- },
338
- dayOfWeekBefore: function (fragment, day) {
339
- return "[" + OPERATOR.dateDayOfWeekBefore + "(" + fragment + ", " + encode(day) + ")]";
340
- },
341
- month: function (fragment, month) {
342
- return "[" + OPERATOR.dateMonth + "(" + fragment + ", " + encode(month) + ")]";
343
- },
344
- monthBefore: function (fragment, month) {
345
- return "[" + OPERATOR.dateMonthBefore + "(" + fragment + ", " + encode(month) + ")]";
346
- },
347
- monthAfter: function (fragment, month) {
348
- return "[" + OPERATOR.dateMonthAfter + "(" + fragment + ", " + encode(month) + ")]";
349
- },
350
- year: function (fragment, year) {
351
- return "[" + OPERATOR.dateYear + "(" + fragment + ", " + year + ")]";
352
- },
353
- hour: function (fragment, hour) {
354
- return "[" + OPERATOR.dateHour + "(" + fragment + ", " + hour + ")]";
355
- },
356
- hourBefore: function (fragment, hour) {
357
- return "[" + OPERATOR.dateHourBefore + "(" + fragment + ", " + hour + ")]";
358
- },
359
- hourAfter: function (fragment, hour) {
360
- return "[" + OPERATOR.dateHourAfter + "(" + fragment + ", " + hour + ")]";
361
- },
362
- };
363
- var number = {
364
- gt: function (fragment, value) {
365
- return "[" + OPERATOR.numberGt + "(" + fragment + ", " + value + ")]";
366
- },
367
- lt: function (fragment, value) {
368
- return "[" + OPERATOR.numberLt + "(" + fragment + ", " + value + ")]";
369
- },
370
- inRange: function (fragment, before, after) {
371
- return "[" + OPERATOR.numberInRange + "(" + fragment + ", " + before + ", " + after + ")]";
372
- },
373
- };
374
- var Predicates = {
375
- at: function (fragment, value) {
376
- return "[" + OPERATOR.at + "(" + fragment + ", " + encode(value) + ")]";
377
- },
378
- not: function (fragment, value) {
379
- return "[" + OPERATOR.not + "(" + fragment + ", " + encode(value) + ")]";
380
- },
381
- missing: function (fragment) {
382
- return "[" + OPERATOR.missing + "(" + fragment + ")]";
383
- },
384
- has: function (fragment) {
385
- return "[" + OPERATOR.has + "(" + fragment + ")]";
386
- },
387
- any: function (fragment, values) {
388
- return "[" + OPERATOR.any + "(" + fragment + ", " + encode(values) + ")]";
389
- },
390
- in: function (fragment, values) {
391
- return "[" + OPERATOR.in + "(" + fragment + ", " + encode(values) + ")]";
392
- },
393
- fulltext: function (fragment, value) {
394
- return "[" + OPERATOR.fulltext + "(" + fragment + ", " + encode(value) + ")]";
395
- },
396
- similar: function (documentId, maxResults) {
397
- return "[" + OPERATOR.similar + "(\"" + documentId + "\", " + maxResults + ")]";
398
- },
399
- date: date,
400
- dateBefore: date.before,
401
- dateAfter: date.after,
402
- dateBetween: date.between,
403
- dayOfMonth: date.dayOfMonth,
404
- dayOfMonthAfter: date.dayOfMonthAfter,
405
- dayOfMonthBefore: date.dayOfMonthBefore,
406
- dayOfWeek: date.dayOfWeek,
407
- dayOfWeekAfter: date.dayOfWeekAfter,
408
- dayOfWeekBefore: date.dayOfWeekBefore,
409
- month: date.month,
410
- monthBefore: date.monthBefore,
411
- monthAfter: date.monthAfter,
412
- year: date.year,
413
- hour: date.hour,
414
- hourBefore: date.hourBefore,
415
- hourAfter: date.hourAfter,
416
- number: number,
417
- gt: number.gt,
418
- lt: number.lt,
419
- inRange: number.inRange,
420
- near: geopoint.near,
421
- geopoint: geopoint,
258
+ var OPERATOR = {
259
+ at: 'at',
260
+ not: 'not',
261
+ missing: 'missing',
262
+ has: 'has',
263
+ any: 'any',
264
+ in: 'in',
265
+ fulltext: 'fulltext',
266
+ similar: 'similar',
267
+ numberGt: 'number.gt',
268
+ numberLt: 'number.lt',
269
+ numberInRange: 'number.inRange',
270
+ dateBefore: 'date.before',
271
+ dateAfter: 'date.after',
272
+ dateBetween: 'date.between',
273
+ dateDayOfMonth: 'date.day-of-month',
274
+ dateDayOfMonthAfter: 'date.day-of-month-after',
275
+ dateDayOfMonthBefore: 'date.day-of-month-before',
276
+ dateDayOfWeek: 'date.day-of-week',
277
+ dateDayOfWeekAfter: 'date.day-of-week-after',
278
+ dateDayOfWeekBefore: 'date.day-of-week-before',
279
+ dateMonth: 'date.month',
280
+ dateMonthBefore: 'date.month-before',
281
+ dateMonthAfter: 'date.month-after',
282
+ dateYear: 'date.year',
283
+ dateHour: 'date.hour',
284
+ dateHourBefore: 'date.hour-before',
285
+ dateHourAfter: 'date.hour-after',
286
+ GeopointNear: 'geopoint.near',
287
+ };
288
+ function encode(value) {
289
+ if (typeof value === 'string') {
290
+ return "\"" + value + "\"";
291
+ }
292
+ else if (typeof value === 'number') {
293
+ return value.toString();
294
+ }
295
+ else if (value instanceof Date) {
296
+ return value.getTime().toString();
297
+ }
298
+ else if (Array.isArray(value)) {
299
+ return "[" + value.map(function (v) { return encode(v); }).join(',') + "]";
300
+ }
301
+ else if (typeof value === "boolean") {
302
+ return value.toString();
303
+ }
304
+ else {
305
+ throw new Error("Unable to encode " + value + " of type " + typeof value);
306
+ }
307
+ }
308
+ var geopoint = {
309
+ near: function (fragment, latitude, longitude, radius) {
310
+ return "[" + OPERATOR.GeopointNear + "(" + fragment + ", " + latitude + ", " + longitude + ", " + radius + ")]";
311
+ },
312
+ };
313
+ var date = {
314
+ before: function (fragment, before) {
315
+ return "[" + OPERATOR.dateBefore + "(" + fragment + ", " + encode(before) + ")]";
316
+ },
317
+ after: function (fragment, after) {
318
+ return "[" + OPERATOR.dateAfter + "(" + fragment + ", " + encode(after) + ")]";
319
+ },
320
+ between: function (fragment, before, after) {
321
+ return "[" + OPERATOR.dateBetween + "(" + fragment + ", " + encode(before) + ", " + encode(after) + ")]";
322
+ },
323
+ dayOfMonth: function (fragment, day) {
324
+ return "[" + OPERATOR.dateDayOfMonth + "(" + fragment + ", " + day + ")]";
325
+ },
326
+ dayOfMonthAfter: function (fragment, day) {
327
+ return "[" + OPERATOR.dateDayOfMonthAfter + "(" + fragment + ", " + day + ")]";
328
+ },
329
+ dayOfMonthBefore: function (fragment, day) {
330
+ return "[" + OPERATOR.dateDayOfMonthBefore + "(" + fragment + ", " + day + ")]";
331
+ },
332
+ dayOfWeek: function (fragment, day) {
333
+ return "[" + OPERATOR.dateDayOfWeek + "(" + fragment + ", " + encode(day) + ")]";
334
+ },
335
+ dayOfWeekAfter: function (fragment, day) {
336
+ return "[" + OPERATOR.dateDayOfWeekAfter + "(" + fragment + ", " + encode(day) + ")]";
337
+ },
338
+ dayOfWeekBefore: function (fragment, day) {
339
+ return "[" + OPERATOR.dateDayOfWeekBefore + "(" + fragment + ", " + encode(day) + ")]";
340
+ },
341
+ month: function (fragment, month) {
342
+ return "[" + OPERATOR.dateMonth + "(" + fragment + ", " + encode(month) + ")]";
343
+ },
344
+ monthBefore: function (fragment, month) {
345
+ return "[" + OPERATOR.dateMonthBefore + "(" + fragment + ", " + encode(month) + ")]";
346
+ },
347
+ monthAfter: function (fragment, month) {
348
+ return "[" + OPERATOR.dateMonthAfter + "(" + fragment + ", " + encode(month) + ")]";
349
+ },
350
+ year: function (fragment, year) {
351
+ return "[" + OPERATOR.dateYear + "(" + fragment + ", " + year + ")]";
352
+ },
353
+ hour: function (fragment, hour) {
354
+ return "[" + OPERATOR.dateHour + "(" + fragment + ", " + hour + ")]";
355
+ },
356
+ hourBefore: function (fragment, hour) {
357
+ return "[" + OPERATOR.dateHourBefore + "(" + fragment + ", " + hour + ")]";
358
+ },
359
+ hourAfter: function (fragment, hour) {
360
+ return "[" + OPERATOR.dateHourAfter + "(" + fragment + ", " + hour + ")]";
361
+ },
362
+ };
363
+ var number = {
364
+ gt: function (fragment, value) {
365
+ return "[" + OPERATOR.numberGt + "(" + fragment + ", " + value + ")]";
366
+ },
367
+ lt: function (fragment, value) {
368
+ return "[" + OPERATOR.numberLt + "(" + fragment + ", " + value + ")]";
369
+ },
370
+ inRange: function (fragment, before, after) {
371
+ return "[" + OPERATOR.numberInRange + "(" + fragment + ", " + before + ", " + after + ")]";
372
+ },
373
+ };
374
+ var Predicates = {
375
+ at: function (fragment, value) {
376
+ return "[" + OPERATOR.at + "(" + fragment + ", " + encode(value) + ")]";
377
+ },
378
+ not: function (fragment, value) {
379
+ return "[" + OPERATOR.not + "(" + fragment + ", " + encode(value) + ")]";
380
+ },
381
+ missing: function (fragment) {
382
+ return "[" + OPERATOR.missing + "(" + fragment + ")]";
383
+ },
384
+ has: function (fragment) {
385
+ return "[" + OPERATOR.has + "(" + fragment + ")]";
386
+ },
387
+ any: function (fragment, values) {
388
+ return "[" + OPERATOR.any + "(" + fragment + ", " + encode(values) + ")]";
389
+ },
390
+ in: function (fragment, values) {
391
+ return "[" + OPERATOR.in + "(" + fragment + ", " + encode(values) + ")]";
392
+ },
393
+ fulltext: function (fragment, value) {
394
+ return "[" + OPERATOR.fulltext + "(" + fragment + ", " + encode(value) + ")]";
395
+ },
396
+ similar: function (documentId, maxResults) {
397
+ return "[" + OPERATOR.similar + "(\"" + documentId + "\", " + maxResults + ")]";
398
+ },
399
+ date: date,
400
+ dateBefore: date.before,
401
+ dateAfter: date.after,
402
+ dateBetween: date.between,
403
+ dayOfMonth: date.dayOfMonth,
404
+ dayOfMonthAfter: date.dayOfMonthAfter,
405
+ dayOfMonthBefore: date.dayOfMonthBefore,
406
+ dayOfWeek: date.dayOfWeek,
407
+ dayOfWeekAfter: date.dayOfWeekAfter,
408
+ dayOfWeekBefore: date.dayOfWeekBefore,
409
+ month: date.month,
410
+ monthBefore: date.monthBefore,
411
+ monthAfter: date.monthAfter,
412
+ year: date.year,
413
+ hour: date.hour,
414
+ hourBefore: date.hourBefore,
415
+ hourAfter: date.hourAfter,
416
+ number: number,
417
+ gt: number.gt,
418
+ lt: number.lt,
419
+ inRange: number.inRange,
420
+ near: geopoint.near,
421
+ geopoint: geopoint,
422
422
  };
423
423
 
424
- /* eslint-disable */
425
- // Some portions of code from https://github.com/jshttp/cookie
426
- var decode = decodeURIComponent;
427
- function tryDecode(str, decode) {
428
- try {
429
- return decode(str);
430
- }
431
- catch (e) {
432
- return str;
433
- }
434
- }
435
- function parse(str, options) {
436
- if (typeof str !== 'string') {
437
- throw new TypeError('argument str must be a string');
438
- }
439
- var obj = {};
440
- var opt = options || {};
441
- var pairs = str.split(/; */);
442
- var dec = opt.decode || decode;
443
- pairs.forEach(function (pair) {
444
- var eq_idx = pair.indexOf('=');
445
- // skip things that don't look like key=value
446
- if (eq_idx < 0) {
447
- return;
448
- }
449
- var key = pair.substr(0, eq_idx).trim();
450
- var val = pair.substr(++eq_idx, pair.length).trim();
451
- // quoted values
452
- if ('"' == val[0]) {
453
- val = val.slice(1, -1);
454
- }
455
- // only assign once
456
- if (undefined == obj[key]) {
457
- obj[key] = tryDecode(val, dec);
458
- }
459
- });
460
- return obj;
461
- }
424
+ /* eslint-disable */
425
+ // Some portions of code from https://github.com/jshttp/cookie
426
+ var decode = decodeURIComponent;
427
+ function tryDecode(str, decode) {
428
+ try {
429
+ return decode(str);
430
+ }
431
+ catch (e) {
432
+ return str;
433
+ }
434
+ }
435
+ function parse(str, options) {
436
+ if (typeof str !== 'string') {
437
+ throw new TypeError('argument str must be a string');
438
+ }
439
+ var obj = {};
440
+ var opt = options || {};
441
+ var pairs = str.split(/; */);
442
+ var dec = opt.decode || decode;
443
+ pairs.forEach(function (pair) {
444
+ var eq_idx = pair.indexOf('=');
445
+ // skip things that don't look like key=value
446
+ if (eq_idx < 0) {
447
+ return;
448
+ }
449
+ var key = pair.substr(0, eq_idx).trim();
450
+ var val = pair.substr(++eq_idx, pair.length).trim();
451
+ // quoted values
452
+ if ('"' == val[0]) {
453
+ val = val.slice(1, -1);
454
+ }
455
+ // only assign once
456
+ if (undefined == obj[key]) {
457
+ obj[key] = tryDecode(val, dec);
458
+ }
459
+ });
460
+ return obj;
461
+ }
462
462
  var Cookies = { parse: parse };
463
463
 
464
- function createPreviewResolver(token, documentId, getDocByID) {
465
- var resolve = function (linkResolver, defaultUrl, cb) {
466
- if (documentId && getDocByID) {
467
- return getDocByID(documentId, { ref: token }).then(function (document) {
468
- if (!document) {
469
- cb && cb(null, defaultUrl);
470
- return defaultUrl;
471
- }
472
- else {
473
- var url = (linkResolver && linkResolver(document)) || document.url || defaultUrl;
474
- cb && cb(null, url);
475
- return url;
476
- }
477
- });
478
- }
479
- else {
480
- return Promise.resolve(defaultUrl);
481
- }
482
- };
483
- return { token: token, documentId: documentId, resolve: resolve };
464
+ function createPreviewResolver(token, documentId, getDocByID) {
465
+ var resolve = function (linkResolver, defaultUrl, cb) {
466
+ if (documentId && getDocByID) {
467
+ return getDocByID(documentId, { ref: token }).then(function (document) {
468
+ if (!document) {
469
+ cb && cb(null, defaultUrl);
470
+ return defaultUrl;
471
+ }
472
+ else {
473
+ var url = (linkResolver && linkResolver(document)) || document.url || defaultUrl;
474
+ cb && cb(null, url);
475
+ return url;
476
+ }
477
+ });
478
+ }
479
+ else {
480
+ return Promise.resolve(defaultUrl);
481
+ }
482
+ };
483
+ return { token: token, documentId: documentId, resolve: resolve };
484
484
  }
485
485
 
486
- var PREVIEW_COOKIE = 'io.prismic.preview';
487
- var EXPERIMENT_COOKIE = 'io.prismic.experiment';
488
- var ResolvedApi = /** @class */ (function () {
489
- function ResolvedApi(data, httpClient, options) {
490
- this.data = data;
491
- this.masterRef = data.refs.filter(function (ref) { return ref.isMasterRef; })[0];
492
- this.experiments = new Experiments(data.experiments);
493
- this.bookmarks = data.bookmarks;
494
- this.httpClient = httpClient;
495
- this.options = options;
496
- this.refs = data.refs;
497
- this.tags = data.tags;
498
- this.types = data.types;
499
- this.languages = data.languages;
500
- }
501
- /**
502
- * Returns a useable form from its id, as described in the RESTful description of the API.
503
- * For instance: api.form("everything") works on every repository (as "everything" exists by default)
504
- * You can then chain the calls: api.form("everything").query('[[:d = at(document.id, "UkL0gMuvzYUANCpf")]]').ref(ref).submit()
505
- */
506
- ResolvedApi.prototype.form = function (formId) {
507
- var form = this.data.forms[formId];
508
- if (!form) {
509
- return null;
510
- }
511
- if (formId === 'tags') {
512
- return new TagsForm(form, this.httpClient);
513
- }
514
- return new SearchForm(form, this.httpClient);
515
- };
516
- ResolvedApi.prototype.searchForm = function (formId) {
517
- var f = this.form(formId);
518
- if (f instanceof SearchForm) {
519
- return f;
520
- }
521
- return null;
522
- };
523
- ResolvedApi.prototype.tagsForm = function () {
524
- var f = this.form('tags');
525
- if (!f) {
526
- throw new Error('Missing tags form');
527
- }
528
- if (f instanceof TagsForm) {
529
- return f;
530
- }
531
- throw new Error('Unexpected error: tags form is not TagsForm');
532
- };
533
- ResolvedApi.prototype.everything = function () {
534
- var f = this.searchForm('everything');
535
- if (!f)
536
- throw new Error('Missing everything form');
537
- return f;
538
- };
539
- /**
540
- * The ID of the master ref on this prismic.io API.
541
- * Do not use like this: searchForm.ref(api.master()).
542
- * Instead, set your ref once in a variable, and call it when you need it; this will allow to change the ref you're viewing easily for your entire page.
543
- */
544
- ResolvedApi.prototype.master = function () {
545
- return this.masterRef.ref;
546
- };
547
- /**
548
- * Returns the ref ID for a given ref's label.
549
- * Do not use like this: searchForm.ref(api.ref("Future release label")).
550
- * Instead, set your ref once in a variable, and call it when you need it; this will allow to change the ref you're viewing easily for your entire page.
551
- */
552
- ResolvedApi.prototype.ref = function (label) {
553
- var ref = this.data.refs.filter(function (ref) { return ref.label === label; })[0];
554
- return ref ? ref.ref : null;
555
- };
556
- ResolvedApi.prototype.currentExperiment = function () {
557
- return this.experiments.current();
558
- };
559
- /**
560
- * Query the repository
561
- */
562
- ResolvedApi.prototype.query = function (q, optionsOrCallback, cb) {
563
- if (cb === void 0) { cb = function () { }; }
564
- var _a = typeof optionsOrCallback === 'function'
565
- ? { options: {}, callback: optionsOrCallback }
566
- : { options: optionsOrCallback || {}, callback: cb }, options = _a.options, callback = _a.callback;
567
- var form = this.everything();
568
- for (var key in options) {
569
- form = form.set(key, options[key]);
570
- }
571
- if (!options.ref) {
572
- // Look in cookies if we have a ref (preview or experiment)
573
- var cookieString = '';
574
- if (this.options.req) { // NodeJS
575
- cookieString = this.options.req.headers['cookie'] || '';
576
- }
577
- else if (typeof window !== 'undefined' && window.document) { // Browser
578
- cookieString = window.document.cookie || '';
579
- }
580
- var cookies = Cookies.parse(cookieString);
581
- var previewRef = cookies[PREVIEW_COOKIE];
582
- var experimentRef = this.experiments.refFromCookie(cookies[EXPERIMENT_COOKIE]);
583
- form = form.ref(previewRef || experimentRef || this.masterRef.ref);
584
- }
585
- if (q) {
586
- form.query(q);
587
- }
588
- return form.submit(callback);
589
- };
590
- /**
591
- * Retrieve the document returned by the given query
592
- * @param {string|array|Predicate} the query
593
- * @param {object} additional parameters. In NodeJS, pass the request as 'req'.
594
- * @param {function} callback(err, doc)
595
- */
596
- ResolvedApi.prototype.queryFirst = function (q, optionsOrCallback, cb) {
597
- var _a = typeof optionsOrCallback === 'function'
598
- ? { options: {}, callback: optionsOrCallback }
599
- : { options: optionsOrCallback || {}, callback: cb || (function () { }) }, options = _a.options, callback = _a.callback;
600
- options.page = 1;
601
- options.pageSize = 1;
602
- return this.query(q, options).then(function (response) {
603
- var document = response && response.results && response.results[0];
604
- callback(null, document);
605
- return document;
606
- }).catch(function (error) {
607
- callback(error);
608
- throw error;
609
- });
610
- };
611
- /**
612
- * Retrieve the document with the given id
613
- */
614
- ResolvedApi.prototype.getByID = function (id, maybeOptions, cb) {
615
- var options = maybeOptions ? __assign({}, maybeOptions) : {};
616
- if (!options.lang)
617
- options.lang = '*';
618
- return this.queryFirst(Predicates.at('document.id', id), options, cb);
619
- };
620
- /**
621
- * Retrieve multiple documents from an array of id
622
- */
623
- ResolvedApi.prototype.getByIDs = function (ids, maybeOptions, cb) {
624
- var options = maybeOptions ? __assign({}, maybeOptions) : {};
625
- if (!options.lang)
626
- options.lang = '*';
627
- return this.query(Predicates.in('document.id', ids), options, cb);
628
- };
629
- /**
630
- * Retrieve the document with the given uid
631
- */
632
- ResolvedApi.prototype.getByUID = function (type, uid, maybeOptions, cb) {
633
- var options = maybeOptions ? __assign({}, maybeOptions) : {};
634
- if (options.lang === '*')
635
- throw new Error("FORBIDDEN. You can't use getByUID with *, use the predicates instead.");
636
- if (!options.page)
637
- options.page = 1;
638
- return this.queryFirst(Predicates.at("my." + type + ".uid", uid), options, cb);
639
- };
640
- /**
641
- * Retrieve the singleton document with the given type
642
- */
643
- ResolvedApi.prototype.getSingle = function (type, maybeOptions, cb) {
644
- var options = maybeOptions ? __assign({}, maybeOptions) : {};
645
- return this.queryFirst(Predicates.at('document.type', type), options, cb);
646
- };
647
- /**
648
- * Retrieve the document with the given bookmark
649
- */
650
- ResolvedApi.prototype.getBookmark = function (bookmark, maybeOptions, cb) {
651
- var id = this.data.bookmarks[bookmark];
652
- if (id) {
653
- return this.getByID(id, maybeOptions, cb);
654
- }
655
- else {
656
- return Promise.reject('Error retrieving bookmarked id');
657
- }
658
- };
659
- /**
660
- * Return all tags of your repository
661
- */
662
- ResolvedApi.prototype.getTags = function (cb) {
663
- return this.tagsForm().submit(cb);
664
- };
665
- ResolvedApi.prototype.getPreviewResolver = function (token, documentId) {
666
- return createPreviewResolver(token, documentId, this.getByID.bind(this));
667
- };
668
- return ResolvedApi;
486
+ var PREVIEW_COOKIE = 'io.prismic.preview';
487
+ var EXPERIMENT_COOKIE = 'io.prismic.experiment';
488
+ var ResolvedApi = /** @class */ (function () {
489
+ function ResolvedApi(data, httpClient, options) {
490
+ this.data = data;
491
+ this.masterRef = data.refs.filter(function (ref) { return ref.isMasterRef; })[0];
492
+ this.experiments = new Experiments(data.experiments);
493
+ this.bookmarks = data.bookmarks;
494
+ this.httpClient = httpClient;
495
+ this.options = options;
496
+ this.refs = data.refs;
497
+ this.tags = data.tags;
498
+ this.types = data.types;
499
+ this.languages = data.languages;
500
+ }
501
+ /**
502
+ * Returns a useable form from its id, as described in the RESTful description of the API.
503
+ * For instance: api.form("everything") works on every repository (as "everything" exists by default)
504
+ * You can then chain the calls: api.form("everything").query('[[:d = at(document.id, "UkL0gMuvzYUANCpf")]]').ref(ref).submit()
505
+ */
506
+ ResolvedApi.prototype.form = function (formId) {
507
+ var form = this.data.forms[formId];
508
+ if (!form) {
509
+ return null;
510
+ }
511
+ if (formId === 'tags') {
512
+ return new TagsForm(form, this.httpClient);
513
+ }
514
+ return new SearchForm(form, this.httpClient);
515
+ };
516
+ ResolvedApi.prototype.searchForm = function (formId) {
517
+ var f = this.form(formId);
518
+ if (f instanceof SearchForm) {
519
+ return f;
520
+ }
521
+ return null;
522
+ };
523
+ ResolvedApi.prototype.tagsForm = function () {
524
+ var f = this.form('tags');
525
+ if (!f) {
526
+ throw new Error('Missing tags form');
527
+ }
528
+ if (f instanceof TagsForm) {
529
+ return f;
530
+ }
531
+ throw new Error('Unexpected error: tags form is not TagsForm');
532
+ };
533
+ ResolvedApi.prototype.everything = function () {
534
+ var f = this.searchForm('everything');
535
+ if (!f)
536
+ throw new Error('Missing everything form');
537
+ return f;
538
+ };
539
+ /**
540
+ * The ID of the master ref on this prismic.io API.
541
+ * Do not use like this: searchForm.ref(api.master()).
542
+ * Instead, set your ref once in a variable, and call it when you need it; this will allow to change the ref you're viewing easily for your entire page.
543
+ */
544
+ ResolvedApi.prototype.master = function () {
545
+ return this.masterRef.ref;
546
+ };
547
+ /**
548
+ * Returns the ref ID for a given ref's label.
549
+ * Do not use like this: searchForm.ref(api.ref("Future release label")).
550
+ * Instead, set your ref once in a variable, and call it when you need it; this will allow to change the ref you're viewing easily for your entire page.
551
+ */
552
+ ResolvedApi.prototype.ref = function (label) {
553
+ var ref = this.data.refs.filter(function (ref) { return ref.label === label; })[0];
554
+ return ref ? ref.ref : null;
555
+ };
556
+ ResolvedApi.prototype.currentExperiment = function () {
557
+ return this.experiments.current();
558
+ };
559
+ /**
560
+ * Query the repository
561
+ */
562
+ ResolvedApi.prototype.query = function (q, optionsOrCallback, cb) {
563
+ if (cb === void 0) { cb = function () { }; }
564
+ var _a = typeof optionsOrCallback === 'function'
565
+ ? { options: {}, callback: optionsOrCallback }
566
+ : { options: optionsOrCallback || {}, callback: cb }, options = _a.options, callback = _a.callback;
567
+ var form = this.everything();
568
+ for (var key in options) {
569
+ form = form.set(key, options[key]);
570
+ }
571
+ if (!options.ref) {
572
+ // Look in cookies if we have a ref (preview or experiment)
573
+ var cookieString = '';
574
+ if (this.options.req) { // NodeJS
575
+ cookieString = this.options.req.headers['cookie'] || '';
576
+ }
577
+ else if (typeof window !== 'undefined' && window.document) { // Browser
578
+ cookieString = window.document.cookie || '';
579
+ }
580
+ var cookies = Cookies.parse(cookieString);
581
+ var previewRef = cookies[PREVIEW_COOKIE];
582
+ var experimentRef = this.experiments.refFromCookie(cookies[EXPERIMENT_COOKIE]);
583
+ form = form.ref(previewRef || experimentRef || this.masterRef.ref);
584
+ }
585
+ if (q) {
586
+ form.query(q);
587
+ }
588
+ return form.submit(callback);
589
+ };
590
+ /**
591
+ * Retrieve the document returned by the given query
592
+ * @param {string|array|Predicate} the query
593
+ * @param {object} additional parameters. In NodeJS, pass the request as 'req'.
594
+ * @param {function} callback(err, doc)
595
+ */
596
+ ResolvedApi.prototype.queryFirst = function (q, optionsOrCallback, cb) {
597
+ var _a = typeof optionsOrCallback === 'function'
598
+ ? { options: {}, callback: optionsOrCallback }
599
+ : { options: optionsOrCallback || {}, callback: cb || (function () { }) }, options = _a.options, callback = _a.callback;
600
+ options.page = 1;
601
+ options.pageSize = 1;
602
+ return this.query(q, options).then(function (response) {
603
+ var document = response && response.results && response.results[0];
604
+ callback(null, document);
605
+ return document;
606
+ }).catch(function (error) {
607
+ callback(error);
608
+ throw error;
609
+ });
610
+ };
611
+ /**
612
+ * Retrieve the document with the given id
613
+ */
614
+ ResolvedApi.prototype.getByID = function (id, maybeOptions, cb) {
615
+ var options = maybeOptions ? __assign({}, maybeOptions) : {};
616
+ if (!options.lang)
617
+ options.lang = '*';
618
+ return this.queryFirst(Predicates.at('document.id', id), options, cb);
619
+ };
620
+ /**
621
+ * Retrieve multiple documents from an array of id
622
+ */
623
+ ResolvedApi.prototype.getByIDs = function (ids, maybeOptions, cb) {
624
+ var options = maybeOptions ? __assign({}, maybeOptions) : {};
625
+ if (!options.lang)
626
+ options.lang = '*';
627
+ return this.query(Predicates.in('document.id', ids), options, cb);
628
+ };
629
+ /**
630
+ * Retrieve the document with the given uid
631
+ */
632
+ ResolvedApi.prototype.getByUID = function (type, uid, maybeOptions, cb) {
633
+ var options = maybeOptions ? __assign({}, maybeOptions) : {};
634
+ if (options.lang === '*')
635
+ throw new Error("FORBIDDEN. You can't use getByUID with *, use the predicates instead.");
636
+ if (!options.page)
637
+ options.page = 1;
638
+ return this.queryFirst(Predicates.at("my." + type + ".uid", uid), options, cb);
639
+ };
640
+ /**
641
+ * Retrieve the singleton document with the given type
642
+ */
643
+ ResolvedApi.prototype.getSingle = function (type, maybeOptions, cb) {
644
+ var options = maybeOptions ? __assign({}, maybeOptions) : {};
645
+ return this.queryFirst(Predicates.at('document.type', type), options, cb);
646
+ };
647
+ /**
648
+ * Retrieve the document with the given bookmark
649
+ */
650
+ ResolvedApi.prototype.getBookmark = function (bookmark, maybeOptions, cb) {
651
+ var id = this.data.bookmarks[bookmark];
652
+ if (id) {
653
+ return this.getByID(id, maybeOptions, cb);
654
+ }
655
+ else {
656
+ return Promise.reject('Error retrieving bookmarked id');
657
+ }
658
+ };
659
+ /**
660
+ * Return all tags of your repository
661
+ */
662
+ ResolvedApi.prototype.getTags = function (cb) {
663
+ return this.tagsForm().submit(cb);
664
+ };
665
+ ResolvedApi.prototype.getPreviewResolver = function (token, documentId) {
666
+ return createPreviewResolver(token, documentId, this.getByID.bind(this));
667
+ };
668
+ return ResolvedApi;
669
669
  }());
670
670
 
671
- /* eslint-disable */
672
- /**
673
- * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most
674
- * recently used items while discarding least recently used items when its limit
675
- * is reached.
676
- *
677
- * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/>
678
- * Typescript-ified by Oleksandr Nikitin <https://tvori.info>
679
- *
680
- * Illustration of the design:
681
- *
682
- * entry entry entry entry
683
- * ______ ______ ______ ______
684
- * | head |.newer => | |.newer => | |.newer => | tail |
685
- * | A | | B | | C | | D |
686
- * |______| <= older.|______| <= older.|______| <= older.|______|
687
- *
688
- * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added
689
- */
690
- function MakeLRUCache(limit) {
691
- return new LRUCache(limit);
692
- }
693
- function LRUCache(limit) {
694
- // Current size of the cache. (Read-only).
695
- this.size = 0;
696
- // Maximum number of items this cache can hold.
697
- this.limit = limit;
698
- this._keymap = {};
699
- }
700
- /**
701
- * Put <value> into the cache associated with <key>. Returns the entry which was
702
- * removed to make room for the new entry. Otherwise undefined is returned
703
- * (i.e. if there was enough room already).
704
- */
705
- LRUCache.prototype.put = function (key, value) {
706
- var entry = { key: key, value: value };
707
- // Note: No protection agains replacing, and thus orphan entries. By design.
708
- this._keymap[key] = entry;
709
- if (this.tail) {
710
- // link previous tail to the new tail (entry)
711
- this.tail.newer = entry;
712
- entry.older = this.tail;
713
- }
714
- else {
715
- // we're first in -- yay
716
- this.head = entry;
717
- }
718
- // add new entry to the end of the linked list -- it's now the freshest entry.
719
- this.tail = entry;
720
- if (this.size === this.limit) {
721
- // we hit the limit -- remove the head
722
- return this.shift();
723
- }
724
- else {
725
- // increase the size counter
726
- this.size++;
727
- }
728
- };
729
- /**
730
- * Purge the least recently used (oldest) entry from the cache. Returns the
731
- * removed entry or undefined if the cache was empty.
732
- *
733
- * If you need to perform any form of finalization of purged items, this is a
734
- * good place to do it. Simply override/replace this function:
735
- *
736
- * var c = new LRUCache(123);
737
- * c.shift = function() {
738
- * var entry = LRUCache.prototype.shift.call(this);
739
- * doSomethingWith(entry);
740
- * return entry;
741
- * }
742
- */
743
- LRUCache.prototype.shift = function () {
744
- // todo: handle special case when limit == 1
745
- var entry = this.head;
746
- if (entry) {
747
- if (this.head.newer) {
748
- this.head = this.head.newer;
749
- this.head.older = undefined;
750
- }
751
- else {
752
- this.head = undefined;
753
- }
754
- // Remove last strong reference to <entry> and remove links from the purged
755
- // entry being returned:
756
- entry.newer = entry.older = undefined;
757
- // delete is slow, but we need to do this to avoid uncontrollable growth:
758
- delete this._keymap[entry.key];
759
- }
760
- console.log('purging ', entry.key);
761
- return entry;
762
- };
763
- /**
764
- * Get and register recent use of <key>. Returns the value associated with <key>
765
- * or undefined if not in cache.
766
- */
767
- LRUCache.prototype.get = function (key, returnEntry) {
768
- // First, find our cache entry
769
- var entry = this._keymap[key];
770
- if (entry === undefined)
771
- return; // Not cached. Sorry.
772
- // As <key> was found in the cache, register it as being requested recently
773
- if (entry === this.tail) {
774
- // Already the most recently used entry, so no need to update the list
775
- return returnEntry ? entry : entry.value;
776
- }
777
- // HEAD--------------TAIL
778
- // <.older .newer>
779
- // <--- add direction --
780
- // A B C <D> E
781
- if (entry.newer) {
782
- if (entry === this.head)
783
- this.head = entry.newer;
784
- entry.newer.older = entry.older; // C <-- E.
785
- }
786
- if (entry.older)
787
- entry.older.newer = entry.newer; // C. --> E
788
- entry.newer = undefined; // D --x
789
- entry.older = this.tail; // D. --> E
790
- if (this.tail)
791
- this.tail.newer = entry; // E. <-- D
792
- this.tail = entry;
793
- return returnEntry ? entry : entry.value;
794
- };
795
- // ----------------------------------------------------------------------------
796
- // Following code is optional and can be removed without breaking the core
797
- // functionality.
798
- /**
799
- * Check if <key> is in the cache without registering recent use. Feasible if
800
- * you do not want to chage the state of the cache, but only "peek" at it.
801
- * Returns the entry associated with <key> if found, or undefined if not found.
802
- */
803
- LRUCache.prototype.find = function (key) {
804
- return this._keymap[key];
805
- };
806
- /**
807
- * Update the value of entry with <key>. Returns the old value, or undefined if
808
- * entry was not in the cache.
809
- */
810
- LRUCache.prototype.set = function (key, value) {
811
- var oldvalue;
812
- var entry = this.get(key, true);
813
- if (entry) {
814
- oldvalue = entry.value;
815
- entry.value = value;
816
- }
817
- else {
818
- oldvalue = this.put(key, value);
819
- if (oldvalue)
820
- oldvalue = oldvalue.value;
821
- }
822
- return oldvalue;
823
- };
824
- /**
825
- * Remove entry <key> from cache and return its value. Returns undefined if not
826
- * found.
827
- */
828
- LRUCache.prototype.remove = function (key) {
829
- var entry = this._keymap[key];
830
- if (!entry)
831
- return;
832
- delete this._keymap[entry.key]; // need to do delete unfortunately
833
- if (entry.newer && entry.older) {
834
- // relink the older entry with the newer entry
835
- entry.older.newer = entry.newer;
836
- entry.newer.older = entry.older;
837
- }
838
- else if (entry.newer) {
839
- // remove the link to us
840
- entry.newer.older = undefined;
841
- // link the newer entry to head
842
- this.head = entry.newer;
843
- }
844
- else if (entry.older) {
845
- // remove the link to us
846
- entry.older.newer = undefined;
847
- // link the newer entry to head
848
- this.tail = entry.older;
849
- }
850
- else { // if(entry.older === undefined && entry.newer === undefined) {
851
- this.head = this.tail = undefined;
852
- }
853
- this.size--;
854
- return entry.value;
855
- };
856
- /** Removes all entries */
857
- LRUCache.prototype.removeAll = function () {
858
- // This should be safe, as we never expose strong refrences to the outside
859
- this.head = this.tail = undefined;
860
- this.size = 0;
861
- this._keymap = {};
862
- };
863
- /**
864
- * Return an array containing all keys of entries stored in the cache object, in
865
- * arbitrary order.
866
- */
867
- if (typeof Object.keys === 'function') {
868
- LRUCache.prototype.keys = function () { return Object.keys(this._keymap); };
869
- }
870
- else {
871
- LRUCache.prototype.keys = function () {
872
- var keys = [];
873
- for (var k in this._keymap)
874
- keys.push(k);
875
- return keys;
876
- };
877
- }
878
- /**
879
- * Call `fun` for each entry. Starting with the newest entry if `desc` is a true
880
- * value, otherwise starts with the oldest (head) enrty and moves towards the
881
- * tail.
882
- *
883
- * `fun` is called with 3 arguments in the context `context`:
884
- * `fun.call(context, Object key, Object value, LRUCache self)`
885
- */
886
- LRUCache.prototype.forEach = function (fun, context, desc) {
887
- var entry;
888
- if (context === true) {
889
- desc = true;
890
- context = undefined;
891
- }
892
- else if (typeof context !== 'object')
893
- context = this;
894
- if (desc) {
895
- entry = this.tail;
896
- while (entry) {
897
- fun.call(context, entry.key, entry.value, this);
898
- entry = entry.older;
899
- }
900
- }
901
- else {
902
- entry = this.head;
903
- while (entry) {
904
- fun.call(context, entry.key, entry.value, this);
905
- entry = entry.newer;
906
- }
907
- }
908
- };
909
- /** Returns a JSON (array) representation */
910
- //LRUCache.prototype.toJSON = function () {
911
- // var s: IEntry[] = [], entry = this.head;
912
- // while (entry) {
913
- // s.push({ key: entry.key.toJSON(), value: entry.value.toJSON() });
914
- // entry = entry.newer;
915
- // }
916
- // return s;
917
- //};
918
- /** Returns a String representation */
919
- LRUCache.prototype.toString = function () {
920
- var s = '', entry = this.head;
921
- while (entry) {
922
- s += String(entry.key) + ':' + entry.value;
923
- entry = entry.newer;
924
- if (entry)
925
- s += ' < ';
926
- }
927
- return s;
928
- };
929
- // Export ourselves
671
+ /* eslint-disable */
672
+ /**
673
+ * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most
674
+ * recently used items while discarding least recently used items when its limit
675
+ * is reached.
676
+ *
677
+ * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/>
678
+ * Typescript-ified by Oleksandr Nikitin <https://tvori.info>
679
+ *
680
+ * Illustration of the design:
681
+ *
682
+ * entry entry entry entry
683
+ * ______ ______ ______ ______
684
+ * | head |.newer => | |.newer => | |.newer => | tail |
685
+ * | A | | B | | C | | D |
686
+ * |______| <= older.|______| <= older.|______| <= older.|______|
687
+ *
688
+ * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added
689
+ */
690
+ function MakeLRUCache(limit) {
691
+ return new LRUCache(limit);
692
+ }
693
+ function LRUCache(limit) {
694
+ // Current size of the cache. (Read-only).
695
+ this.size = 0;
696
+ // Maximum number of items this cache can hold.
697
+ this.limit = limit;
698
+ this._keymap = {};
699
+ }
700
+ /**
701
+ * Put <value> into the cache associated with <key>. Returns the entry which was
702
+ * removed to make room for the new entry. Otherwise undefined is returned
703
+ * (i.e. if there was enough room already).
704
+ */
705
+ LRUCache.prototype.put = function (key, value) {
706
+ var entry = { key: key, value: value };
707
+ // Note: No protection agains replacing, and thus orphan entries. By design.
708
+ this._keymap[key] = entry;
709
+ if (this.tail) {
710
+ // link previous tail to the new tail (entry)
711
+ this.tail.newer = entry;
712
+ entry.older = this.tail;
713
+ }
714
+ else {
715
+ // we're first in -- yay
716
+ this.head = entry;
717
+ }
718
+ // add new entry to the end of the linked list -- it's now the freshest entry.
719
+ this.tail = entry;
720
+ if (this.size === this.limit) {
721
+ // we hit the limit -- remove the head
722
+ return this.shift();
723
+ }
724
+ else {
725
+ // increase the size counter
726
+ this.size++;
727
+ }
728
+ };
729
+ /**
730
+ * Purge the least recently used (oldest) entry from the cache. Returns the
731
+ * removed entry or undefined if the cache was empty.
732
+ *
733
+ * If you need to perform any form of finalization of purged items, this is a
734
+ * good place to do it. Simply override/replace this function:
735
+ *
736
+ * var c = new LRUCache(123);
737
+ * c.shift = function() {
738
+ * var entry = LRUCache.prototype.shift.call(this);
739
+ * doSomethingWith(entry);
740
+ * return entry;
741
+ * }
742
+ */
743
+ LRUCache.prototype.shift = function () {
744
+ // todo: handle special case when limit == 1
745
+ var entry = this.head;
746
+ if (entry) {
747
+ if (this.head.newer) {
748
+ this.head = this.head.newer;
749
+ this.head.older = undefined;
750
+ }
751
+ else {
752
+ this.head = undefined;
753
+ }
754
+ // Remove last strong reference to <entry> and remove links from the purged
755
+ // entry being returned:
756
+ entry.newer = entry.older = undefined;
757
+ // delete is slow, but we need to do this to avoid uncontrollable growth:
758
+ delete this._keymap[entry.key];
759
+ }
760
+ console.log('purging ', entry.key);
761
+ return entry;
762
+ };
763
+ /**
764
+ * Get and register recent use of <key>. Returns the value associated with <key>
765
+ * or undefined if not in cache.
766
+ */
767
+ LRUCache.prototype.get = function (key, returnEntry) {
768
+ // First, find our cache entry
769
+ var entry = this._keymap[key];
770
+ if (entry === undefined)
771
+ return; // Not cached. Sorry.
772
+ // As <key> was found in the cache, register it as being requested recently
773
+ if (entry === this.tail) {
774
+ // Already the most recently used entry, so no need to update the list
775
+ return returnEntry ? entry : entry.value;
776
+ }
777
+ // HEAD--------------TAIL
778
+ // <.older .newer>
779
+ // <--- add direction --
780
+ // A B C <D> E
781
+ if (entry.newer) {
782
+ if (entry === this.head)
783
+ this.head = entry.newer;
784
+ entry.newer.older = entry.older; // C <-- E.
785
+ }
786
+ if (entry.older)
787
+ entry.older.newer = entry.newer; // C. --> E
788
+ entry.newer = undefined; // D --x
789
+ entry.older = this.tail; // D. --> E
790
+ if (this.tail)
791
+ this.tail.newer = entry; // E. <-- D
792
+ this.tail = entry;
793
+ return returnEntry ? entry : entry.value;
794
+ };
795
+ // ----------------------------------------------------------------------------
796
+ // Following code is optional and can be removed without breaking the core
797
+ // functionality.
798
+ /**
799
+ * Check if <key> is in the cache without registering recent use. Feasible if
800
+ * you do not want to chage the state of the cache, but only "peek" at it.
801
+ * Returns the entry associated with <key> if found, or undefined if not found.
802
+ */
803
+ LRUCache.prototype.find = function (key) {
804
+ return this._keymap[key];
805
+ };
806
+ /**
807
+ * Update the value of entry with <key>. Returns the old value, or undefined if
808
+ * entry was not in the cache.
809
+ */
810
+ LRUCache.prototype.set = function (key, value) {
811
+ var oldvalue;
812
+ var entry = this.get(key, true);
813
+ if (entry) {
814
+ oldvalue = entry.value;
815
+ entry.value = value;
816
+ }
817
+ else {
818
+ oldvalue = this.put(key, value);
819
+ if (oldvalue)
820
+ oldvalue = oldvalue.value;
821
+ }
822
+ return oldvalue;
823
+ };
824
+ /**
825
+ * Remove entry <key> from cache and return its value. Returns undefined if not
826
+ * found.
827
+ */
828
+ LRUCache.prototype.remove = function (key) {
829
+ var entry = this._keymap[key];
830
+ if (!entry)
831
+ return;
832
+ delete this._keymap[entry.key]; // need to do delete unfortunately
833
+ if (entry.newer && entry.older) {
834
+ // relink the older entry with the newer entry
835
+ entry.older.newer = entry.newer;
836
+ entry.newer.older = entry.older;
837
+ }
838
+ else if (entry.newer) {
839
+ // remove the link to us
840
+ entry.newer.older = undefined;
841
+ // link the newer entry to head
842
+ this.head = entry.newer;
843
+ }
844
+ else if (entry.older) {
845
+ // remove the link to us
846
+ entry.older.newer = undefined;
847
+ // link the newer entry to head
848
+ this.tail = entry.older;
849
+ }
850
+ else { // if(entry.older === undefined && entry.newer === undefined) {
851
+ this.head = this.tail = undefined;
852
+ }
853
+ this.size--;
854
+ return entry.value;
855
+ };
856
+ /** Removes all entries */
857
+ LRUCache.prototype.removeAll = function () {
858
+ // This should be safe, as we never expose strong refrences to the outside
859
+ this.head = this.tail = undefined;
860
+ this.size = 0;
861
+ this._keymap = {};
862
+ };
863
+ /**
864
+ * Return an array containing all keys of entries stored in the cache object, in
865
+ * arbitrary order.
866
+ */
867
+ if (typeof Object.keys === 'function') {
868
+ LRUCache.prototype.keys = function () { return Object.keys(this._keymap); };
869
+ }
870
+ else {
871
+ LRUCache.prototype.keys = function () {
872
+ var keys = [];
873
+ for (var k in this._keymap)
874
+ keys.push(k);
875
+ return keys;
876
+ };
877
+ }
878
+ /**
879
+ * Call `fun` for each entry. Starting with the newest entry if `desc` is a true
880
+ * value, otherwise starts with the oldest (head) enrty and moves towards the
881
+ * tail.
882
+ *
883
+ * `fun` is called with 3 arguments in the context `context`:
884
+ * `fun.call(context, Object key, Object value, LRUCache self)`
885
+ */
886
+ LRUCache.prototype.forEach = function (fun, context, desc) {
887
+ var entry;
888
+ if (context === true) {
889
+ desc = true;
890
+ context = undefined;
891
+ }
892
+ else if (typeof context !== 'object')
893
+ context = this;
894
+ if (desc) {
895
+ entry = this.tail;
896
+ while (entry) {
897
+ fun.call(context, entry.key, entry.value, this);
898
+ entry = entry.older;
899
+ }
900
+ }
901
+ else {
902
+ entry = this.head;
903
+ while (entry) {
904
+ fun.call(context, entry.key, entry.value, this);
905
+ entry = entry.newer;
906
+ }
907
+ }
908
+ };
909
+ /** Returns a JSON (array) representation */
910
+ //LRUCache.prototype.toJSON = function () {
911
+ // var s: IEntry[] = [], entry = this.head;
912
+ // while (entry) {
913
+ // s.push({ key: entry.key.toJSON(), value: entry.value.toJSON() });
914
+ // entry = entry.newer;
915
+ // }
916
+ // return s;
917
+ //};
918
+ /** Returns a String representation */
919
+ LRUCache.prototype.toString = function () {
920
+ var s = '', entry = this.head;
921
+ while (entry) {
922
+ s += String(entry.key) + ':' + entry.value;
923
+ entry = entry.newer;
924
+ if (entry)
925
+ s += ' < ';
926
+ }
927
+ return s;
928
+ };
929
+ // Export ourselves
930
930
  //if (typeof this === 'object') this.LRUCache = LRUCache;
931
931
 
932
- var DefaultApiCache = /** @class */ (function () {
933
- function DefaultApiCache(limit) {
934
- if (limit === void 0) { limit = 1000; }
935
- this.lru = MakeLRUCache(limit);
936
- }
937
- DefaultApiCache.prototype.isExpired = function (key) {
938
- var value = this.lru.get(key, false);
939
- if (value) {
940
- return value.expiredIn !== 0 && value.expiredIn < Date.now();
941
- }
942
- else {
943
- return false;
944
- }
945
- };
946
- DefaultApiCache.prototype.get = function (key, cb) {
947
- var value = this.lru.get(key, false);
948
- if (value && !this.isExpired(key)) {
949
- cb(null, value.data);
950
- }
951
- else {
952
- cb && cb(null);
953
- }
954
- };
955
- DefaultApiCache.prototype.set = function (key, value, ttl, cb) {
956
- this.lru.remove(key);
957
- this.lru.put(key, {
958
- data: value,
959
- expiredIn: ttl ? (Date.now() + (ttl * 1000)) : 0,
960
- });
961
- cb && cb(null);
962
- };
963
- DefaultApiCache.prototype.remove = function (key, cb) {
964
- this.lru.remove(key);
965
- cb && cb(null);
966
- };
967
- DefaultApiCache.prototype.clear = function (cb) {
968
- this.lru.removeAll();
969
- cb && cb(null);
970
- };
971
- return DefaultApiCache;
932
+ var DefaultApiCache = /** @class */ (function () {
933
+ function DefaultApiCache(limit) {
934
+ if (limit === void 0) { limit = 1000; }
935
+ this.lru = MakeLRUCache(limit);
936
+ }
937
+ DefaultApiCache.prototype.isExpired = function (key) {
938
+ var value = this.lru.get(key, false);
939
+ if (value) {
940
+ return value.expiredIn !== 0 && value.expiredIn < Date.now();
941
+ }
942
+ else {
943
+ return false;
944
+ }
945
+ };
946
+ DefaultApiCache.prototype.get = function (key, cb) {
947
+ var value = this.lru.get(key, false);
948
+ if (value && !this.isExpired(key)) {
949
+ cb(null, value.data);
950
+ }
951
+ else {
952
+ cb && cb(null);
953
+ }
954
+ };
955
+ DefaultApiCache.prototype.set = function (key, value, ttl, cb) {
956
+ this.lru.remove(key);
957
+ this.lru.put(key, {
958
+ data: value,
959
+ expiredIn: ttl ? (Date.now() + (ttl * 1000)) : 0,
960
+ });
961
+ cb && cb(null);
962
+ };
963
+ DefaultApiCache.prototype.remove = function (key, cb) {
964
+ this.lru.remove(key);
965
+ cb && cb(null);
966
+ };
967
+ DefaultApiCache.prototype.clear = function (cb) {
968
+ this.lru.removeAll();
969
+ cb && cb(null);
970
+ };
971
+ return DefaultApiCache;
972
972
  }());
973
973
 
974
- function fetchRequest(url, options, callback) {
975
- var fetchOptions = {
976
- headers: {
977
- Accept: 'application/json',
978
- },
979
- };
980
- if (options && options.proxyAgent) {
981
- fetchOptions.agent = options.proxyAgent;
982
- }
983
- // can't use number because of NodeJS globals included
984
- var timeoutId;
985
- var fetchPromise = crossFetch(url, fetchOptions);
986
- var promise = options.timeoutInMs ? Promise.race([
987
- fetchPromise,
988
- new Promise(function (_, reject) {
989
- timeoutId = setTimeout(function () { return reject(new Error(url + " response timeout")); }, options.timeoutInMs);
990
- })
991
- ]) : fetchPromise;
992
- promise.then(function (resp) {
993
- clearTimeout(timeoutId);
994
- if (~~(resp.status / 100 !== 2)) {
995
- /**
996
- * @description
997
- * drain the resp before throwing an error to prevent memory leaks
998
- * @link https://github.com/bitinn/node-fetch/issues/83
999
- */
1000
- return resp.text().then(function () {
1001
- var e = new Error("Unexpected status code [" + resp.status + "] on URL " + url);
1002
- e.status = resp.status;
1003
- throw e;
1004
- });
1005
- }
1006
- return resp.json().then(function (result) {
1007
- var cacheControl = resp.headers.get('cache-control');
1008
- var parsedCacheControl = cacheControl ? /max-age=(\d+)/.exec(cacheControl) : null;
1009
- var ttl = parsedCacheControl ? parseInt(parsedCacheControl[1], 10) : undefined;
1010
- callback(null, result, resp, ttl);
1011
- });
1012
- }).catch(function (err) {
1013
- clearTimeout(timeoutId);
1014
- callback(err);
1015
- });
1016
- }
1017
- var DefaultRequestHandler = /** @class */ (function () {
1018
- function DefaultRequestHandler(options) {
1019
- this.options = options || {};
1020
- }
1021
- DefaultRequestHandler.prototype.request = function (url, callback) {
1022
- fetchRequest(url, this.options, callback);
1023
- };
1024
- return DefaultRequestHandler;
974
+ function fetchRequest(url, options, callback) {
975
+ var fetchOptions = {
976
+ headers: {
977
+ Accept: 'application/json',
978
+ },
979
+ };
980
+ if (options && options.proxyAgent) {
981
+ fetchOptions.agent = options.proxyAgent;
982
+ }
983
+ // can't use number because of NodeJS globals included
984
+ var timeoutId;
985
+ var fetchPromise = crossFetch(url, fetchOptions);
986
+ var promise = options.timeoutInMs ? Promise.race([
987
+ fetchPromise,
988
+ new Promise(function (_, reject) {
989
+ timeoutId = setTimeout(function () { return reject(new Error(url + " response timeout")); }, options.timeoutInMs);
990
+ })
991
+ ]) : fetchPromise;
992
+ promise.then(function (resp) {
993
+ clearTimeout(timeoutId);
994
+ if (~~(resp.status / 100 !== 2)) {
995
+ /**
996
+ * @description
997
+ * drain the resp before throwing an error to prevent memory leaks
998
+ * @link https://github.com/bitinn/node-fetch/issues/83
999
+ */
1000
+ return resp.text().then(function () {
1001
+ var e = new Error("Unexpected status code [" + resp.status + "] on URL " + url);
1002
+ e.status = resp.status;
1003
+ throw e;
1004
+ });
1005
+ }
1006
+ return resp.json().then(function (result) {
1007
+ var cacheControl = resp.headers.get('cache-control');
1008
+ var parsedCacheControl = cacheControl ? /max-age=(\d+)/.exec(cacheControl) : null;
1009
+ var ttl = parsedCacheControl ? parseInt(parsedCacheControl[1], 10) : undefined;
1010
+ callback(null, result, resp, ttl);
1011
+ });
1012
+ }).catch(function (err) {
1013
+ clearTimeout(timeoutId);
1014
+ callback(err);
1015
+ });
1016
+ }
1017
+ var DefaultRequestHandler = /** @class */ (function () {
1018
+ function DefaultRequestHandler(options) {
1019
+ this.options = options || {};
1020
+ }
1021
+ DefaultRequestHandler.prototype.request = function (url, callback) {
1022
+ fetchRequest(url, this.options, callback);
1023
+ };
1024
+ return DefaultRequestHandler;
1025
1025
  }());
1026
1026
 
1027
- var HttpClient = /** @class */ (function () {
1028
- function HttpClient(requestHandler, cache, proxyAgent, timeoutInMs) {
1029
- this.requestHandler = requestHandler || new DefaultRequestHandler({ proxyAgent: proxyAgent, timeoutInMs: timeoutInMs });
1030
- this.cache = cache || new DefaultApiCache();
1031
- }
1032
- HttpClient.prototype.request = function (url, callback) {
1033
- this.requestHandler.request(url, function (err, result, xhr, ttl) {
1034
- if (err) {
1035
- callback && callback(err, null, xhr, ttl);
1036
- }
1037
- else if (result) {
1038
- callback && callback(null, result, xhr, ttl);
1039
- }
1040
- });
1041
- };
1042
- /**
1043
- * Fetch a URL corresponding to a query, and parse the response as a Response object
1044
- */
1045
- HttpClient.prototype.cachedRequest = function (url, maybeOptions) {
1046
- var _this = this;
1047
- var options = maybeOptions || {};
1048
- var run = function (cb) {
1049
- var cacheKey = options.cacheKey || url;
1050
- _this.cache.get(cacheKey, function (cacheGetError, cacheGetValue) {
1051
- if (cacheGetError || cacheGetValue) {
1052
- cb(cacheGetError, cacheGetValue);
1053
- }
1054
- else {
1055
- _this.request(url, function (fetchError, fetchValue, _, ttlReq) {
1056
- if (fetchError) {
1057
- cb(fetchError, null);
1058
- }
1059
- else {
1060
- var ttl = ttlReq || options.ttl;
1061
- if (ttl) {
1062
- _this.cache.set(cacheKey, fetchValue, ttl, cb);
1063
- }
1064
- cb(null, fetchValue);
1065
- }
1066
- });
1067
- }
1068
- });
1069
- };
1070
- return new Promise(function (resolve, reject) {
1071
- run(function (err, value) {
1072
- if (err)
1073
- reject(err);
1074
- if (value)
1075
- resolve(value);
1076
- });
1077
- });
1078
- };
1079
- return HttpClient;
1027
+ var HttpClient = /** @class */ (function () {
1028
+ function HttpClient(requestHandler, cache, proxyAgent, timeoutInMs) {
1029
+ this.requestHandler = requestHandler || new DefaultRequestHandler({ proxyAgent: proxyAgent, timeoutInMs: timeoutInMs });
1030
+ this.cache = cache || new DefaultApiCache();
1031
+ }
1032
+ HttpClient.prototype.request = function (url, callback) {
1033
+ this.requestHandler.request(url, function (err, result, xhr, ttl) {
1034
+ if (err) {
1035
+ callback && callback(err, null, xhr, ttl);
1036
+ }
1037
+ else if (result) {
1038
+ callback && callback(null, result, xhr, ttl);
1039
+ }
1040
+ });
1041
+ };
1042
+ /**
1043
+ * Fetch a URL corresponding to a query, and parse the response as a Response object
1044
+ */
1045
+ HttpClient.prototype.cachedRequest = function (url, maybeOptions) {
1046
+ var _this = this;
1047
+ var options = maybeOptions || {};
1048
+ var run = function (cb) {
1049
+ var cacheKey = options.cacheKey || url;
1050
+ _this.cache.get(cacheKey, function (cacheGetError, cacheGetValue) {
1051
+ if (cacheGetError || cacheGetValue) {
1052
+ cb(cacheGetError, cacheGetValue);
1053
+ }
1054
+ else {
1055
+ _this.request(url, function (fetchError, fetchValue, _, ttlReq) {
1056
+ if (fetchError) {
1057
+ cb(fetchError, null);
1058
+ }
1059
+ else {
1060
+ var ttl = ttlReq || options.ttl;
1061
+ if (ttl) {
1062
+ _this.cache.set(cacheKey, fetchValue, ttl, cb);
1063
+ }
1064
+ cb(null, fetchValue);
1065
+ }
1066
+ });
1067
+ }
1068
+ });
1069
+ };
1070
+ return new Promise(function (resolve, reject) {
1071
+ run(function (err, value) {
1072
+ if (err)
1073
+ reject(err);
1074
+ if (value)
1075
+ resolve(value);
1076
+ });
1077
+ });
1078
+ };
1079
+ return HttpClient;
1080
1080
  }());
1081
1081
 
1082
- function separator(url) {
1083
- return url.indexOf('?') > -1 ? '&' : '?';
1084
- }
1085
- var Api = /** @class */ (function () {
1086
- function Api(url, options) {
1087
- this.options = options || {};
1088
- this.url = url;
1089
- var queryStrings = [
1090
- this.options.accessToken && "access_token=" + this.options.accessToken,
1091
- this.options.routes && "routes=" + encodeURIComponent(JSON.stringify(this.options.routes))
1092
- ]
1093
- .filter(Boolean);
1094
- if (queryStrings.length > 0) {
1095
- this.url += separator(url) + queryStrings.join('&');
1096
- }
1097
- this.apiDataTTL = this.options.apiDataTTL || 5;
1098
- this.httpClient = new HttpClient(this.options.requestHandler, this.options.apiCache, this.options.proxyAgent, this.options.timeoutInMs);
1099
- }
1100
- /**
1101
- * Fetches data used to construct the api client, from cache if it's
1102
- * present, otherwise from calling the prismic api endpoint (which is
1103
- * then cached).
1104
- */
1105
- Api.prototype.get = function (cb) {
1106
- var _this = this;
1107
- return this.httpClient.cachedRequest(this.url, { ttl: this.apiDataTTL }).then(function (data) {
1108
- var resolvedApi = new ResolvedApi(data, _this.httpClient, _this.options);
1109
- cb && cb(null, resolvedApi);
1110
- return resolvedApi;
1111
- }).catch(function (error) {
1112
- cb && cb(error);
1113
- throw error;
1114
- });
1115
- };
1116
- return Api;
1082
+ function separator(url) {
1083
+ return url.indexOf('?') > -1 ? '&' : '?';
1084
+ }
1085
+ var Api = /** @class */ (function () {
1086
+ function Api(url, options) {
1087
+ this.options = options || {};
1088
+ this.url = url;
1089
+ var queryStrings = [
1090
+ this.options.accessToken && "access_token=" + this.options.accessToken,
1091
+ this.options.routes && "routes=" + encodeURIComponent(JSON.stringify(this.options.routes))
1092
+ ]
1093
+ .filter(Boolean);
1094
+ if (queryStrings.length > 0) {
1095
+ this.url += separator(url) + queryStrings.join('&');
1096
+ }
1097
+ this.apiDataTTL = this.options.apiDataTTL || 5;
1098
+ this.httpClient = new HttpClient(this.options.requestHandler, this.options.apiCache, this.options.proxyAgent, this.options.timeoutInMs);
1099
+ }
1100
+ /**
1101
+ * Fetches data used to construct the api client, from cache if it's
1102
+ * present, otherwise from calling the prismic api endpoint (which is
1103
+ * then cached).
1104
+ */
1105
+ Api.prototype.get = function (cb) {
1106
+ var _this = this;
1107
+ return this.httpClient.cachedRequest(this.url, { ttl: this.apiDataTTL }).then(function (data) {
1108
+ var resolvedApi = new ResolvedApi(data, _this.httpClient, _this.options);
1109
+ cb && cb(null, resolvedApi);
1110
+ return resolvedApi;
1111
+ }).catch(function (error) {
1112
+ cb && cb(error);
1113
+ throw error;
1114
+ });
1115
+ };
1116
+ return Api;
1117
1117
  }());
1118
1118
 
1119
- var LazySearchForm = /** @class */ (function () {
1120
- function LazySearchForm(id, api) {
1121
- this.id = id;
1122
- this.api = api;
1123
- this.fields = {};
1124
- }
1125
- LazySearchForm.prototype.set = function (key, value) {
1126
- this.fields[key] = value;
1127
- return this;
1128
- };
1129
- LazySearchForm.prototype.ref = function (ref) {
1130
- return this.set('ref', ref);
1131
- };
1132
- LazySearchForm.prototype.query = function (query) {
1133
- return this.set('q', query);
1134
- };
1135
- LazySearchForm.prototype.pageSize = function (size) {
1136
- return this.set('pageSize', size);
1137
- };
1138
- LazySearchForm.prototype.graphQuery = function (query) {
1139
- return this.set('graphQuery', query);
1140
- };
1141
- LazySearchForm.prototype.lang = function (langCode) {
1142
- return this.set('lang', langCode);
1143
- };
1144
- LazySearchForm.prototype.page = function (p) {
1145
- return this.set('page', p);
1146
- };
1147
- LazySearchForm.prototype.after = function (documentId) {
1148
- return this.set('after', documentId);
1149
- };
1150
- LazySearchForm.prototype.orderings = function (orderings) {
1151
- return this.set('orderings', orderings);
1152
- };
1153
- LazySearchForm.prototype.url = function () {
1154
- var _this = this;
1155
- return this.api.get().then(function (api) {
1156
- return LazySearchForm.toSearchForm(_this, api).url();
1157
- });
1158
- };
1159
- LazySearchForm.prototype.submit = function (cb) {
1160
- var _this = this;
1161
- return this.api.get().then(function (api) {
1162
- return LazySearchForm.toSearchForm(_this, api).submit(cb);
1163
- });
1164
- };
1165
- LazySearchForm.toSearchForm = function (lazyForm, api) {
1166
- var form = api.searchForm(lazyForm.id);
1167
- if (form) {
1168
- return Object.keys(lazyForm.fields).reduce(function (form, fieldKey) {
1169
- var fieldValue = lazyForm.fields[fieldKey];
1170
- if (fieldKey === 'q') {
1171
- return form.query(fieldValue);
1172
- }
1173
- else if (fieldKey === 'pageSize') {
1174
- return form.pageSize(fieldValue);
1175
- }
1176
- else if (fieldKey === 'graphQuery') {
1177
- return form.graphQuery(fieldValue);
1178
- }
1179
- else if (fieldKey === 'lang') {
1180
- return form.lang(fieldValue);
1181
- }
1182
- else if (fieldKey === 'page') {
1183
- return form.page(fieldValue);
1184
- }
1185
- else if (fieldKey === 'after') {
1186
- return form.after(fieldValue);
1187
- }
1188
- else if (fieldKey === 'orderings') {
1189
- return form.orderings(fieldValue);
1190
- }
1191
- else {
1192
- return form.set(fieldKey, fieldValue);
1193
- }
1194
- }, form);
1195
- }
1196
- else {
1197
- throw new Error("Unable to access to form " + lazyForm.id);
1198
- }
1199
- };
1200
- return LazySearchForm;
1119
+ var LazySearchForm = /** @class */ (function () {
1120
+ function LazySearchForm(id, api) {
1121
+ this.id = id;
1122
+ this.api = api;
1123
+ this.fields = {};
1124
+ }
1125
+ LazySearchForm.prototype.set = function (key, value) {
1126
+ this.fields[key] = value;
1127
+ return this;
1128
+ };
1129
+ LazySearchForm.prototype.ref = function (ref) {
1130
+ return this.set('ref', ref);
1131
+ };
1132
+ LazySearchForm.prototype.query = function (query) {
1133
+ return this.set('q', query);
1134
+ };
1135
+ LazySearchForm.prototype.pageSize = function (size) {
1136
+ return this.set('pageSize', size);
1137
+ };
1138
+ LazySearchForm.prototype.graphQuery = function (query) {
1139
+ return this.set('graphQuery', query);
1140
+ };
1141
+ LazySearchForm.prototype.lang = function (langCode) {
1142
+ return this.set('lang', langCode);
1143
+ };
1144
+ LazySearchForm.prototype.page = function (p) {
1145
+ return this.set('page', p);
1146
+ };
1147
+ LazySearchForm.prototype.after = function (documentId) {
1148
+ return this.set('after', documentId);
1149
+ };
1150
+ LazySearchForm.prototype.orderings = function (orderings) {
1151
+ return this.set('orderings', orderings);
1152
+ };
1153
+ LazySearchForm.prototype.url = function () {
1154
+ var _this = this;
1155
+ return this.api.get().then(function (api) {
1156
+ return LazySearchForm.toSearchForm(_this, api).url();
1157
+ });
1158
+ };
1159
+ LazySearchForm.prototype.submit = function (cb) {
1160
+ var _this = this;
1161
+ return this.api.get().then(function (api) {
1162
+ return LazySearchForm.toSearchForm(_this, api).submit(cb);
1163
+ });
1164
+ };
1165
+ LazySearchForm.toSearchForm = function (lazyForm, api) {
1166
+ var form = api.searchForm(lazyForm.id);
1167
+ if (form) {
1168
+ return Object.keys(lazyForm.fields).reduce(function (form, fieldKey) {
1169
+ var fieldValue = lazyForm.fields[fieldKey];
1170
+ if (fieldKey === 'q') {
1171
+ return form.query(fieldValue);
1172
+ }
1173
+ else if (fieldKey === 'pageSize') {
1174
+ return form.pageSize(fieldValue);
1175
+ }
1176
+ else if (fieldKey === 'graphQuery') {
1177
+ return form.graphQuery(fieldValue);
1178
+ }
1179
+ else if (fieldKey === 'lang') {
1180
+ return form.lang(fieldValue);
1181
+ }
1182
+ else if (fieldKey === 'page') {
1183
+ return form.page(fieldValue);
1184
+ }
1185
+ else if (fieldKey === 'after') {
1186
+ return form.after(fieldValue);
1187
+ }
1188
+ else if (fieldKey === 'orderings') {
1189
+ return form.orderings(fieldValue);
1190
+ }
1191
+ else {
1192
+ return form.set(fieldKey, fieldValue);
1193
+ }
1194
+ }, form);
1195
+ }
1196
+ else {
1197
+ throw new Error("Unable to access to form " + lazyForm.id);
1198
+ }
1199
+ };
1200
+ return LazySearchForm;
1201
1201
  }());
1202
1202
 
1203
- var DefaultClient = /** @class */ (function () {
1204
- function DefaultClient(url, options) {
1205
- this.api = new Api(url, options);
1206
- }
1207
- DefaultClient.prototype.getApi = function () {
1208
- return this.api.get();
1209
- };
1210
- DefaultClient.prototype.everything = function () {
1211
- return this.form('everything');
1212
- };
1213
- DefaultClient.prototype.form = function (formId) {
1214
- return new LazySearchForm(formId, this.api);
1215
- };
1216
- DefaultClient.prototype.query = function (q, optionsOrCallback, cb) {
1217
- return this.getApi().then(function (api) { return api.query(q, optionsOrCallback, cb); });
1218
- };
1219
- DefaultClient.prototype.queryFirst = function (q, optionsOrCallback, cb) {
1220
- return this.getApi().then(function (api) { return api.queryFirst(q, optionsOrCallback, cb); });
1221
- };
1222
- DefaultClient.prototype.getByID = function (id, options, cb) {
1223
- return this.getApi().then(function (api) { return api.getByID(id, options, cb); });
1224
- };
1225
- DefaultClient.prototype.getByIDs = function (ids, options, cb) {
1226
- return this.getApi().then(function (api) { return api.getByIDs(ids, options, cb); });
1227
- };
1228
- DefaultClient.prototype.getByUID = function (type, uid, options, cb) {
1229
- return this.getApi().then(function (api) { return api.getByUID(type, uid, options, cb); });
1230
- };
1231
- DefaultClient.prototype.getSingle = function (type, options, cb) {
1232
- return this.getApi().then(function (api) { return api.getSingle(type, options, cb); });
1233
- };
1234
- DefaultClient.prototype.getBookmark = function (bookmark, options, cb) {
1235
- return this.getApi().then(function (api) { return api.getBookmark(bookmark, options, cb); });
1236
- };
1237
- DefaultClient.prototype.getTags = function () {
1238
- return this.getApi().then(function (api) { return api.getTags(); });
1239
- };
1240
- DefaultClient.prototype.getPreviewResolver = function (token, documentId) {
1241
- var _this = this;
1242
- var getDocById = function (documentId, maybeOptions) { return _this.getApi().then(function (api) {
1243
- return api.getByID(documentId, maybeOptions);
1244
- }); };
1245
- return createPreviewResolver(token, documentId, getDocById);
1246
- };
1247
- DefaultClient.getApi = function (url, options) {
1248
- var api = new Api(url, options);
1249
- return api.get();
1250
- };
1251
- return DefaultClient;
1203
+ var DefaultClient = /** @class */ (function () {
1204
+ function DefaultClient(url, options) {
1205
+ this.api = new Api(url, options);
1206
+ }
1207
+ DefaultClient.prototype.getApi = function () {
1208
+ return this.api.get();
1209
+ };
1210
+ DefaultClient.prototype.everything = function () {
1211
+ return this.form('everything');
1212
+ };
1213
+ DefaultClient.prototype.form = function (formId) {
1214
+ return new LazySearchForm(formId, this.api);
1215
+ };
1216
+ DefaultClient.prototype.query = function (q, optionsOrCallback, cb) {
1217
+ return this.getApi().then(function (api) { return api.query(q, optionsOrCallback, cb); });
1218
+ };
1219
+ DefaultClient.prototype.queryFirst = function (q, optionsOrCallback, cb) {
1220
+ return this.getApi().then(function (api) { return api.queryFirst(q, optionsOrCallback, cb); });
1221
+ };
1222
+ DefaultClient.prototype.getByID = function (id, options, cb) {
1223
+ return this.getApi().then(function (api) { return api.getByID(id, options, cb); });
1224
+ };
1225
+ DefaultClient.prototype.getByIDs = function (ids, options, cb) {
1226
+ return this.getApi().then(function (api) { return api.getByIDs(ids, options, cb); });
1227
+ };
1228
+ DefaultClient.prototype.getByUID = function (type, uid, options, cb) {
1229
+ return this.getApi().then(function (api) { return api.getByUID(type, uid, options, cb); });
1230
+ };
1231
+ DefaultClient.prototype.getSingle = function (type, options, cb) {
1232
+ return this.getApi().then(function (api) { return api.getSingle(type, options, cb); });
1233
+ };
1234
+ DefaultClient.prototype.getBookmark = function (bookmark, options, cb) {
1235
+ return this.getApi().then(function (api) { return api.getBookmark(bookmark, options, cb); });
1236
+ };
1237
+ DefaultClient.prototype.getTags = function () {
1238
+ return this.getApi().then(function (api) { return api.getTags(); });
1239
+ };
1240
+ DefaultClient.prototype.getPreviewResolver = function (token, documentId) {
1241
+ var _this = this;
1242
+ var getDocById = function (documentId, maybeOptions) { return _this.getApi().then(function (api) {
1243
+ return api.getByID(documentId, maybeOptions);
1244
+ }); };
1245
+ return createPreviewResolver(token, documentId, getDocById);
1246
+ };
1247
+ DefaultClient.getApi = function (url, options) {
1248
+ var api = new Api(url, options);
1249
+ return api.get();
1250
+ };
1251
+ return DefaultClient;
1252
1252
  }());
1253
1253
 
1254
- var index = {
1255
- experimentCookie: EXPERIMENT_COOKIE,
1256
- previewCookie: PREVIEW_COOKIE,
1257
- Predicates: Predicates,
1258
- predicates: Predicates,
1259
- Experiments: Experiments,
1260
- Api: Api,
1261
- client: client,
1262
- getApi: getApi,
1263
- api: api,
1264
- };
1265
- function client(url, options) {
1266
- return new DefaultClient(url, options);
1267
- }
1268
- function getApi(url, options) {
1269
- return DefaultClient.getApi(url, options);
1270
- }
1271
- function api(url, options) {
1272
- return getApi(url, options);
1254
+ var index = {
1255
+ experimentCookie: EXPERIMENT_COOKIE,
1256
+ previewCookie: PREVIEW_COOKIE,
1257
+ Predicates: Predicates,
1258
+ predicates: Predicates,
1259
+ Experiments: Experiments,
1260
+ Api: Api,
1261
+ client: client,
1262
+ getApi: getApi,
1263
+ api: api,
1264
+ };
1265
+ function client(url, options) {
1266
+ return new DefaultClient(url, options);
1267
+ }
1268
+ function getApi(url, options) {
1269
+ return DefaultClient.getApi(url, options);
1270
+ }
1271
+ function api(url, options) {
1272
+ return getApi(url, options);
1273
1273
  }
1274
1274
 
1275
1275
  export default index;