@prismicio/client 5.1.1 → 5.2.0

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