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