@cubejs-client/core 0.30.60 → 0.30.64

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.
@@ -1,76 +1,13 @@
1
- import 'core-js/modules/es.object.keys.js';
2
- import 'core-js/modules/es.symbol.js';
3
- import 'core-js/modules/es.array.filter.js';
4
- import 'core-js/modules/es.object.get-own-property-descriptor.js';
5
- import 'core-js/modules/es.object.get-own-property-descriptors.js';
6
- import 'core-js/modules/es.object.define-properties.js';
7
- import 'core-js/modules/es.object.define-property.js';
8
- import _defineProperty from '@babel/runtime/helpers/defineProperty';
9
- import _typeof from '@babel/runtime/helpers/typeof';
10
- import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
11
- import _createClass from '@babel/runtime/helpers/createClass';
12
- import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
13
- import _regeneratorRuntime from '@babel/runtime/regenerator';
14
- import 'core-js/modules/es.object.to-string.js';
15
- import 'core-js/modules/es.promise.js';
16
- import 'core-js/modules/es.array.is-array.js';
17
- import 'core-js/modules/web.timers.js';
18
- import 'core-js/modules/es.array.for-each.js';
19
- import 'core-js/modules/web.dom-collections.for-each.js';
20
- import 'core-js/modules/es.array.map.js';
21
- import 'core-js/modules/es.function.bind.js';
22
1
  import { v4 } from 'uuid';
23
- import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
24
- import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
25
- import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
26
- import 'core-js/modules/es.array.iterator.js';
27
- import 'core-js/modules/es.map.js';
28
- import 'core-js/modules/es.string.iterator.js';
29
- import 'core-js/modules/web.dom-collections.iterator.js';
30
- import 'core-js/modules/es.array.from.js';
31
- import 'core-js/modules/es.array.includes.js';
32
- import 'core-js/modules/es.string.includes.js';
33
- import 'core-js/modules/es.object.values.js';
34
- import 'core-js/modules/es.array.find.js';
35
- import 'core-js/modules/es.array.concat.js';
36
- import 'core-js/modules/es.regexp.exec.js';
37
- import 'core-js/modules/es.string.split.js';
38
- import 'core-js/modules/es.array.join.js';
39
- import 'core-js/modules/es.date.to-string.js';
40
- import 'core-js/modules/es.regexp.to-string.js';
41
- import 'core-js/modules/es.string.match.js';
42
- import 'core-js/modules/es.array.reduce.js';
43
- import 'core-js/modules/es.number.is-nan.js';
44
- import 'core-js/modules/es.number.constructor.js';
45
- import 'core-js/modules/es.number.parse-float.js';
46
- import 'core-js/modules/es.set.js';
47
- import 'core-js/modules/es.array.index-of.js';
48
- import 'core-js/modules/es.string.trim.js';
49
2
  import dayjs from 'dayjs';
50
3
  import quarterOfYear from 'dayjs/plugin/quarterOfYear';
51
4
  import en from 'dayjs/locale/en';
52
- import { fromPairs, toPairs, equals, clone, indexBy, prop, pipe, map, filter, reduce, minBy, maxBy, flatten, pluck, mergeDeepLeft, mergeAll, uniq, dropLast, groupBy, unnest as unnest$1 } from 'ramda';
53
- import 'core-js/modules/es.object.entries.js';
54
- import 'core-js/modules/es.array.every.js';
55
- import 'core-js/modules/es.array.splice.js';
56
- import 'core-js/modules/es.function.name.js';
57
- import 'core-js/modules/es.array.sort.js';
58
- import 'core-js/modules/web.url-search-params.js';
5
+ import { fromPairs, toPairs, equals, clone, indexBy, prop, mergeDeepLeft, pipe, map, filter, reduce, minBy, maxBy, flatten, pluck, mergeAll, uniq, dropLast, groupBy, unnest as unnest$1 } from 'ramda';
59
6
  import fetch from 'cross-fetch';
60
7
  import 'url-search-params-polyfill';
61
- import 'core-js/modules/es.reflect.construct.js';
62
- import _inherits from '@babel/runtime/helpers/inherits';
63
- import _possibleConstructorReturn from '@babel/runtime/helpers/possibleConstructorReturn';
64
- import _getPrototypeOf from '@babel/runtime/helpers/getPrototypeOf';
65
- import _wrapNativeSuper from '@babel/runtime/helpers/wrapNativeSuper';
66
8
 
67
- var _excluded$2 = ["query"];
68
-
69
- function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
70
-
71
- function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
72
- var DEFAULT_GRANULARITY = 'day';
73
- var GRANULARITIES = [{
9
+ const DEFAULT_GRANULARITY = 'day';
10
+ const GRANULARITIES = [{
74
11
  name: undefined,
75
12
  title: 'w/o grouping'
76
13
  }, {
@@ -99,12 +36,8 @@ var GRANULARITIES = [{
99
36
  title: 'Year'
100
37
  }];
101
38
  function removeEmptyQueryFields(_query) {
102
- var query = _query || {};
103
- return fromPairs(toPairs(query).map(function (_ref) {
104
- var _ref2 = _slicedToArray(_ref, 2),
105
- key = _ref2[0],
106
- value = _ref2[1];
107
-
39
+ const query = _query || {};
40
+ return fromPairs(toPairs(query).map(([key, value]) => {
108
41
  if (['measures', 'dimensions', 'segments', 'timeDimensions', 'filters'].includes(key)) {
109
42
  if (Array.isArray(value) && value.length === 0) {
110
43
  return null;
@@ -123,53 +56,49 @@ function removeEmptyQueryFields(_query) {
123
56
  }).filter(Boolean));
124
57
  }
125
58
  function validateQuery(_query) {
126
- var query = _query || {};
127
- return removeEmptyQueryFields(_objectSpread$3(_objectSpread$3({}, query), {}, {
128
- filters: (query.filters || []).filter(function (f) {
129
- return f.operator;
130
- }),
131
- timeDimensions: (query.timeDimensions || []).filter(function (td) {
132
- return !(!td.dateRange && !td.granularity);
133
- })
134
- }));
59
+ const query = _query || {};
60
+ return removeEmptyQueryFields({ ...query,
61
+ filters: (query.filters || []).filter(f => f.operator),
62
+ timeDimensions: (query.timeDimensions || []).filter(td => !(!td.dateRange && !td.granularity))
63
+ });
135
64
  }
136
- function areQueriesEqual() {
137
- var query1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
138
- var query2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
65
+ function areQueriesEqual(query1 = {}, query2 = {}) {
139
66
  return equals(Object.entries(query1 && query1.order || {}), Object.entries(query2 && query2.order || {})) && equals(query1, query2);
140
67
  }
141
68
  function defaultOrder(query) {
142
- var granularity = (query.timeDimensions || []).find(function (d) {
143
- return d.granularity;
144
- });
69
+ const granularity = (query.timeDimensions || []).find(d => d.granularity);
145
70
 
146
71
  if (granularity) {
147
- return _defineProperty({}, granularity.dimension, 'asc');
72
+ return {
73
+ [granularity.dimension]: 'asc'
74
+ };
148
75
  } else if ((query.measures || []).length > 0 && (query.dimensions || []).length > 0) {
149
- return _defineProperty({}, query.measures[0], 'desc');
76
+ return {
77
+ [query.measures[0]]: 'desc'
78
+ };
150
79
  } else if ((query.dimensions || []).length > 0) {
151
- return _defineProperty({}, query.dimensions[0], 'asc');
80
+ return {
81
+ [query.dimensions[0]]: 'asc'
82
+ };
152
83
  }
153
84
 
154
85
  return {};
155
86
  }
156
- function defaultHeuristics(newState) {
157
- var oldQuery = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
158
- var options = arguments.length > 2 ? arguments[2] : undefined;
159
-
160
- var _clone = clone(newState),
161
- query = _clone.query,
162
- props = _objectWithoutProperties(_clone, _excluded$2);
163
-
164
- var meta = options.meta,
165
- sessionGranularity = options.sessionGranularity;
166
- var granularity = sessionGranularity || DEFAULT_GRANULARITY;
167
-
168
- var state = _objectSpread$3({
169
- query: query
170
- }, props);
171
-
172
- var newQuery = null;
87
+ function defaultHeuristics(newState, oldQuery = {}, options) {
88
+ const {
89
+ query,
90
+ ...props
91
+ } = clone(newState);
92
+ const {
93
+ meta,
94
+ sessionGranularity
95
+ } = options;
96
+ const granularity = sessionGranularity || DEFAULT_GRANULARITY;
97
+ let state = {
98
+ query,
99
+ ...props
100
+ };
101
+ let newQuery = null;
173
102
 
174
103
  if (!areQueriesEqual(query, oldQuery)) {
175
104
  newQuery = query;
@@ -181,110 +110,99 @@ function defaultHeuristics(newState) {
181
110
 
182
111
  if (newQuery) {
183
112
  if ((oldQuery.timeDimensions || []).length === 1 && (newQuery.timeDimensions || []).length === 1 && newQuery.timeDimensions[0].granularity && oldQuery.timeDimensions[0].granularity !== newQuery.timeDimensions[0].granularity) {
184
- state = _objectSpread$3(_objectSpread$3({}, state), {}, {
113
+ state = { ...state,
185
114
  sessionGranularity: newQuery.timeDimensions[0].granularity
186
- });
115
+ };
187
116
  }
188
117
 
189
118
  if ((oldQuery.measures || []).length === 0 && (newQuery.measures || []).length > 0 || (oldQuery.measures || []).length === 1 && (newQuery.measures || []).length === 1 && oldQuery.measures[0] !== newQuery.measures[0]) {
190
- var _ref6 = newQuery.timeDimensions || [],
191
- _ref7 = _slicedToArray(_ref6, 1),
192
- td = _ref7[0];
193
-
194
- var defaultTimeDimension = meta.defaultTimeDimensionNameFor(newQuery.measures[0]);
195
- newQuery = _objectSpread$3(_objectSpread$3({}, newQuery), {}, {
119
+ const [td] = newQuery.timeDimensions || [];
120
+ const defaultTimeDimension = meta.defaultTimeDimensionNameFor(newQuery.measures[0]);
121
+ newQuery = { ...newQuery,
196
122
  timeDimensions: defaultTimeDimension ? [{
197
123
  dimension: defaultTimeDimension,
198
124
  granularity: td && td.granularity || granularity,
199
125
  dateRange: td && td.dateRange
200
126
  }] : []
201
- });
202
- return _objectSpread$3(_objectSpread$3({}, state), {}, {
127
+ };
128
+ return { ...state,
203
129
  pivotConfig: null,
204
130
  shouldApplyHeuristicOrder: true,
205
131
  query: newQuery,
206
132
  chartType: defaultTimeDimension ? 'line' : 'number'
207
- });
133
+ };
208
134
  }
209
135
 
210
136
  if ((oldQuery.dimensions || []).length === 0 && (newQuery.dimensions || []).length > 0) {
211
- newQuery = _objectSpread$3(_objectSpread$3({}, newQuery), {}, {
212
- timeDimensions: (newQuery.timeDimensions || []).map(function (td) {
213
- return _objectSpread$3(_objectSpread$3({}, td), {}, {
214
- granularity: undefined
215
- });
216
- })
217
- });
218
- return _objectSpread$3(_objectSpread$3({}, state), {}, {
137
+ newQuery = { ...newQuery,
138
+ timeDimensions: (newQuery.timeDimensions || []).map(td => ({ ...td,
139
+ granularity: undefined
140
+ }))
141
+ };
142
+ return { ...state,
219
143
  pivotConfig: null,
220
144
  shouldApplyHeuristicOrder: true,
221
145
  query: newQuery,
222
146
  chartType: 'table'
223
- });
147
+ };
224
148
  }
225
149
 
226
150
  if ((oldQuery.dimensions || []).length > 0 && (newQuery.dimensions || []).length === 0) {
227
- newQuery = _objectSpread$3(_objectSpread$3({}, newQuery), {}, {
228
- timeDimensions: (newQuery.timeDimensions || []).map(function (td) {
229
- return _objectSpread$3(_objectSpread$3({}, td), {}, {
230
- granularity: td.granularity || granularity
231
- });
232
- })
233
- });
234
- return _objectSpread$3(_objectSpread$3({}, state), {}, {
151
+ newQuery = { ...newQuery,
152
+ timeDimensions: (newQuery.timeDimensions || []).map(td => ({ ...td,
153
+ granularity: td.granularity || granularity
154
+ }))
155
+ };
156
+ return { ...state,
235
157
  pivotConfig: null,
236
158
  shouldApplyHeuristicOrder: true,
237
159
  query: newQuery,
238
160
  chartType: (newQuery.timeDimensions || []).length ? 'line' : 'number'
239
- });
161
+ };
240
162
  }
241
163
 
242
164
  if (((oldQuery.dimensions || []).length > 0 || (oldQuery.measures || []).length > 0) && (newQuery.dimensions || []).length === 0 && (newQuery.measures || []).length === 0) {
243
- newQuery = _objectSpread$3(_objectSpread$3({}, newQuery), {}, {
165
+ newQuery = { ...newQuery,
244
166
  timeDimensions: [],
245
167
  filters: []
246
- });
247
- return _objectSpread$3(_objectSpread$3({}, state), {}, {
168
+ };
169
+ return { ...state,
248
170
  pivotConfig: null,
249
171
  shouldApplyHeuristicOrder: true,
250
172
  query: newQuery,
251
173
  sessionGranularity: null
252
- });
174
+ };
253
175
  }
254
176
 
255
177
  return state;
256
178
  }
257
179
 
258
180
  if (state.chartType) {
259
- var newChartType = state.chartType;
181
+ const newChartType = state.chartType;
260
182
 
261
183
  if ((newChartType === 'line' || newChartType === 'area') && (oldQuery.timeDimensions || []).length === 1 && !oldQuery.timeDimensions[0].granularity) {
262
- var _oldQuery$timeDimensi = _slicedToArray(oldQuery.timeDimensions, 1),
263
- _td = _oldQuery$timeDimensi[0];
264
-
265
- return _objectSpread$3(_objectSpread$3({}, state), {}, {
184
+ const [td] = oldQuery.timeDimensions;
185
+ return { ...state,
266
186
  pivotConfig: null,
267
- query: _objectSpread$3(_objectSpread$3({}, oldQuery), {}, {
268
- timeDimensions: [_objectSpread$3(_objectSpread$3({}, _td), {}, {
269
- granularity: granularity
270
- })]
271
- })
272
- });
187
+ query: { ...oldQuery,
188
+ timeDimensions: [{ ...td,
189
+ granularity
190
+ }]
191
+ }
192
+ };
273
193
  }
274
194
 
275
195
  if ((newChartType === 'pie' || newChartType === 'table' || newChartType === 'number') && (oldQuery.timeDimensions || []).length === 1 && oldQuery.timeDimensions[0].granularity) {
276
- var _oldQuery$timeDimensi2 = _slicedToArray(oldQuery.timeDimensions, 1),
277
- _td2 = _oldQuery$timeDimensi2[0];
278
-
279
- return _objectSpread$3(_objectSpread$3({}, state), {}, {
196
+ const [td] = oldQuery.timeDimensions;
197
+ return { ...state,
280
198
  pivotConfig: null,
281
199
  shouldApplyHeuristicOrder: true,
282
- query: _objectSpread$3(_objectSpread$3({}, oldQuery), {}, {
283
- timeDimensions: [_objectSpread$3(_objectSpread$3({}, _td2), {}, {
200
+ query: { ...oldQuery,
201
+ timeDimensions: [{ ...td,
284
202
  granularity: undefined
285
- })]
286
- })
287
- });
203
+ }]
204
+ }
205
+ };
288
206
  }
289
207
  }
290
208
 
@@ -295,18 +213,15 @@ function isQueryPresent(query) {
295
213
  return false;
296
214
  }
297
215
 
298
- return (Array.isArray(query) ? query : [query]).every(function (q) {
299
- return q.measures && q.measures.length || q.dimensions && q.dimensions.length || q.timeDimensions && q.timeDimensions.length;
300
- });
216
+ return (Array.isArray(query) ? query : [query]).every(q => q.measures && q.measures.length || q.dimensions && q.dimensions.length || q.timeDimensions && q.timeDimensions.length);
301
217
  }
302
218
  function movePivotItem(pivotConfig, sourceIndex, destinationIndex, sourceAxis, destinationAxis) {
303
- var nextPivotConfig = _objectSpread$3(_objectSpread$3({}, pivotConfig), {}, {
304
- x: _toConsumableArray(pivotConfig.x),
305
- y: _toConsumableArray(pivotConfig.y)
306
- });
307
-
308
- var id = pivotConfig[sourceAxis][sourceIndex];
309
- var lastIndex = nextPivotConfig[destinationAxis].length - 1;
219
+ const nextPivotConfig = { ...pivotConfig,
220
+ x: [...pivotConfig.x],
221
+ y: [...pivotConfig.y]
222
+ };
223
+ const id = pivotConfig[sourceAxis][sourceIndex];
224
+ const lastIndex = nextPivotConfig[destinationAxis].length - 1;
310
225
 
311
226
  if (id === 'measures') {
312
227
  destinationIndex = lastIndex + 1;
@@ -319,148 +234,87 @@ function movePivotItem(pivotConfig, sourceIndex, destinationIndex, sourceAxis, d
319
234
  return nextPivotConfig;
320
235
  }
321
236
  function moveItemInArray(list, sourceIndex, destinationIndex) {
322
- var result = _toConsumableArray(list);
323
-
324
- var _result$splice = result.splice(sourceIndex, 1),
325
- _result$splice2 = _slicedToArray(_result$splice, 1),
326
- removed = _result$splice2[0];
327
-
237
+ const result = [...list];
238
+ const [removed] = result.splice(sourceIndex, 1);
328
239
  result.splice(destinationIndex, 0, removed);
329
240
  return result;
330
241
  }
331
- function flattenFilters() {
332
- var filters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
333
- return filters.reduce(function (memo, filter) {
242
+ function flattenFilters(filters = []) {
243
+ return filters.reduce((memo, filter) => {
334
244
  if (filter.or || filter.and) {
335
- return [].concat(_toConsumableArray(memo), _toConsumableArray(flattenFilters(filter.or || filter.and)));
245
+ return [...memo, ...flattenFilters(filter.or || filter.and)];
336
246
  }
337
247
 
338
- return [].concat(_toConsumableArray(memo), [filter]);
248
+ return [...memo, filter];
339
249
  }, []);
340
250
  }
341
- function getQueryMembers() {
342
- var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
343
- var keys = ['measures', 'dimensions', 'segments'];
344
- var members = new Set();
345
- keys.forEach(function (key) {
346
- return (query[key] || []).forEach(function (member) {
347
- return members.add(member);
348
- });
349
- });
350
- (query.timeDimensions || []).forEach(function (td) {
351
- return members.add(td.dimension);
352
- });
353
- flattenFilters(query.filters).forEach(function (filter) {
354
- return members.add(filter.dimension || filter.member);
355
- });
356
- return _toConsumableArray(members);
251
+ function getQueryMembers(query = {}) {
252
+ const keys = ['measures', 'dimensions', 'segments'];
253
+ const members = new Set();
254
+ keys.forEach(key => (query[key] || []).forEach(member => members.add(member)));
255
+ (query.timeDimensions || []).forEach(td => members.add(td.dimension));
256
+ flattenFilters(query.filters).forEach(filter => members.add(filter.dimension || filter.member));
257
+ return [...members];
357
258
  }
358
259
  function getOrderMembersFromOrder(orderMembers, order) {
359
- var ids = new Set();
360
- var indexedOrderMembers = indexBy(prop('id'), orderMembers);
361
- var entries = Array.isArray(order) ? order : Object.entries(order || {});
362
- var nextOrderMembers = [];
363
- entries.forEach(function (_ref8) {
364
- var _ref9 = _slicedToArray(_ref8, 2),
365
- memberId = _ref9[0],
366
- currentOrder = _ref9[1];
367
-
260
+ const ids = new Set();
261
+ const indexedOrderMembers = indexBy(prop('id'), orderMembers);
262
+ const entries = Array.isArray(order) ? order : Object.entries(order || {});
263
+ const nextOrderMembers = [];
264
+ entries.forEach(([memberId, currentOrder]) => {
368
265
  if (currentOrder !== 'none' && indexedOrderMembers[memberId]) {
369
266
  ids.add(memberId);
370
- nextOrderMembers.push(_objectSpread$3(_objectSpread$3({}, indexedOrderMembers[memberId]), {}, {
267
+ nextOrderMembers.push({ ...indexedOrderMembers[memberId],
371
268
  order: currentOrder
372
- }));
269
+ });
373
270
  }
374
271
  });
375
- orderMembers.forEach(function (member) {
272
+ orderMembers.forEach(member => {
376
273
  if (!ids.has(member.id)) {
377
- nextOrderMembers.push(_objectSpread$3(_objectSpread$3({}, member), {}, {
274
+ nextOrderMembers.push({ ...member,
378
275
  order: member.order || 'none'
379
- }));
276
+ });
380
277
  }
381
278
  });
382
279
  return nextOrderMembers;
383
280
  }
384
281
  function aliasSeries(values, index, pivotConfig, duplicateMeasures) {
385
- var nonNullValues = values.filter(function (value) {
386
- return value != null;
387
- });
282
+ const nonNullValues = values.filter(value => value != null);
388
283
 
389
284
  if (pivotConfig && pivotConfig.aliasSeries && pivotConfig.aliasSeries[index]) {
390
- return [pivotConfig.aliasSeries[index]].concat(_toConsumableArray(nonNullValues));
285
+ return [pivotConfig.aliasSeries[index], ...nonNullValues];
391
286
  } else if (duplicateMeasures.has(nonNullValues[0])) {
392
- return [index].concat(_toConsumableArray(nonNullValues));
287
+ return [index, ...nonNullValues];
393
288
  }
394
289
 
395
290
  return nonNullValues;
396
291
  }
397
292
 
398
- var _excluded$1 = ["x"],
399
- _excluded2 = ["key"],
400
- _excluded3 = ["title", "shortTitle"];
401
-
402
- function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
403
-
404
- function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
405
293
  dayjs.extend(quarterOfYear); // When granularity is week, weekStart Value must be 1. However, since the client can change it globally (https://day.js.org/docs/en/i18n/changing-locale)
406
294
  // So the function below has been added.
407
295
 
408
- var internalDayjs = function internalDayjs() {
409
- return dayjs.apply(void 0, arguments).locale(_objectSpread$2(_objectSpread$2({}, en), {}, {
410
- weekStart: 1
411
- }));
412
- };
296
+ const internalDayjs = (...args) => dayjs(...args).locale({ ...en,
297
+ weekStart: 1
298
+ });
413
299
 
414
- var TIME_SERIES = {
415
- day: function day(range) {
416
- return range.by('d').map(function (d) {
417
- return d.format('YYYY-MM-DDT00:00:00.000');
418
- });
419
- },
420
- month: function month(range) {
421
- return range.snapTo('month').by('M').map(function (d) {
422
- return d.format('YYYY-MM-01T00:00:00.000');
423
- });
424
- },
425
- year: function year(range) {
426
- return range.snapTo('year').by('y').map(function (d) {
427
- return d.format('YYYY-01-01T00:00:00.000');
428
- });
429
- },
430
- hour: function hour(range) {
431
- return range.by('h').map(function (d) {
432
- return d.format('YYYY-MM-DDTHH:00:00.000');
433
- });
434
- },
435
- minute: function minute(range) {
436
- return range.by('m').map(function (d) {
437
- return d.format('YYYY-MM-DDTHH:mm:00.000');
438
- });
439
- },
440
- second: function second(range) {
441
- return range.by('s').map(function (d) {
442
- return d.format('YYYY-MM-DDTHH:mm:ss.000');
443
- });
444
- },
445
- week: function week(range) {
446
- return range.snapTo('week').by('w').map(function (d) {
447
- return d.startOf('week').format('YYYY-MM-DDT00:00:00.000');
448
- });
449
- },
450
- quarter: function quarter(range) {
451
- return range.snapTo('quarter').by('quarter').map(function (d) {
452
- return d.startOf('quarter').format('YYYY-MM-DDT00:00:00.000');
453
- });
454
- }
300
+ const TIME_SERIES = {
301
+ day: range => range.by('d').map(d => d.format('YYYY-MM-DDT00:00:00.000')),
302
+ month: range => range.snapTo('month').by('M').map(d => d.format('YYYY-MM-01T00:00:00.000')),
303
+ year: range => range.snapTo('year').by('y').map(d => d.format('YYYY-01-01T00:00:00.000')),
304
+ hour: range => range.by('h').map(d => d.format('YYYY-MM-DDTHH:00:00.000')),
305
+ minute: range => range.by('m').map(d => d.format('YYYY-MM-DDTHH:mm:00.000')),
306
+ second: range => range.by('s').map(d => d.format('YYYY-MM-DDTHH:mm:ss.000')),
307
+ week: range => range.snapTo('week').by('w').map(d => d.startOf('week').format('YYYY-MM-DDT00:00:00.000')),
308
+ quarter: range => range.snapTo('quarter').by('quarter').map(d => d.startOf('quarter').format('YYYY-MM-DDT00:00:00.000'))
455
309
  };
456
- var DateRegex = /^\d\d\d\d-\d\d-\d\d$/;
457
- var LocalDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z?$/;
310
+ const DateRegex = /^\d\d\d\d-\d\d-\d\d$/;
311
+ const LocalDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z?$/;
458
312
 
459
- var groupByToPairs = function groupByToPairs(keyFn) {
460
- var acc = new Map();
461
- return function (data) {
462
- data.forEach(function (row) {
463
- var key = keyFn(row);
313
+ const groupByToPairs = keyFn => {
314
+ const acc = new Map();
315
+ return data => {
316
+ data.forEach(row => {
317
+ const key = keyFn(row);
464
318
 
465
319
  if (!acc.has(key)) {
466
320
  acc.set(key, []);
@@ -472,49 +326,51 @@ var groupByToPairs = function groupByToPairs(keyFn) {
472
326
  };
473
327
  };
474
328
 
475
- var unnest = function unnest(arr) {
476
- var res = [];
477
- arr.forEach(function (subArr) {
478
- subArr.forEach(function (element) {
479
- return res.push(element);
480
- });
329
+ const unnest = arr => {
330
+ const res = [];
331
+ arr.forEach(subArr => {
332
+ subArr.forEach(element => res.push(element));
481
333
  });
482
334
  return res;
483
335
  };
484
336
 
485
- var dayRange = function dayRange(from, to) {
486
- return {
487
- by: function by(value) {
488
- var results = [];
489
- var start = internalDayjs(from);
490
- var end = internalDayjs(to);
337
+ const dayRange = (from, to) => ({
338
+ by: value => {
339
+ const results = [];
340
+ let start = internalDayjs(from);
341
+ const end = internalDayjs(to);
491
342
 
492
- while (start.isBefore(end) || start.isSame(end)) {
493
- results.push(start);
494
- start = start.add(1, value);
495
- }
343
+ while (start.isBefore(end) || start.isSame(end)) {
344
+ results.push(start);
345
+ start = start.add(1, value);
346
+ }
496
347
 
497
- return results;
498
- },
499
- snapTo: function snapTo(value) {
500
- return dayRange(internalDayjs(from).startOf(value), internalDayjs(to).endOf(value));
501
- },
502
- start: internalDayjs(from),
503
- end: internalDayjs(to)
504
- };
505
- };
506
- var QUERY_TYPE = {
348
+ return results;
349
+ },
350
+ snapTo: value => dayRange(internalDayjs(from).startOf(value), internalDayjs(to).endOf(value)),
351
+ start: internalDayjs(from),
352
+ end: internalDayjs(to)
353
+ });
354
+ const QUERY_TYPE = {
507
355
  REGULAR_QUERY: 'regularQuery',
508
356
  COMPARE_DATE_RANGE_QUERY: 'compareDateRangeQuery',
509
357
  BLENDING_QUERY: 'blendingQuery'
510
358
  };
511
359
 
512
- var ResultSet = /*#__PURE__*/function () {
513
- function ResultSet(loadResponse) {
514
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
360
+ class ResultSet {
361
+ static measureFromAxis(axisValues) {
362
+ return axisValues[axisValues.length - 1];
363
+ }
364
+
365
+ static timeDimensionMember(td) {
366
+ return `${td.dimension}.${td.granularity}`;
367
+ }
515
368
 
516
- _classCallCheck(this, ResultSet);
369
+ static deserialize(data, options = {}) {
370
+ return new ResultSet(data.loadResponse, options);
371
+ }
517
372
 
373
+ constructor(loadResponse, options = {}) {
518
374
  this.loadResponse = loadResponse;
519
375
 
520
376
  if (this.loadResponse.queryType != null) {
@@ -522,9 +378,9 @@ var ResultSet = /*#__PURE__*/function () {
522
378
  this.loadResponses = loadResponse.results;
523
379
  } else {
524
380
  this.queryType = QUERY_TYPE.REGULAR_QUERY;
525
- this.loadResponse.pivotQuery = _objectSpread$2(_objectSpread$2({}, loadResponse.query), {}, {
381
+ this.loadResponse.pivotQuery = { ...loadResponse.query,
526
382
  queryType: this.queryType
527
- });
383
+ };
528
384
  this.loadResponses = [loadResponse];
529
385
  }
530
386
 
@@ -537,803 +393,586 @@ var ResultSet = /*#__PURE__*/function () {
537
393
  this.backwardCompatibleData = [];
538
394
  }
539
395
 
540
- _createClass(ResultSet, [{
541
- key: "drillDown",
542
- value: function drillDown(drillDownLocator, pivotConfig) {
543
- if (this.queryType === QUERY_TYPE.COMPARE_DATE_RANGE_QUERY) {
544
- throw new Error('compareDateRange drillDown query is not currently supported');
545
- }
396
+ drillDown(drillDownLocator, pivotConfig) {
397
+ if (this.queryType === QUERY_TYPE.COMPARE_DATE_RANGE_QUERY) {
398
+ throw new Error('compareDateRange drillDown query is not currently supported');
399
+ }
546
400
 
547
- if (this.queryType === QUERY_TYPE.BLENDING_QUERY) {
548
- throw new Error('Data blending drillDown query is not currently supported');
549
- }
401
+ if (this.queryType === QUERY_TYPE.BLENDING_QUERY) {
402
+ throw new Error('Data blending drillDown query is not currently supported');
403
+ }
550
404
 
551
- var _drillDownLocator$xVa = drillDownLocator.xValues,
552
- xValues = _drillDownLocator$xVa === void 0 ? [] : _drillDownLocator$xVa,
553
- _drillDownLocator$yVa = drillDownLocator.yValues,
554
- yValues = _drillDownLocator$yVa === void 0 ? [] : _drillDownLocator$yVa;
555
- var normalizedPivotConfig = this.normalizePivotConfig(pivotConfig);
556
- var values = [];
557
- normalizedPivotConfig.x.forEach(function (member, currentIndex) {
558
- return values.push([member, xValues[currentIndex]]);
559
- });
560
- normalizedPivotConfig.y.forEach(function (member, currentIndex) {
561
- return values.push([member, yValues[currentIndex]]);
562
- });
405
+ const {
406
+ xValues = [],
407
+ yValues = []
408
+ } = drillDownLocator;
409
+ const normalizedPivotConfig = this.normalizePivotConfig(pivotConfig);
410
+ const values = [];
411
+ normalizedPivotConfig.x.forEach((member, currentIndex) => values.push([member, xValues[currentIndex]]));
412
+ normalizedPivotConfig.y.forEach((member, currentIndex) => values.push([member, yValues[currentIndex]]));
413
+ const {
414
+ filters: parentFilters = [],
415
+ segments = []
416
+ } = this.query();
417
+ const {
418
+ measures
419
+ } = this.loadResponses[0].annotation;
420
+ let [, measureName] = values.find(([member]) => member === 'measures') || [];
421
+
422
+ if (measureName === undefined) {
423
+ [measureName] = Object.keys(measures);
424
+ }
563
425
 
564
- var _this$query = this.query(),
565
- _this$query$filters = _this$query.filters,
566
- parentFilters = _this$query$filters === void 0 ? [] : _this$query$filters,
567
- _this$query$segments = _this$query.segments,
568
- segments = _this$query$segments === void 0 ? [] : _this$query$segments;
426
+ if (!(measures[measureName] && measures[measureName].drillMembers || []).length) {
427
+ return null;
428
+ }
569
429
 
570
- var measures = this.loadResponses[0].annotation.measures;
430
+ const filters = [{
431
+ member: measureName,
432
+ operator: 'measureFilter'
433
+ }, ...parentFilters];
434
+ const timeDimensions = [];
435
+ values.filter(([member]) => member !== 'measures').forEach(([member, value]) => {
436
+ const [cubeName, dimension, granularity] = member.split('.');
437
+
438
+ if (granularity !== undefined) {
439
+ const range = dayRange(value, value).snapTo(granularity);
440
+ timeDimensions.push({
441
+ dimension: [cubeName, dimension].join('.'),
442
+ dateRange: [range.start, range.end].map(dt => dt.format('YYYY-MM-DDTHH:mm:ss.SSS'))
443
+ });
444
+ } else if (value == null) {
445
+ filters.push({
446
+ member,
447
+ operator: 'notSet'
448
+ });
449
+ } else {
450
+ filters.push({
451
+ member,
452
+ operator: 'equals',
453
+ values: [value.toString()]
454
+ });
455
+ }
456
+ });
457
+ const {
458
+ query
459
+ } = this.loadResponses[0];
571
460
 
572
- var _ref = values.find(function (_ref3) {
573
- var _ref4 = _slicedToArray(_ref3, 1),
574
- member = _ref4[0];
461
+ if (timeDimensions.length === 0 && query.timeDimensions.length > 0 && query.timeDimensions[0].granularity == null) {
462
+ timeDimensions.push(query.timeDimensions[0]);
463
+ }
575
464
 
576
- return member === 'measures';
577
- }) || [],
578
- _ref2 = _slicedToArray(_ref, 2),
579
- measureName = _ref2[1];
465
+ return { ...measures[measureName].drillMembersGrouped,
466
+ filters,
467
+ ...(segments.length > 0 ? {
468
+ segments
469
+ } : {}),
470
+ timeDimensions,
471
+ segments,
472
+ timezone: query.timezone
473
+ };
474
+ }
580
475
 
581
- if (measureName === undefined) {
582
- var _Object$keys = Object.keys(measures);
476
+ series(pivotConfig) {
477
+ return this.seriesNames(pivotConfig).map(({
478
+ title,
479
+ key
480
+ }) => ({
481
+ title,
482
+ key,
483
+ series: this.chartPivot(pivotConfig).map(({
484
+ x,
485
+ ...obj
486
+ }) => ({
487
+ value: obj[key],
488
+ x
489
+ }))
490
+ }));
491
+ }
583
492
 
584
- var _Object$keys2 = _slicedToArray(_Object$keys, 1);
493
+ axisValues(axis, resultIndex = 0) {
494
+ const {
495
+ query
496
+ } = this.loadResponses[resultIndex];
497
+ return row => {
498
+ const value = measure => axis.filter(d => d !== 'measures').map(d => row[d] != null ? row[d] : null).concat(measure ? [measure] : []);
585
499
 
586
- measureName = _Object$keys2[0];
500
+ if (axis.find(d => d === 'measures') && (query.measures || []).length) {
501
+ return query.measures.map(value);
587
502
  }
588
503
 
589
- if (!(measures[measureName] && measures[measureName].drillMembers || []).length) {
590
- return null;
504
+ return [value()];
505
+ };
506
+ }
507
+
508
+ axisValuesString(axisValues, delimiter) {
509
+ const formatValue = v => {
510
+ if (v == null) {
511
+ return '∅';
512
+ } else if (v === '') {
513
+ return '[Empty string]';
514
+ } else {
515
+ return v;
591
516
  }
517
+ };
592
518
 
593
- var filters = [{
594
- member: measureName,
595
- operator: 'measureFilter'
596
- }].concat(_toConsumableArray(parentFilters));
597
- var timeDimensions = [];
598
- values.filter(function (_ref5) {
599
- var _ref6 = _slicedToArray(_ref5, 1),
600
- member = _ref6[0];
601
-
602
- return member !== 'measures';
603
- }).forEach(function (_ref7) {
604
- var _ref8 = _slicedToArray(_ref7, 2),
605
- member = _ref8[0],
606
- value = _ref8[1];
607
-
608
- var _member$split = member.split('.'),
609
- _member$split2 = _slicedToArray(_member$split, 3),
610
- cubeName = _member$split2[0],
611
- dimension = _member$split2[1],
612
- granularity = _member$split2[2];
613
-
614
- if (granularity !== undefined) {
615
- var range = dayRange(value, value).snapTo(granularity);
616
- timeDimensions.push({
617
- dimension: [cubeName, dimension].join('.'),
618
- dateRange: [range.start, range.end].map(function (dt) {
619
- return dt.format('YYYY-MM-DDTHH:mm:ss.SSS');
620
- })
621
- });
622
- } else if (value == null) {
623
- filters.push({
624
- member: member,
625
- operator: 'notSet'
626
- });
627
- } else {
628
- filters.push({
629
- member: member,
630
- operator: 'equals',
631
- values: [value.toString()]
632
- });
633
- }
634
- });
635
- var query = this.loadResponses[0].query;
519
+ return axisValues.map(formatValue).join(delimiter || ', ');
520
+ }
636
521
 
637
- if (timeDimensions.length === 0 && query.timeDimensions.length > 0 && query.timeDimensions[0].granularity == null) {
638
- timeDimensions.push(query.timeDimensions[0]);
639
- }
522
+ static getNormalizedPivotConfig(query = {}, pivotConfig = null) {
523
+ const defaultPivotConfig = {
524
+ x: [],
525
+ y: [],
526
+ fillMissingDates: true,
527
+ joinDateRange: false
528
+ };
529
+ const {
530
+ measures = [],
531
+ dimensions = []
532
+ } = query;
533
+ const timeDimensions = (query.timeDimensions || []).filter(td => !!td.granularity);
534
+ pivotConfig = pivotConfig || (timeDimensions.length ? {
535
+ x: timeDimensions.map(td => ResultSet.timeDimensionMember(td)),
536
+ y: dimensions
537
+ } : {
538
+ x: dimensions,
539
+ y: []
540
+ });
541
+ pivotConfig = mergeDeepLeft(pivotConfig, defaultPivotConfig);
640
542
 
641
- return _objectSpread$2(_objectSpread$2(_objectSpread$2({}, measures[measureName].drillMembersGrouped), {}, {
642
- filters: filters
643
- }, segments.length > 0 ? {
644
- segments: segments
645
- } : {}), {}, {
646
- timeDimensions: timeDimensions,
647
- segments: segments,
648
- timezone: query.timezone
649
- });
650
- }
651
- }, {
652
- key: "series",
653
- value: function series(pivotConfig) {
654
- var _this = this;
543
+ const substituteTimeDimensionMembers = axis => axis.map(subDim => timeDimensions.find(td => td.dimension === subDim) && !dimensions.find(d => d === subDim) ? ResultSet.timeDimensionMember(query.timeDimensions.find(td => td.dimension === subDim)) : subDim);
655
544
 
656
- return this.seriesNames(pivotConfig).map(function (_ref9) {
657
- var title = _ref9.title,
658
- key = _ref9.key;
659
- return {
660
- title: title,
661
- key: key,
662
- series: _this.chartPivot(pivotConfig).map(function (_ref10) {
663
- var x = _ref10.x,
664
- obj = _objectWithoutProperties(_ref10, _excluded$1);
665
-
666
- return {
667
- value: obj[key],
668
- x: x
669
- };
670
- })
671
- };
672
- });
673
- }
674
- }, {
675
- key: "axisValues",
676
- value: function axisValues(axis) {
677
- var resultIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
678
- var query = this.loadResponses[resultIndex].query;
679
- return function (row) {
680
- var value = function value(measure) {
681
- return axis.filter(function (d) {
682
- return d !== 'measures';
683
- }).map(function (d) {
684
- return row[d] != null ? row[d] : null;
685
- }).concat(measure ? [measure] : []);
686
- };
545
+ pivotConfig.x = substituteTimeDimensionMembers(pivotConfig.x);
546
+ pivotConfig.y = substituteTimeDimensionMembers(pivotConfig.y);
547
+ const allIncludedDimensions = pivotConfig.x.concat(pivotConfig.y);
548
+ const allDimensions = timeDimensions.map(td => ResultSet.timeDimensionMember(td)).concat(dimensions);
687
549
 
688
- if (axis.find(function (d) {
689
- return d === 'measures';
690
- }) && (query.measures || []).length) {
691
- return query.measures.map(value);
692
- }
550
+ const dimensionFilter = key => allDimensions.includes(key) || key === 'measures';
693
551
 
694
- return [value()];
695
- };
696
- }
697
- }, {
698
- key: "axisValuesString",
699
- value: function axisValuesString(axisValues, delimiter) {
700
- var formatValue = function formatValue(v) {
701
- if (v == null) {
702
- return '∅';
703
- } else if (v === '') {
704
- return '[Empty string]';
705
- } else {
706
- return v;
707
- }
708
- };
552
+ pivotConfig.x = pivotConfig.x.concat(allDimensions.filter(d => !allIncludedDimensions.includes(d) && d !== 'compareDateRange')).filter(dimensionFilter);
553
+ pivotConfig.y = pivotConfig.y.filter(dimensionFilter);
709
554
 
710
- return axisValues.map(formatValue).join(delimiter || ', ');
555
+ if (!pivotConfig.x.concat(pivotConfig.y).find(d => d === 'measures')) {
556
+ pivotConfig.y.push('measures');
711
557
  }
712
- }, {
713
- key: "normalizePivotConfig",
714
- value: function normalizePivotConfig(pivotConfig) {
715
- return ResultSet.getNormalizedPivotConfig(this.loadResponse.pivotQuery, pivotConfig);
558
+
559
+ if (dimensions.includes('compareDateRange') && !pivotConfig.y.concat(pivotConfig.x).includes('compareDateRange')) {
560
+ pivotConfig.y.unshift('compareDateRange');
716
561
  }
717
- }, {
718
- key: "timeSeries",
719
- value: function timeSeries(timeDimension, resultIndex) {
720
- if (!timeDimension.granularity) {
721
- return null;
722
- }
723
562
 
724
- var dateRange = timeDimension.dateRange;
725
-
726
- if (!dateRange) {
727
- var member = ResultSet.timeDimensionMember(timeDimension);
728
- var dates = pipe(map(function (row) {
729
- return row[member] && internalDayjs(row[member]);
730
- }), filter(Boolean))(this.timeDimensionBackwardCompatibleData(resultIndex));
731
- dateRange = dates.length && [reduce(minBy(function (d) {
732
- return d.toDate();
733
- }), dates[0], dates), reduce(maxBy(function (d) {
734
- return d.toDate();
735
- }), dates[0], dates)] || null;
736
- }
563
+ if (!measures.length) {
564
+ pivotConfig.x = pivotConfig.x.filter(d => d !== 'measures');
565
+ pivotConfig.y = pivotConfig.y.filter(d => d !== 'measures');
566
+ }
737
567
 
738
- if (!dateRange) {
739
- return null;
740
- }
568
+ return pivotConfig;
569
+ }
741
570
 
742
- var padToDay = timeDimension.dateRange ? timeDimension.dateRange.find(function (d) {
743
- return d.match(DateRegex);
744
- }) : !['hour', 'minute', 'second'].includes(timeDimension.granularity);
571
+ normalizePivotConfig(pivotConfig) {
572
+ return ResultSet.getNormalizedPivotConfig(this.loadResponse.pivotQuery, pivotConfig);
573
+ }
745
574
 
746
- var _dateRange = dateRange,
747
- _dateRange2 = _slicedToArray(_dateRange, 2),
748
- start = _dateRange2[0],
749
- end = _dateRange2[1];
575
+ timeSeries(timeDimension, resultIndex) {
576
+ if (!timeDimension.granularity) {
577
+ return null;
578
+ }
750
579
 
751
- var range = dayRange(start, end);
580
+ let {
581
+ dateRange
582
+ } = timeDimension;
752
583
 
753
- if (!TIME_SERIES[timeDimension.granularity]) {
754
- throw new Error("Unsupported time granularity: ".concat(timeDimension.granularity));
755
- }
584
+ if (!dateRange) {
585
+ const member = ResultSet.timeDimensionMember(timeDimension);
586
+ const dates = pipe(map(row => row[member] && internalDayjs(row[member])), filter(Boolean))(this.timeDimensionBackwardCompatibleData(resultIndex));
587
+ dateRange = dates.length && [reduce(minBy(d => d.toDate()), dates[0], dates), reduce(maxBy(d => d.toDate()), dates[0], dates)] || null;
588
+ }
756
589
 
757
- return TIME_SERIES[timeDimension.granularity](padToDay ? range.snapTo('d') : range);
590
+ if (!dateRange) {
591
+ return null;
758
592
  }
759
- }, {
760
- key: "pivot",
761
- value: function pivot(pivotConfig) {
762
- var _this2 = this;
763
-
764
- pivotConfig = this.normalizePivotConfig(pivotConfig);
765
- var query = this.loadResponse.pivotQuery;
766
-
767
- var pivotImpl = function pivotImpl() {
768
- var resultIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
769
- var groupByXAxis = groupByToPairs(function (_ref11) {
770
- var xValues = _ref11.xValues;
771
- return _this2.axisValuesString(xValues);
772
- });
773
593
 
774
- var measureValue = function measureValue(row, measure) {
775
- return row[measure] || 0;
776
- };
594
+ const padToDay = timeDimension.dateRange ? timeDimension.dateRange.find(d => d.match(DateRegex)) : !['hour', 'minute', 'second'].includes(timeDimension.granularity);
595
+ const [start, end] = dateRange;
596
+ const range = dayRange(start, end);
777
597
 
778
- if (pivotConfig.fillMissingDates && pivotConfig.x.length === 1 && equals(pivotConfig.x, (query.timeDimensions || []).filter(function (td) {
779
- return Boolean(td.granularity);
780
- }).map(function (td) {
781
- return ResultSet.timeDimensionMember(td);
782
- }))) {
783
- var series = _this2.loadResponses.map(function (loadResponse) {
784
- return _this2.timeSeries(loadResponse.query.timeDimensions[0], resultIndex);
785
- });
598
+ if (!TIME_SERIES[timeDimension.granularity]) {
599
+ throw new Error(`Unsupported time granularity: ${timeDimension.granularity}`);
600
+ }
786
601
 
787
- if (series[0]) {
788
- groupByXAxis = function groupByXAxis(rows) {
789
- var byXValues = groupBy(function (_ref12) {
790
- var xValues = _ref12.xValues;
791
- return xValues[0];
792
- }, rows);
793
- return series[resultIndex].map(function (d) {
794
- return [d, byXValues[d] || [{
795
- xValues: [d],
796
- row: {}
797
- }]];
798
- });
799
- };
800
- }
602
+ return TIME_SERIES[timeDimension.granularity](padToDay ? range.snapTo('d') : range);
603
+ }
604
+
605
+ pivot(pivotConfig) {
606
+ pivotConfig = this.normalizePivotConfig(pivotConfig);
607
+ const {
608
+ pivotQuery: query
609
+ } = this.loadResponse;
610
+
611
+ const pivotImpl = (resultIndex = 0) => {
612
+ let groupByXAxis = groupByToPairs(({
613
+ xValues
614
+ }) => this.axisValuesString(xValues));
615
+
616
+ const measureValue = (row, measure) => row[measure] || 0;
617
+
618
+ if (pivotConfig.fillMissingDates && pivotConfig.x.length === 1 && equals(pivotConfig.x, (query.timeDimensions || []).filter(td => Boolean(td.granularity)).map(td => ResultSet.timeDimensionMember(td)))) {
619
+ const series = this.loadResponses.map(loadResponse => this.timeSeries(loadResponse.query.timeDimensions[0], resultIndex));
620
+
621
+ if (series[0]) {
622
+ groupByXAxis = rows => {
623
+ const byXValues = groupBy(({
624
+ xValues
625
+ }) => xValues[0], rows);
626
+ return series[resultIndex].map(d => [d, byXValues[d] || [{
627
+ xValues: [d],
628
+ row: {}
629
+ }]]);
630
+ };
801
631
  }
632
+ }
802
633
 
803
- var xGrouped = pipe(map(function (row) {
804
- return _this2.axisValues(pivotConfig.x, resultIndex)(row).map(function (xValues) {
805
- return {
806
- xValues: xValues,
807
- row: row
808
- };
809
- });
810
- }), unnest, groupByXAxis)(_this2.timeDimensionBackwardCompatibleData(resultIndex));
811
- var yValuesMap = {};
812
- xGrouped.forEach(function (_ref13) {
813
- var _ref14 = _slicedToArray(_ref13, 2),
814
- rows = _ref14[1];
815
-
816
- rows.forEach(function (_ref15) {
817
- var row = _ref15.row;
818
-
819
- _this2.axisValues(pivotConfig.y, resultIndex)(row).forEach(function (values) {
820
- if (Object.keys(row).length > 0) {
821
- yValuesMap[values.join()] = values;
822
- }
823
- });
634
+ const xGrouped = pipe(map(row => this.axisValues(pivotConfig.x, resultIndex)(row).map(xValues => ({
635
+ xValues,
636
+ row
637
+ }))), unnest, groupByXAxis)(this.timeDimensionBackwardCompatibleData(resultIndex));
638
+ const yValuesMap = {};
639
+ xGrouped.forEach(([, rows]) => {
640
+ rows.forEach(({
641
+ row
642
+ }) => {
643
+ this.axisValues(pivotConfig.y, resultIndex)(row).forEach(values => {
644
+ if (Object.keys(row).length > 0) {
645
+ yValuesMap[values.join()] = values;
646
+ }
824
647
  });
825
648
  });
826
- var allYValues = Object.values(yValuesMap);
827
- var measureOnX = Boolean(pivotConfig.x.find(function (d) {
828
- return d === 'measures';
829
- }));
830
- return xGrouped.map(function (_ref16) {
831
- var _ref17 = _slicedToArray(_ref16, 2),
832
- rows = _ref17[1];
833
-
834
- var xValues = rows[0].xValues;
835
- var yGrouped = {};
836
- rows.forEach(function (_ref18) {
837
- var row = _ref18.row;
838
-
839
- var arr = _this2.axisValues(pivotConfig.y, resultIndex)(row).map(function (yValues) {
840
- return {
841
- yValues: yValues,
842
- row: row
843
- };
844
- });
845
-
846
- arr.forEach(function (res) {
847
- yGrouped[_this2.axisValuesString(res.yValues)] = res;
848
- });
649
+ });
650
+ const allYValues = Object.values(yValuesMap);
651
+ const measureOnX = Boolean(pivotConfig.x.find(d => d === 'measures'));
652
+ return xGrouped.map(([, rows]) => {
653
+ const {
654
+ xValues
655
+ } = rows[0];
656
+ const yGrouped = {};
657
+ rows.forEach(({
658
+ row
659
+ }) => {
660
+ const arr = this.axisValues(pivotConfig.y, resultIndex)(row).map(yValues => ({
661
+ yValues,
662
+ row
663
+ }));
664
+ arr.forEach(res => {
665
+ yGrouped[this.axisValuesString(res.yValues)] = res;
849
666
  });
850
- return {
851
- xValues: xValues,
852
- yValuesArray: unnest(allYValues.map(function (yValues) {
853
- var measure = measureOnX ? ResultSet.measureFromAxis(xValues) : ResultSet.measureFromAxis(yValues);
854
- return [[yValues, measureValue((yGrouped[_this2.axisValuesString(yValues)] || {
855
- row: {}
856
- }).row, measure)]];
857
- }))
858
- };
859
667
  });
860
- };
861
-
862
- var pivots = this.loadResponses.length > 1 ? this.loadResponses.map(function (_, index) {
863
- return pivotImpl(index);
864
- }) : [];
865
- return pivots.length ? this.mergePivots(pivots, pivotConfig.joinDateRange) : pivotImpl();
866
- }
867
- }, {
868
- key: "mergePivots",
869
- value: function mergePivots(pivots, joinDateRange) {
870
- var minLengthPivot = pivots.reduce(function (memo, current) {
871
- return memo != null && current.length >= memo.length ? memo : current;
872
- }, null);
873
- return minLengthPivot.map(function (_, index) {
874
- var xValues = joinDateRange ? [pivots.map(function (pivot) {
875
- return pivot[index] && pivot[index].xValues || [];
876
- }).join(', ')] : minLengthPivot[index].xValues;
877
668
  return {
878
- xValues: xValues,
879
- yValuesArray: unnest(pivots.map(function (pivot) {
880
- return pivot[index].yValuesArray;
669
+ xValues,
670
+ yValuesArray: unnest(allYValues.map(yValues => {
671
+ const measure = measureOnX ? ResultSet.measureFromAxis(xValues) : ResultSet.measureFromAxis(yValues);
672
+ return [[yValues, measureValue((yGrouped[this.axisValuesString(yValues)] || {
673
+ row: {}
674
+ }).row, measure)]];
881
675
  }))
882
676
  };
883
677
  });
884
- }
885
- }, {
886
- key: "pivotedRows",
887
- value: function pivotedRows(pivotConfig) {
888
- // TODO
889
- return this.chartPivot(pivotConfig);
890
- }
891
- }, {
892
- key: "chartPivot",
893
- value: function chartPivot(pivotConfig) {
894
- var _this3 = this;
895
-
896
- var validate = function validate(value) {
897
- if (_this3.parseDateMeasures && LocalDateRegex.test(value)) {
898
- return new Date(value);
899
- } else if (!Number.isNaN(Number.parseFloat(value))) {
900
- return Number.parseFloat(value);
901
- }
902
-
903
- return value;
904
- };
905
-
906
- var duplicateMeasures = new Set();
907
-
908
- if (this.queryType === QUERY_TYPE.BLENDING_QUERY) {
909
- var allMeasures = flatten(this.loadResponses.map(function (_ref19) {
910
- var query = _ref19.query;
911
- return query.measures;
912
- }));
913
- allMeasures.filter(function (e, i, a) {
914
- return a.indexOf(e) !== i;
915
- }).forEach(function (m) {
916
- return duplicateMeasures.add(m);
917
- });
918
- }
919
-
920
- return this.pivot(pivotConfig).map(function (_ref20) {
921
- var xValues = _ref20.xValues,
922
- yValuesArray = _ref20.yValuesArray;
923
- var yValuesMap = {};
924
- yValuesArray.forEach(function (_ref21, i) {
925
- var _ref22 = _slicedToArray(_ref21, 2),
926
- yValues = _ref22[0],
927
- m = _ref22[1];
678
+ };
928
679
 
929
- yValuesMap[_this3.axisValuesString(aliasSeries(yValues, i, pivotConfig, duplicateMeasures), ',')] = m && validate(m);
930
- });
931
- return _objectSpread$2({
932
- x: _this3.axisValuesString(xValues, ','),
933
- xValues: xValues
934
- }, yValuesMap);
935
- });
936
- }
937
- }, {
938
- key: "tablePivot",
939
- value: function tablePivot(pivotConfig) {
940
- var normalizedPivotConfig = this.normalizePivotConfig(pivotConfig || {});
941
- var isMeasuresPresent = normalizedPivotConfig.x.concat(normalizedPivotConfig.y).includes('measures');
942
- return this.pivot(normalizedPivotConfig).map(function (_ref23) {
943
- var xValues = _ref23.xValues,
944
- yValuesArray = _ref23.yValuesArray;
945
- return fromPairs(normalizedPivotConfig.x.map(function (key, index) {
946
- return [key, xValues[index]];
947
- }).concat(isMeasuresPresent ? yValuesArray.map(function (_ref24) {
948
- var _ref25 = _slicedToArray(_ref24, 2),
949
- yValues = _ref25[0],
950
- measure = _ref25[1];
951
-
952
- return [yValues.length ? yValues.join() : 'value', measure];
953
- }) : []));
954
- });
955
- }
956
- }, {
957
- key: "tableColumns",
958
- value: function tableColumns(pivotConfig) {
959
- var normalizedPivotConfig = this.normalizePivotConfig(pivotConfig || {});
960
- var annotations = pipe(pluck('annotation'), reduce(mergeDeepLeft(), {}))(this.loadResponses);
961
- var flatMeta = Object.values(annotations).reduce(function (a, b) {
962
- return _objectSpread$2(_objectSpread$2({}, a), b);
963
- }, {});
964
- var schema = {};
965
-
966
- var extractFields = function extractFields(key) {
967
- var _ref26 = flatMeta[key] || {},
968
- title = _ref26.title,
969
- shortTitle = _ref26.shortTitle,
970
- type = _ref26.type,
971
- format = _ref26.format,
972
- meta = _ref26.meta;
680
+ const pivots = this.loadResponses.length > 1 ? this.loadResponses.map((_, index) => pivotImpl(index)) : [];
681
+ return pivots.length ? this.mergePivots(pivots, pivotConfig.joinDateRange) : pivotImpl();
682
+ }
973
683
 
974
- return {
975
- key: key,
976
- title: title,
977
- shortTitle: shortTitle,
978
- type: type,
979
- format: format,
980
- meta: meta
981
- };
684
+ mergePivots(pivots, joinDateRange) {
685
+ const minLengthPivot = pivots.reduce((memo, current) => memo != null && current.length >= memo.length ? memo : current, null);
686
+ return minLengthPivot.map((_, index) => {
687
+ const xValues = joinDateRange ? [pivots.map(pivot => pivot[index] && pivot[index].xValues || []).join(', ')] : minLengthPivot[index].xValues;
688
+ return {
689
+ xValues,
690
+ yValuesArray: unnest(pivots.map(pivot => pivot[index].yValuesArray))
982
691
  };
692
+ });
693
+ }
983
694
 
984
- var pivot = this.pivot(normalizedPivotConfig);
985
- (pivot[0] && pivot[0].yValuesArray || []).forEach(function (_ref27) {
986
- var _ref28 = _slicedToArray(_ref27, 1),
987
- yValues = _ref28[0];
988
-
989
- if (yValues.length > 0) {
990
- var currentItem = schema;
991
- yValues.forEach(function (value, index) {
992
- currentItem["_".concat(value)] = {
993
- key: value,
994
- memberId: normalizedPivotConfig.y[index] === 'measures' ? value : normalizedPivotConfig.y[index],
995
- children: currentItem["_".concat(value)] && currentItem["_".concat(value)].children || {}
996
- };
997
- currentItem = currentItem["_".concat(value)].children;
998
- });
999
- }
1000
- });
1001
-
1002
- var toColumns = function toColumns() {
1003
- var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1004
- var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
695
+ pivotedRows(pivotConfig) {
696
+ // TODO
697
+ return this.chartPivot(pivotConfig);
698
+ }
1005
699
 
1006
- if (Object.keys(item).length === 0) {
1007
- return [];
1008
- }
700
+ chartPivot(pivotConfig) {
701
+ const validate = value => {
702
+ if (this.parseDateMeasures && LocalDateRegex.test(value)) {
703
+ return new Date(value);
704
+ } else if (!Number.isNaN(Number.parseFloat(value))) {
705
+ return Number.parseFloat(value);
706
+ }
1009
707
 
1010
- return Object.values(item).map(function (_ref29) {
1011
- var key = _ref29.key,
1012
- currentItem = _objectWithoutProperties(_ref29, _excluded2);
708
+ return value;
709
+ };
1013
710
 
1014
- var children = toColumns(currentItem.children, [].concat(_toConsumableArray(path), [key]));
711
+ const duplicateMeasures = new Set();
1015
712
 
1016
- var _extractFields = extractFields(currentItem.memberId),
1017
- title = _extractFields.title,
1018
- shortTitle = _extractFields.shortTitle,
1019
- fields = _objectWithoutProperties(_extractFields, _excluded3);
713
+ if (this.queryType === QUERY_TYPE.BLENDING_QUERY) {
714
+ const allMeasures = flatten(this.loadResponses.map(({
715
+ query
716
+ }) => query.measures));
717
+ allMeasures.filter((e, i, a) => a.indexOf(e) !== i).forEach(m => duplicateMeasures.add(m));
718
+ }
1020
719
 
1021
- var dimensionValue = key !== currentItem.memberId || title == null ? key : '';
720
+ return this.pivot(pivotConfig).map(({
721
+ xValues,
722
+ yValuesArray
723
+ }) => {
724
+ const yValuesMap = {};
725
+ yValuesArray.forEach(([yValues, m], i) => {
726
+ yValuesMap[this.axisValuesString(aliasSeries(yValues, i, pivotConfig, duplicateMeasures), ',')] = m && validate(m);
727
+ });
728
+ return {
729
+ x: this.axisValuesString(xValues, ','),
730
+ xValues,
731
+ ...yValuesMap
732
+ };
733
+ });
734
+ }
1022
735
 
1023
- if (!children.length) {
1024
- return _objectSpread$2(_objectSpread$2({}, fields), {}, {
1025
- key: key,
1026
- dataIndex: [].concat(_toConsumableArray(path), [key]).join(),
1027
- title: [title, dimensionValue].join(' ').trim(),
1028
- shortTitle: dimensionValue || shortTitle
1029
- });
1030
- }
736
+ tablePivot(pivotConfig) {
737
+ const normalizedPivotConfig = this.normalizePivotConfig(pivotConfig || {});
738
+ const isMeasuresPresent = normalizedPivotConfig.x.concat(normalizedPivotConfig.y).includes('measures');
739
+ return this.pivot(normalizedPivotConfig).map(({
740
+ xValues,
741
+ yValuesArray
742
+ }) => fromPairs(normalizedPivotConfig.x.map((key, index) => [key, xValues[index]]).concat(isMeasuresPresent ? yValuesArray.map(([yValues, measure]) => [yValues.length ? yValues.join() : 'value', measure]) : [])));
743
+ }
1031
744
 
1032
- return _objectSpread$2(_objectSpread$2({}, fields), {}, {
1033
- key: key,
1034
- title: [title, dimensionValue].join(' ').trim(),
1035
- shortTitle: dimensionValue || shortTitle,
1036
- children: children
1037
- });
1038
- });
745
+ tableColumns(pivotConfig) {
746
+ const normalizedPivotConfig = this.normalizePivotConfig(pivotConfig || {});
747
+ const annotations = pipe(pluck('annotation'), reduce(mergeDeepLeft(), {}))(this.loadResponses);
748
+ const flatMeta = Object.values(annotations).reduce((a, b) => ({ ...a,
749
+ ...b
750
+ }), {});
751
+ const schema = {};
752
+
753
+ const extractFields = key => {
754
+ const {
755
+ title,
756
+ shortTitle,
757
+ type,
758
+ format,
759
+ meta
760
+ } = flatMeta[key] || {};
761
+ return {
762
+ key,
763
+ title,
764
+ shortTitle,
765
+ type,
766
+ format,
767
+ meta
1039
768
  };
769
+ };
1040
770
 
1041
- var otherColumns = [];
1042
-
1043
- if (!pivot.length && normalizedPivotConfig.y.includes('measures')) {
1044
- otherColumns = (this.loadResponses[0].query.measures || []).map(function (key) {
1045
- return _objectSpread$2(_objectSpread$2({}, extractFields(key)), {}, {
1046
- dataIndex: key
1047
- });
771
+ const pivot = this.pivot(normalizedPivotConfig);
772
+ (pivot[0] && pivot[0].yValuesArray || []).forEach(([yValues]) => {
773
+ if (yValues.length > 0) {
774
+ let currentItem = schema;
775
+ yValues.forEach((value, index) => {
776
+ currentItem[`_${value}`] = {
777
+ key: value,
778
+ memberId: normalizedPivotConfig.y[index] === 'measures' ? value : normalizedPivotConfig.y[index],
779
+ children: currentItem[`_${value}`] && currentItem[`_${value}`].children || {}
780
+ };
781
+ currentItem = currentItem[`_${value}`].children;
1048
782
  });
1049
- } // Syntatic column to display the measure value
1050
-
783
+ }
784
+ });
1051
785
 
1052
- if (!normalizedPivotConfig.y.length && normalizedPivotConfig.x.includes('measures')) {
1053
- otherColumns.push({
1054
- key: 'value',
1055
- dataIndex: 'value',
1056
- title: 'Value',
1057
- shortTitle: 'Value',
1058
- type: 'string'
1059
- });
786
+ const toColumns = (item = {}, path = []) => {
787
+ if (Object.keys(item).length === 0) {
788
+ return [];
1060
789
  }
1061
790
 
1062
- return normalizedPivotConfig.x.map(function (key) {
1063
- if (key === 'measures') {
1064
- return {
1065
- key: 'measures',
1066
- dataIndex: 'measures',
1067
- title: 'Measures',
1068
- shortTitle: 'Measures',
1069
- type: 'string'
791
+ return Object.values(item).map(({
792
+ key,
793
+ ...currentItem
794
+ }) => {
795
+ const children = toColumns(currentItem.children, [...path, key]);
796
+ const {
797
+ title,
798
+ shortTitle,
799
+ ...fields
800
+ } = extractFields(currentItem.memberId);
801
+ const dimensionValue = key !== currentItem.memberId || title == null ? key : '';
802
+
803
+ if (!children.length) {
804
+ return { ...fields,
805
+ key,
806
+ dataIndex: [...path, key].join(),
807
+ title: [title, dimensionValue].join(' ').trim(),
808
+ shortTitle: dimensionValue || shortTitle
1070
809
  };
1071
810
  }
1072
811
 
1073
- return _objectSpread$2(_objectSpread$2({}, extractFields(key)), {}, {
1074
- dataIndex: key
1075
- });
1076
- }).concat(toColumns(schema)).concat(otherColumns);
1077
- }
1078
- }, {
1079
- key: "totalRow",
1080
- value: function totalRow(pivotConfig) {
1081
- return this.chartPivot(pivotConfig)[0];
1082
- }
1083
- }, {
1084
- key: "categories",
1085
- value: function categories(pivotConfig) {
1086
- // TODO
1087
- return this.chartPivot(pivotConfig);
1088
- }
1089
- }, {
1090
- key: "seriesNames",
1091
- value: function seriesNames(pivotConfig) {
1092
- var _this4 = this;
1093
-
1094
- pivotConfig = this.normalizePivotConfig(pivotConfig);
1095
- var measures = pipe(pluck('annotation'), pluck('measures'), mergeAll)(this.loadResponses);
1096
- var seriesNames = unnest(this.loadResponses.map(function (_, index) {
1097
- return pipe(map(_this4.axisValues(pivotConfig.y, index)), unnest, uniq)(_this4.timeDimensionBackwardCompatibleData(index));
812
+ return { ...fields,
813
+ key,
814
+ title: [title, dimensionValue].join(' ').trim(),
815
+ shortTitle: dimensionValue || shortTitle,
816
+ children
817
+ };
818
+ });
819
+ };
820
+
821
+ let otherColumns = [];
822
+
823
+ if (!pivot.length && normalizedPivotConfig.y.includes('measures')) {
824
+ otherColumns = (this.loadResponses[0].query.measures || []).map(key => ({ ...extractFields(key),
825
+ dataIndex: key
1098
826
  }));
1099
- var duplicateMeasures = new Set();
1100
-
1101
- if (this.queryType === QUERY_TYPE.BLENDING_QUERY) {
1102
- var allMeasures = flatten(this.loadResponses.map(function (_ref30) {
1103
- var query = _ref30.query;
1104
- return query.measures;
1105
- }));
1106
- allMeasures.filter(function (e, i, a) {
1107
- return a.indexOf(e) !== i;
1108
- }).forEach(function (m) {
1109
- return duplicateMeasures.add(m);
1110
- });
1111
- }
827
+ } // Syntatic column to display the measure value
1112
828
 
1113
- return seriesNames.map(function (axisValues, i) {
1114
- var aliasedAxis = aliasSeries(axisValues, i, pivotConfig, duplicateMeasures);
1115
- return {
1116
- title: _this4.axisValuesString(pivotConfig.y.find(function (d) {
1117
- return d === 'measures';
1118
- }) ? dropLast(1, aliasedAxis).concat(measures[ResultSet.measureFromAxis(axisValues)].title) : aliasedAxis, ', '),
1119
- key: _this4.axisValuesString(aliasedAxis, ','),
1120
- yValues: axisValues
1121
- };
829
+
830
+ if (!normalizedPivotConfig.y.length && normalizedPivotConfig.x.includes('measures')) {
831
+ otherColumns.push({
832
+ key: 'value',
833
+ dataIndex: 'value',
834
+ title: 'Value',
835
+ shortTitle: 'Value',
836
+ type: 'string'
1122
837
  });
1123
838
  }
1124
- }, {
1125
- key: "query",
1126
- value: function query() {
1127
- if (this.queryType !== QUERY_TYPE.REGULAR_QUERY) {
1128
- throw new Error("Method is not supported for a '".concat(this.queryType, "' query type. Please use decompose"));
1129
- }
1130
839
 
1131
- return this.loadResponses[0].query;
1132
- }
1133
- }, {
1134
- key: "pivotQuery",
1135
- value: function pivotQuery() {
1136
- return this.loadResponse.pivotQuery || null;
1137
- }
1138
- }, {
1139
- key: "rawData",
1140
- value: function rawData() {
1141
- if (this.queryType !== QUERY_TYPE.REGULAR_QUERY) {
1142
- throw new Error("Method is not supported for a '".concat(this.queryType, "' query type. Please use decompose"));
840
+ return normalizedPivotConfig.x.map(key => {
841
+ if (key === 'measures') {
842
+ return {
843
+ key: 'measures',
844
+ dataIndex: 'measures',
845
+ title: 'Measures',
846
+ shortTitle: 'Measures',
847
+ type: 'string'
848
+ };
1143
849
  }
1144
850
 
1145
- return this.loadResponses[0].data;
1146
- }
1147
- }, {
1148
- key: "annotation",
1149
- value: function annotation() {
1150
- if (this.queryType !== QUERY_TYPE.REGULAR_QUERY) {
1151
- throw new Error("Method is not supported for a '".concat(this.queryType, "' query type. Please use decompose"));
1152
- }
851
+ return { ...extractFields(key),
852
+ dataIndex: key
853
+ };
854
+ }).concat(toColumns(schema)).concat(otherColumns);
855
+ }
1153
856
 
1154
- return this.loadResponses[0].annotation;
1155
- }
1156
- }, {
1157
- key: "timeDimensionBackwardCompatibleData",
1158
- value: function timeDimensionBackwardCompatibleData(resultIndex) {
1159
- if (resultIndex === undefined) {
1160
- throw new Error('resultIndex is required');
1161
- }
857
+ totalRow(pivotConfig) {
858
+ return this.chartPivot(pivotConfig)[0];
859
+ }
1162
860
 
1163
- if (!this.backwardCompatibleData[resultIndex]) {
1164
- var _this$loadResponses$r = this.loadResponses[resultIndex],
1165
- data = _this$loadResponses$r.data,
1166
- query = _this$loadResponses$r.query;
1167
- var timeDimensions = (query.timeDimensions || []).filter(function (td) {
1168
- return Boolean(td.granularity);
1169
- });
1170
- this.backwardCompatibleData[resultIndex] = data.map(function (row) {
1171
- return _objectSpread$2(_objectSpread$2({}, row), fromPairs(Object.keys(row).filter(function (field) {
1172
- return timeDimensions.find(function (d) {
1173
- return d.dimension === field;
1174
- }) && !row[ResultSet.timeDimensionMember(timeDimensions.find(function (d) {
1175
- return d.dimension === field;
1176
- }))];
1177
- }).map(function (field) {
1178
- return [ResultSet.timeDimensionMember(timeDimensions.find(function (d) {
1179
- return d.dimension === field;
1180
- })), row[field]];
1181
- })));
1182
- });
1183
- }
861
+ categories(pivotConfig) {
862
+ // TODO
863
+ return this.chartPivot(pivotConfig);
864
+ }
1184
865
 
1185
- return this.backwardCompatibleData[resultIndex];
1186
- }
1187
- }, {
1188
- key: "decompose",
1189
- value: function decompose() {
1190
- var _this5 = this;
1191
-
1192
- return this.loadResponses.map(function (result) {
1193
- return new ResultSet({
1194
- queryType: QUERY_TYPE.REGULAR_QUERY,
1195
- pivotQuery: _objectSpread$2(_objectSpread$2({}, result.query), {}, {
1196
- queryType: QUERY_TYPE.REGULAR_QUERY
1197
- }),
1198
- results: [result]
1199
- }, _this5.options);
1200
- });
866
+ seriesNames(pivotConfig) {
867
+ pivotConfig = this.normalizePivotConfig(pivotConfig);
868
+ const measures = pipe(pluck('annotation'), pluck('measures'), mergeAll)(this.loadResponses);
869
+ const seriesNames = unnest(this.loadResponses.map((_, index) => pipe(map(this.axisValues(pivotConfig.y, index)), unnest, uniq)(this.timeDimensionBackwardCompatibleData(index))));
870
+ const duplicateMeasures = new Set();
871
+
872
+ if (this.queryType === QUERY_TYPE.BLENDING_QUERY) {
873
+ const allMeasures = flatten(this.loadResponses.map(({
874
+ query
875
+ }) => query.measures));
876
+ allMeasures.filter((e, i, a) => a.indexOf(e) !== i).forEach(m => duplicateMeasures.add(m));
1201
877
  }
1202
- }, {
1203
- key: "serialize",
1204
- value: function serialize() {
878
+
879
+ return seriesNames.map((axisValues, i) => {
880
+ const aliasedAxis = aliasSeries(axisValues, i, pivotConfig, duplicateMeasures);
1205
881
  return {
1206
- loadResponse: clone(this.loadResponse)
882
+ title: this.axisValuesString(pivotConfig.y.find(d => d === 'measures') ? dropLast(1, aliasedAxis).concat(measures[ResultSet.measureFromAxis(axisValues)].title) : aliasedAxis, ', '),
883
+ key: this.axisValuesString(aliasedAxis, ','),
884
+ yValues: axisValues
1207
885
  };
886
+ });
887
+ }
888
+
889
+ query() {
890
+ if (this.queryType !== QUERY_TYPE.REGULAR_QUERY) {
891
+ throw new Error(`Method is not supported for a '${this.queryType}' query type. Please use decompose`);
1208
892
  }
1209
- }], [{
1210
- key: "measureFromAxis",
1211
- value: function measureFromAxis(axisValues) {
1212
- return axisValues[axisValues.length - 1];
1213
- }
1214
- }, {
1215
- key: "timeDimensionMember",
1216
- value: function timeDimensionMember(td) {
1217
- return "".concat(td.dimension, ".").concat(td.granularity);
1218
- }
1219
- }, {
1220
- key: "deserialize",
1221
- value: function deserialize(data) {
1222
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1223
- return new ResultSet(data.loadResponse, options);
1224
- }
1225
- }, {
1226
- key: "getNormalizedPivotConfig",
1227
- value: function getNormalizedPivotConfig() {
1228
- var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1229
- var pivotConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
1230
- var defaultPivotConfig = {
1231
- x: [],
1232
- y: [],
1233
- fillMissingDates: true,
1234
- joinDateRange: false
1235
- };
1236
- var _query$measures = query.measures,
1237
- measures = _query$measures === void 0 ? [] : _query$measures,
1238
- _query$dimensions = query.dimensions,
1239
- dimensions = _query$dimensions === void 0 ? [] : _query$dimensions;
1240
- var timeDimensions = (query.timeDimensions || []).filter(function (td) {
1241
- return !!td.granularity;
1242
- });
1243
- pivotConfig = pivotConfig || (timeDimensions.length ? {
1244
- x: timeDimensions.map(function (td) {
1245
- return ResultSet.timeDimensionMember(td);
1246
- }),
1247
- y: dimensions
1248
- } : {
1249
- x: dimensions,
1250
- y: []
1251
- });
1252
- pivotConfig = mergeDeepLeft(pivotConfig, defaultPivotConfig);
1253
-
1254
- var substituteTimeDimensionMembers = function substituteTimeDimensionMembers(axis) {
1255
- return axis.map(function (subDim) {
1256
- return timeDimensions.find(function (td) {
1257
- return td.dimension === subDim;
1258
- }) && !dimensions.find(function (d) {
1259
- return d === subDim;
1260
- }) ? ResultSet.timeDimensionMember(query.timeDimensions.find(function (td) {
1261
- return td.dimension === subDim;
1262
- })) : subDim;
1263
- });
1264
- };
1265
893
 
1266
- pivotConfig.x = substituteTimeDimensionMembers(pivotConfig.x);
1267
- pivotConfig.y = substituteTimeDimensionMembers(pivotConfig.y);
1268
- var allIncludedDimensions = pivotConfig.x.concat(pivotConfig.y);
1269
- var allDimensions = timeDimensions.map(function (td) {
1270
- return ResultSet.timeDimensionMember(td);
1271
- }).concat(dimensions);
894
+ return this.loadResponses[0].query;
895
+ }
1272
896
 
1273
- var dimensionFilter = function dimensionFilter(key) {
1274
- return allDimensions.includes(key) || key === 'measures';
1275
- };
897
+ pivotQuery() {
898
+ return this.loadResponse.pivotQuery || null;
899
+ }
1276
900
 
1277
- pivotConfig.x = pivotConfig.x.concat(allDimensions.filter(function (d) {
1278
- return !allIncludedDimensions.includes(d) && d !== 'compareDateRange';
1279
- })).filter(dimensionFilter);
1280
- pivotConfig.y = pivotConfig.y.filter(dimensionFilter);
901
+ rawData() {
902
+ if (this.queryType !== QUERY_TYPE.REGULAR_QUERY) {
903
+ throw new Error(`Method is not supported for a '${this.queryType}' query type. Please use decompose`);
904
+ }
1281
905
 
1282
- if (!pivotConfig.x.concat(pivotConfig.y).find(function (d) {
1283
- return d === 'measures';
1284
- })) {
1285
- pivotConfig.y.push('measures');
1286
- }
906
+ return this.loadResponses[0].data;
907
+ }
1287
908
 
1288
- if (dimensions.includes('compareDateRange') && !pivotConfig.y.concat(pivotConfig.x).includes('compareDateRange')) {
1289
- pivotConfig.y.unshift('compareDateRange');
1290
- }
909
+ annotation() {
910
+ if (this.queryType !== QUERY_TYPE.REGULAR_QUERY) {
911
+ throw new Error(`Method is not supported for a '${this.queryType}' query type. Please use decompose`);
912
+ }
1291
913
 
1292
- if (!measures.length) {
1293
- pivotConfig.x = pivotConfig.x.filter(function (d) {
1294
- return d !== 'measures';
1295
- });
1296
- pivotConfig.y = pivotConfig.y.filter(function (d) {
1297
- return d !== 'measures';
1298
- });
1299
- }
914
+ return this.loadResponses[0].annotation;
915
+ }
916
+
917
+ timeDimensionBackwardCompatibleData(resultIndex) {
918
+ if (resultIndex === undefined) {
919
+ throw new Error('resultIndex is required');
920
+ }
1300
921
 
1301
- return pivotConfig;
922
+ if (!this.backwardCompatibleData[resultIndex]) {
923
+ const {
924
+ data,
925
+ query
926
+ } = this.loadResponses[resultIndex];
927
+ const timeDimensions = (query.timeDimensions || []).filter(td => Boolean(td.granularity));
928
+ this.backwardCompatibleData[resultIndex] = data.map(row => ({ ...row,
929
+ ...fromPairs(Object.keys(row).filter(field => timeDimensions.find(d => d.dimension === field) && !row[ResultSet.timeDimensionMember(timeDimensions.find(d => d.dimension === field))]).map(field => [ResultSet.timeDimensionMember(timeDimensions.find(d => d.dimension === field)), row[field]]))
930
+ }));
1302
931
  }
1303
- }]);
1304
932
 
1305
- return ResultSet;
1306
- }();
933
+ return this.backwardCompatibleData[resultIndex];
934
+ }
935
+
936
+ decompose() {
937
+ return this.loadResponses.map(result => new ResultSet({
938
+ queryType: QUERY_TYPE.REGULAR_QUERY,
939
+ pivotQuery: { ...result.query,
940
+ queryType: QUERY_TYPE.REGULAR_QUERY
941
+ },
942
+ results: [result]
943
+ }, this.options));
944
+ }
945
+
946
+ serialize() {
947
+ return {
948
+ loadResponse: clone(this.loadResponse)
949
+ };
950
+ }
1307
951
 
1308
- var SqlQuery = /*#__PURE__*/function () {
1309
- function SqlQuery(sqlQuery) {
1310
- _classCallCheck(this, SqlQuery);
952
+ }
1311
953
 
954
+ class SqlQuery {
955
+ constructor(sqlQuery) {
1312
956
  this.sqlQuery = sqlQuery;
1313
957
  }
1314
958
 
1315
- _createClass(SqlQuery, [{
1316
- key: "rawQuery",
1317
- value: function rawQuery() {
1318
- return this.sqlQuery.sql;
1319
- }
1320
- }, {
1321
- key: "sql",
1322
- value: function sql() {
1323
- return this.rawQuery().sql[0];
1324
- }
1325
- }]);
959
+ rawQuery() {
960
+ return this.sqlQuery.sql;
961
+ }
1326
962
 
1327
- return SqlQuery;
1328
- }();
963
+ sql() {
964
+ return this.rawQuery().sql[0];
965
+ }
1329
966
 
1330
- var memberMap = function memberMap(memberArray) {
1331
- return fromPairs(memberArray.map(function (m) {
1332
- return [m.name, m];
1333
- }));
1334
- };
967
+ }
1335
968
 
1336
- var operators = {
969
+ /**
970
+ * @module @cubejs-client/core
971
+ */
972
+
973
+ const memberMap = memberArray => fromPairs(memberArray.map(m => [m.name, m]));
974
+
975
+ const operators = {
1337
976
  string: [{
1338
977
  name: 'contains',
1339
978
  title: 'contains'
@@ -1402,158 +1041,112 @@ var operators = {
1402
1041
  * Contains information about available cubes and it's members.
1403
1042
  */
1404
1043
 
1405
- var Meta = /*#__PURE__*/function () {
1406
- function Meta(metaResponse) {
1407
- _classCallCheck(this, Meta);
1408
-
1044
+ class Meta {
1045
+ constructor(metaResponse) {
1409
1046
  this.meta = metaResponse;
1410
- var cubes = this.meta.cubes;
1047
+ const {
1048
+ cubes
1049
+ } = this.meta;
1411
1050
  this.cubes = cubes;
1412
- this.cubesMap = fromPairs(cubes.map(function (c) {
1413
- return [c.name, {
1414
- measures: memberMap(c.measures),
1415
- dimensions: memberMap(c.dimensions),
1416
- segments: memberMap(c.segments)
1417
- }];
1418
- }));
1051
+ this.cubesMap = fromPairs(cubes.map(c => [c.name, {
1052
+ measures: memberMap(c.measures),
1053
+ dimensions: memberMap(c.dimensions),
1054
+ segments: memberMap(c.segments)
1055
+ }]));
1419
1056
  }
1420
1057
 
1421
- _createClass(Meta, [{
1422
- key: "membersForQuery",
1423
- value: function membersForQuery(query, memberType) {
1424
- return unnest$1(this.cubes.map(function (c) {
1425
- return c[memberType];
1426
- })).sort(function (a, b) {
1427
- return a.title > b.title ? 1 : -1;
1428
- });
1429
- }
1430
- }, {
1431
- key: "membersGroupedByCube",
1432
- value: function membersGroupedByCube() {
1433
- var memberKeys = ['measures', 'dimensions', 'segments', 'timeDimensions'];
1434
- return this.cubes.reduce(function (memo, cube) {
1435
- memberKeys.forEach(function (key) {
1436
- var members = cube[key];
1437
-
1438
- if (key === 'timeDimensions') {
1439
- members = cube.dimensions.filter(function (m) {
1440
- return m.type === 'time';
1441
- });
1442
- }
1443
-
1444
- memo[key] = [].concat(_toConsumableArray(memo[key]), [{
1445
- cubeName: cube.name,
1446
- cubeTitle: cube.title,
1447
- members: members
1448
- }]);
1449
- });
1450
- return memo;
1451
- }, {
1452
- measures: [],
1453
- dimensions: [],
1454
- segments: [],
1455
- timeDimensions: []
1456
- });
1457
- }
1458
- }, {
1459
- key: "resolveMember",
1460
- value: function resolveMember(memberName, memberType) {
1461
- var _this = this;
1058
+ membersForQuery(query, memberType) {
1059
+ return unnest$1(this.cubes.map(c => c[memberType])).sort((a, b) => a.title > b.title ? 1 : -1);
1060
+ }
1462
1061
 
1463
- var _memberName$split = memberName.split('.'),
1464
- _memberName$split2 = _slicedToArray(_memberName$split, 1),
1465
- cube = _memberName$split2[0];
1062
+ membersGroupedByCube() {
1063
+ const memberKeys = ['measures', 'dimensions', 'segments', 'timeDimensions'];
1064
+ return this.cubes.reduce((memo, cube) => {
1065
+ memberKeys.forEach(key => {
1066
+ let members = cube[key];
1466
1067
 
1467
- if (!this.cubesMap[cube]) {
1468
- return {
1469
- title: memberName,
1470
- error: "Cube not found ".concat(cube, " for path '").concat(memberName, "'")
1471
- };
1472
- }
1068
+ if (key === 'timeDimensions') {
1069
+ members = cube.dimensions.filter(m => m.type === 'time');
1070
+ }
1473
1071
 
1474
- var memberTypes = Array.isArray(memberType) ? memberType : [memberType];
1475
- var member = memberTypes.map(function (type) {
1476
- return _this.cubesMap[cube][type] && _this.cubesMap[cube][type][memberName];
1477
- }).find(function (m) {
1478
- return m;
1072
+ memo[key] = [...memo[key], {
1073
+ cubeName: cube.name,
1074
+ cubeTitle: cube.title,
1075
+ members
1076
+ }];
1479
1077
  });
1078
+ return memo;
1079
+ }, {
1080
+ measures: [],
1081
+ dimensions: [],
1082
+ segments: [],
1083
+ timeDimensions: []
1084
+ });
1085
+ }
1480
1086
 
1481
- if (!member) {
1482
- return {
1483
- title: memberName,
1484
- error: "Path not found '".concat(memberName, "'")
1485
- };
1486
- }
1087
+ resolveMember(memberName, memberType) {
1088
+ const [cube] = memberName.split('.');
1487
1089
 
1488
- return member;
1090
+ if (!this.cubesMap[cube]) {
1091
+ return {
1092
+ title: memberName,
1093
+ error: `Cube not found ${cube} for path '${memberName}'`
1094
+ };
1489
1095
  }
1490
- }, {
1491
- key: "defaultTimeDimensionNameFor",
1492
- value: function defaultTimeDimensionNameFor(memberName) {
1493
- var _this2 = this;
1494
1096
 
1495
- var _memberName$split3 = memberName.split('.'),
1496
- _memberName$split4 = _slicedToArray(_memberName$split3, 1),
1497
- cube = _memberName$split4[0];
1498
-
1499
- if (!this.cubesMap[cube]) {
1500
- return null;
1501
- }
1097
+ const memberTypes = Array.isArray(memberType) ? memberType : [memberType];
1098
+ const member = memberTypes.map(type => this.cubesMap[cube][type] && this.cubesMap[cube][type][memberName]).find(m => m);
1502
1099
 
1503
- return Object.keys(this.cubesMap[cube].dimensions || {}).find(function (d) {
1504
- return _this2.cubesMap[cube].dimensions[d].type === 'time';
1505
- });
1506
- }
1507
- }, {
1508
- key: "filterOperatorsForMember",
1509
- value: function filterOperatorsForMember(memberName, memberType) {
1510
- var member = this.resolveMember(memberName, memberType);
1511
- return operators[member.type] || operators.string;
1100
+ if (!member) {
1101
+ return {
1102
+ title: memberName,
1103
+ error: `Path not found '${memberName}'`
1104
+ };
1512
1105
  }
1513
- }]);
1514
-
1515
- return Meta;
1516
- }();
1517
-
1518
- var ProgressResult = /*#__PURE__*/function () {
1519
- function ProgressResult(progressResponse) {
1520
- _classCallCheck(this, ProgressResult);
1521
1106
 
1522
- this.progressResponse = progressResponse;
1107
+ return member;
1523
1108
  }
1524
1109
 
1525
- _createClass(ProgressResult, [{
1526
- key: "stage",
1527
- value: function stage() {
1528
- return this.progressResponse.stage;
1529
- }
1530
- }, {
1531
- key: "timeElapsed",
1532
- value: function timeElapsed() {
1533
- return this.progressResponse.timeElapsed;
1110
+ defaultTimeDimensionNameFor(memberName) {
1111
+ const [cube] = memberName.split('.');
1112
+
1113
+ if (!this.cubesMap[cube]) {
1114
+ return null;
1534
1115
  }
1535
- }]);
1536
1116
 
1537
- return ProgressResult;
1538
- }();
1117
+ return Object.keys(this.cubesMap[cube].dimensions || {}).find(d => this.cubesMap[cube].dimensions[d].type === 'time');
1118
+ }
1539
1119
 
1540
- var _excluded = ["baseRequestId"];
1120
+ filterOperatorsForMember(memberName, memberType) {
1121
+ const member = this.resolveMember(memberName, memberType);
1122
+ return operators[member.type] || operators.string;
1123
+ }
1541
1124
 
1542
- function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
1125
+ }
1543
1126
 
1544
- function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1127
+ class ProgressResult {
1128
+ constructor(progressResponse) {
1129
+ this.progressResponse = progressResponse;
1130
+ }
1545
1131
 
1546
- var HttpTransport = /*#__PURE__*/function () {
1547
- function HttpTransport(_ref) {
1548
- var authorization = _ref.authorization,
1549
- apiUrl = _ref.apiUrl,
1550
- method = _ref.method,
1551
- _ref$headers = _ref.headers,
1552
- headers = _ref$headers === void 0 ? {} : _ref$headers,
1553
- credentials = _ref.credentials;
1132
+ stage() {
1133
+ return this.progressResponse.stage;
1134
+ }
1554
1135
 
1555
- _classCallCheck(this, HttpTransport);
1136
+ timeElapsed() {
1137
+ return this.progressResponse.timeElapsed;
1138
+ }
1556
1139
 
1140
+ }
1141
+
1142
+ class HttpTransport {
1143
+ constructor({
1144
+ authorization,
1145
+ apiUrl,
1146
+ method,
1147
+ headers = {},
1148
+ credentials
1149
+ }) {
1557
1150
  this.authorization = authorization;
1558
1151
  this.apiUrl = apiUrl;
1559
1152
  this.method = method;
@@ -1561,167 +1154,92 @@ var HttpTransport = /*#__PURE__*/function () {
1561
1154
  this.credentials = credentials;
1562
1155
  }
1563
1156
 
1564
- _createClass(HttpTransport, [{
1565
- key: "request",
1566
- value: function request(method, _ref2) {
1567
- var _this = this;
1568
-
1569
- var baseRequestId = _ref2.baseRequestId,
1570
- params = _objectWithoutProperties(_ref2, _excluded);
1571
-
1572
- var spanCounter = 1;
1573
- var searchParams = new URLSearchParams(params && Object.keys(params).map(function (k) {
1574
- return _defineProperty({}, k, _typeof(params[k]) === 'object' ? JSON.stringify(params[k]) : params[k]);
1575
- }).reduce(function (a, b) {
1576
- return _objectSpread$1(_objectSpread$1({}, a), b);
1577
- }, {}));
1578
- var url = "".concat(this.apiUrl, "/").concat(method).concat(searchParams.toString().length ? "?".concat(searchParams) : '');
1579
- var requestMethod = this.method || (url.length < 2000 ? 'GET' : 'POST');
1580
-
1581
- if (requestMethod === 'POST') {
1582
- url = "".concat(this.apiUrl, "/").concat(method);
1583
- this.headers['Content-Type'] = 'application/json';
1584
- } // Currently, all methods make GET requests. If a method makes a request with a body payload,
1585
- // remember to add {'Content-Type': 'application/json'} to the header.
1586
-
1587
-
1588
- var runRequest = function runRequest() {
1589
- return fetch(url, {
1590
- method: requestMethod,
1591
- headers: _objectSpread$1({
1592
- Authorization: _this.authorization,
1593
- 'x-request-id': baseRequestId && "".concat(baseRequestId, "-span-").concat(spanCounter++)
1594
- }, _this.headers),
1595
- credentials: _this.credentials,
1596
- body: requestMethod === 'POST' ? JSON.stringify(params) : null
1597
- });
1598
- };
1599
-
1600
- return {
1601
- /* eslint no-unsafe-finally: off */
1602
- subscribe: function subscribe(callback) {
1603
- var _this2 = this;
1604
-
1605
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
1606
- var result;
1607
- return _regeneratorRuntime.wrap(function _callee$(_context) {
1608
- while (1) {
1609
- switch (_context.prev = _context.next) {
1610
- case 0:
1611
- result = {
1612
- error: 'network Error' // add default error message
1613
-
1614
- };
1615
- _context.prev = 1;
1616
- _context.next = 4;
1617
- return runRequest();
1618
-
1619
- case 4:
1620
- result = _context.sent;
1621
-
1622
- case 5:
1623
- _context.prev = 5;
1624
- return _context.abrupt("return", callback(result, function () {
1625
- return _this2.subscribe(callback);
1626
- }));
1627
-
1628
- case 8:
1629
- case "end":
1630
- return _context.stop();
1631
- }
1632
- }
1633
- }, _callee, null, [[1,, 5, 8]]);
1634
- }))();
1635
- }
1636
- };
1637
- }
1638
- }]);
1639
-
1640
- return HttpTransport;
1641
- }();
1642
-
1643
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
1157
+ request(method, {
1158
+ baseRequestId,
1159
+ ...params
1160
+ }) {
1161
+ let spanCounter = 1;
1162
+ const searchParams = new URLSearchParams(params && Object.keys(params).map(k => ({
1163
+ [k]: typeof params[k] === 'object' ? JSON.stringify(params[k]) : params[k]
1164
+ })).reduce((a, b) => ({ ...a,
1165
+ ...b
1166
+ }), {}));
1167
+ let url = `${this.apiUrl}/${method}${searchParams.toString().length ? `?${searchParams}` : ''}`;
1168
+ const requestMethod = this.method || (url.length < 2000 ? 'GET' : 'POST');
1169
+
1170
+ if (requestMethod === 'POST') {
1171
+ url = `${this.apiUrl}/${method}`;
1172
+ this.headers['Content-Type'] = 'application/json';
1173
+ } // Currently, all methods make GET requests. If a method makes a request with a body payload,
1174
+ // remember to add {'Content-Type': 'application/json'} to the header.
1175
+
1176
+
1177
+ const runRequest = () => fetch(url, {
1178
+ method: requestMethod,
1179
+ headers: {
1180
+ Authorization: this.authorization,
1181
+ 'x-request-id': baseRequestId && `${baseRequestId}-span-${spanCounter++}`,
1182
+ ...this.headers
1183
+ },
1184
+ credentials: this.credentials,
1185
+ body: requestMethod === 'POST' ? JSON.stringify(params) : null
1186
+ });
1644
1187
 
1645
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1188
+ return {
1189
+ /* eslint no-unsafe-finally: off */
1190
+ async subscribe(callback) {
1191
+ let result = {
1192
+ error: 'network Error' // add default error message
1646
1193
 
1647
- var RequestError = /*#__PURE__*/function (_Error) {
1648
- _inherits(RequestError, _Error);
1194
+ };
1649
1195
 
1650
- var _super = _createSuper(RequestError);
1196
+ try {
1197
+ result = await runRequest();
1198
+ } finally {
1199
+ return callback(result, () => this.subscribe(callback));
1200
+ }
1201
+ }
1651
1202
 
1652
- function RequestError(message, response, status) {
1653
- var _this;
1203
+ };
1204
+ }
1654
1205
 
1655
- _classCallCheck(this, RequestError);
1206
+ }
1656
1207
 
1657
- _this = _super.call(this, message);
1658
- _this.response = response;
1659
- _this.status = status;
1660
- return _this;
1208
+ class RequestError extends Error {
1209
+ constructor(message, response, status) {
1210
+ super(message);
1211
+ this.response = response;
1212
+ this.status = status;
1661
1213
  }
1662
1214
 
1663
- return _createClass(RequestError);
1664
- }( /*#__PURE__*/_wrapNativeSuper(Error));
1665
-
1666
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
1215
+ }
1667
1216
 
1668
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1669
- var mutexCounter = 0;
1670
- var MUTEX_ERROR = 'Mutex has been changed';
1217
+ let mutexCounter = 0;
1218
+ const MUTEX_ERROR = 'Mutex has been changed';
1671
1219
  /**
1672
1220
  * Query result dataset formats enum.
1673
1221
  */
1674
1222
 
1675
- var ResultType = {
1223
+ const ResultType = {
1676
1224
  DEFAULT: 'default',
1677
1225
  COMPACT: 'compact'
1678
1226
  };
1679
1227
 
1680
1228
  function mutexPromise(promise) {
1681
- return new Promise( /*#__PURE__*/function () {
1682
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve, reject) {
1683
- return _regeneratorRuntime.wrap(function _callee$(_context) {
1684
- while (1) {
1685
- switch (_context.prev = _context.next) {
1686
- case 0:
1687
- _context.prev = 0;
1688
- _context.t0 = resolve;
1689
- _context.next = 4;
1690
- return promise;
1691
-
1692
- case 4:
1693
- _context.t1 = _context.sent;
1694
- (0, _context.t0)(_context.t1);
1695
- _context.next = 11;
1696
- break;
1697
-
1698
- case 8:
1699
- _context.prev = 8;
1700
- _context.t2 = _context["catch"](0);
1701
-
1702
- if (_context.t2 !== MUTEX_ERROR) {
1703
- reject(_context.t2);
1704
- }
1705
-
1706
- case 11:
1707
- case "end":
1708
- return _context.stop();
1709
- }
1710
- }
1711
- }, _callee, null, [[0, 8]]);
1712
- }));
1713
-
1714
- return function (_x, _x2) {
1715
- return _ref.apply(this, arguments);
1716
- };
1717
- }());
1229
+ return new Promise(async (resolve, reject) => {
1230
+ try {
1231
+ resolve(await promise);
1232
+ } catch (error) {
1233
+ if (error !== MUTEX_ERROR) {
1234
+ reject(error);
1235
+ }
1236
+ }
1237
+ });
1718
1238
  }
1719
1239
 
1720
- var CubejsApi = /*#__PURE__*/function () {
1721
- function CubejsApi(apiToken, options) {
1722
- _classCallCheck(this, CubejsApi);
1723
-
1724
- if (apiToken !== null && !Array.isArray(apiToken) && _typeof(apiToken) === 'object') {
1240
+ class CubejsApi {
1241
+ constructor(apiToken, options) {
1242
+ if (apiToken !== null && !Array.isArray(apiToken) && typeof apiToken === 'object') {
1725
1243
  options = apiToken;
1726
1244
  apiToken = undefined;
1727
1245
  }
@@ -1749,621 +1267,283 @@ var CubejsApi = /*#__PURE__*/function () {
1749
1267
  this.updateAuthorizationPromise = null;
1750
1268
  }
1751
1269
 
1752
- _createClass(CubejsApi, [{
1753
- key: "request",
1754
- value: function request(method, params) {
1755
- return this.transport.request(method, _objectSpread({
1756
- baseRequestId: v4()
1757
- }, params));
1270
+ request(method, params) {
1271
+ return this.transport.request(method, {
1272
+ baseRequestId: v4(),
1273
+ ...params
1274
+ });
1275
+ }
1276
+
1277
+ loadMethod(request, toResult, options, callback) {
1278
+ const mutexValue = ++mutexCounter;
1279
+
1280
+ if (typeof options === 'function' && !callback) {
1281
+ callback = options;
1282
+ options = undefined;
1758
1283
  }
1759
- }, {
1760
- key: "loadMethod",
1761
- value: function loadMethod(request, toResult, options, callback) {
1762
- var _this = this;
1763
1284
 
1764
- var mutexValue = ++mutexCounter;
1285
+ options = options || {};
1286
+ const mutexKey = options.mutexKey || 'default';
1765
1287
 
1766
- if (typeof options === 'function' && !callback) {
1767
- callback = options;
1768
- options = undefined;
1769
- }
1288
+ if (options.mutexObj) {
1289
+ options.mutexObj[mutexKey] = mutexValue;
1290
+ }
1291
+
1292
+ const requestPromise = this.updateTransportAuthorization().then(() => request());
1293
+ let skipAuthorizationUpdate = true;
1294
+ let unsubscribed = false;
1295
+
1296
+ const checkMutex = async () => {
1297
+ const requestInstance = await requestPromise;
1298
+
1299
+ if (options.mutexObj && options.mutexObj[mutexKey] !== mutexValue) {
1300
+ unsubscribed = true;
1770
1301
 
1771
- options = options || {};
1772
- var mutexKey = options.mutexKey || 'default';
1302
+ if (requestInstance.unsubscribe) {
1303
+ await requestInstance.unsubscribe();
1304
+ }
1773
1305
 
1774
- if (options.mutexObj) {
1775
- options.mutexObj[mutexKey] = mutexValue;
1306
+ throw MUTEX_ERROR;
1776
1307
  }
1308
+ };
1777
1309
 
1778
- var requestPromise = this.updateTransportAuthorization().then(function () {
1779
- return request();
1780
- });
1781
- var skipAuthorizationUpdate = true;
1782
- var unsubscribed = false;
1783
-
1784
- var checkMutex = /*#__PURE__*/function () {
1785
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
1786
- var requestInstance;
1787
- return _regeneratorRuntime.wrap(function _callee2$(_context2) {
1788
- while (1) {
1789
- switch (_context2.prev = _context2.next) {
1790
- case 0:
1791
- _context2.next = 2;
1792
- return requestPromise;
1793
-
1794
- case 2:
1795
- requestInstance = _context2.sent;
1796
-
1797
- if (!(options.mutexObj && options.mutexObj[mutexKey] !== mutexValue)) {
1798
- _context2.next = 9;
1799
- break;
1800
- }
1801
-
1802
- unsubscribed = true;
1803
-
1804
- if (!requestInstance.unsubscribe) {
1805
- _context2.next = 8;
1806
- break;
1807
- }
1808
-
1809
- _context2.next = 8;
1810
- return requestInstance.unsubscribe();
1811
-
1812
- case 8:
1813
- throw MUTEX_ERROR;
1814
-
1815
- case 9:
1816
- case "end":
1817
- return _context2.stop();
1818
- }
1819
- }
1820
- }, _callee2);
1821
- }));
1310
+ const loadImpl = async (response, next) => {
1311
+ const requestInstance = await requestPromise;
1822
1312
 
1823
- return function checkMutex() {
1824
- return _ref2.apply(this, arguments);
1825
- };
1826
- }();
1827
-
1828
- var loadImpl = /*#__PURE__*/function () {
1829
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(response, next) {
1830
- var requestInstance, subscribeNext, continueWait, body, text, error, result;
1831
- return _regeneratorRuntime.wrap(function _callee5$(_context5) {
1832
- while (1) {
1833
- switch (_context5.prev = _context5.next) {
1834
- case 0:
1835
- _context5.next = 2;
1836
- return requestPromise;
1837
-
1838
- case 2:
1839
- requestInstance = _context5.sent;
1840
-
1841
- subscribeNext = /*#__PURE__*/function () {
1842
- var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
1843
- return _regeneratorRuntime.wrap(function _callee3$(_context3) {
1844
- while (1) {
1845
- switch (_context3.prev = _context3.next) {
1846
- case 0:
1847
- if (!(options.subscribe && !unsubscribed)) {
1848
- _context3.next = 8;
1849
- break;
1850
- }
1851
-
1852
- if (!requestInstance.unsubscribe) {
1853
- _context3.next = 5;
1854
- break;
1855
- }
1856
-
1857
- return _context3.abrupt("return", next());
1858
-
1859
- case 5:
1860
- _context3.next = 7;
1861
- return new Promise(function (resolve) {
1862
- return setTimeout(function () {
1863
- return resolve();
1864
- }, _this.pollInterval * 1000);
1865
- });
1866
-
1867
- case 7:
1868
- return _context3.abrupt("return", next());
1869
-
1870
- case 8:
1871
- return _context3.abrupt("return", null);
1872
-
1873
- case 9:
1874
- case "end":
1875
- return _context3.stop();
1876
- }
1877
- }
1878
- }, _callee3);
1879
- }));
1880
-
1881
- return function subscribeNext() {
1882
- return _ref4.apply(this, arguments);
1883
- };
1884
- }();
1885
-
1886
- continueWait = /*#__PURE__*/function () {
1887
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(wait) {
1888
- return _regeneratorRuntime.wrap(function _callee4$(_context4) {
1889
- while (1) {
1890
- switch (_context4.prev = _context4.next) {
1891
- case 0:
1892
- if (unsubscribed) {
1893
- _context4.next = 5;
1894
- break;
1895
- }
1896
-
1897
- if (!wait) {
1898
- _context4.next = 4;
1899
- break;
1900
- }
1901
-
1902
- _context4.next = 4;
1903
- return new Promise(function (resolve) {
1904
- return setTimeout(function () {
1905
- return resolve();
1906
- }, _this.pollInterval * 1000);
1907
- });
1908
-
1909
- case 4:
1910
- return _context4.abrupt("return", next());
1911
-
1912
- case 5:
1913
- return _context4.abrupt("return", null);
1914
-
1915
- case 6:
1916
- case "end":
1917
- return _context4.stop();
1918
- }
1919
- }
1920
- }, _callee4);
1921
- }));
1922
-
1923
- return function continueWait(_x5) {
1924
- return _ref5.apply(this, arguments);
1925
- };
1926
- }();
1927
-
1928
- if (!(options.subscribe && !skipAuthorizationUpdate)) {
1929
- _context5.next = 8;
1930
- break;
1931
- }
1932
-
1933
- _context5.next = 8;
1934
- return _this.updateTransportAuthorization();
1935
-
1936
- case 8:
1937
- skipAuthorizationUpdate = false;
1938
-
1939
- if (!(response.status === 502)) {
1940
- _context5.next = 13;
1941
- break;
1942
- }
1943
-
1944
- _context5.next = 12;
1945
- return checkMutex();
1946
-
1947
- case 12:
1948
- return _context5.abrupt("return", continueWait(true));
1949
-
1950
- case 13:
1951
- body = {};
1952
- text = '';
1953
- _context5.prev = 15;
1954
- _context5.next = 18;
1955
- return response.text();
1956
-
1957
- case 18:
1958
- text = _context5.sent;
1959
- body = JSON.parse(text);
1960
- _context5.next = 25;
1961
- break;
1962
-
1963
- case 22:
1964
- _context5.prev = 22;
1965
- _context5.t0 = _context5["catch"](15);
1966
- body.error = text;
1967
-
1968
- case 25:
1969
- if (!(body.error === 'Continue wait')) {
1970
- _context5.next = 30;
1971
- break;
1972
- }
1973
-
1974
- _context5.next = 28;
1975
- return checkMutex();
1976
-
1977
- case 28:
1978
- if (options.progressCallback) {
1979
- options.progressCallback(new ProgressResult(body));
1980
- }
1981
-
1982
- return _context5.abrupt("return", continueWait());
1983
-
1984
- case 30:
1985
- if (!(response.status !== 200)) {
1986
- _context5.next = 43;
1987
- break;
1988
- }
1989
-
1990
- _context5.next = 33;
1991
- return checkMutex();
1992
-
1993
- case 33:
1994
- if (!(!options.subscribe && requestInstance.unsubscribe)) {
1995
- _context5.next = 36;
1996
- break;
1997
- }
1998
-
1999
- _context5.next = 36;
2000
- return requestInstance.unsubscribe();
2001
-
2002
- case 36:
2003
- error = new RequestError(body.error, body, response.status); // TODO error class
2004
-
2005
- if (!callback) {
2006
- _context5.next = 41;
2007
- break;
2008
- }
2009
-
2010
- callback(error);
2011
- _context5.next = 42;
2012
- break;
2013
-
2014
- case 41:
2015
- throw error;
2016
-
2017
- case 42:
2018
- return _context5.abrupt("return", subscribeNext());
2019
-
2020
- case 43:
2021
- _context5.next = 45;
2022
- return checkMutex();
2023
-
2024
- case 45:
2025
- if (!(!options.subscribe && requestInstance.unsubscribe)) {
2026
- _context5.next = 48;
2027
- break;
2028
- }
2029
-
2030
- _context5.next = 48;
2031
- return requestInstance.unsubscribe();
1313
+ const subscribeNext = async () => {
1314
+ if (options.subscribe && !unsubscribed) {
1315
+ if (requestInstance.unsubscribe) {
1316
+ return next();
1317
+ } else {
1318
+ await new Promise(resolve => setTimeout(() => resolve(), this.pollInterval * 1000));
1319
+ return next();
1320
+ }
1321
+ }
2032
1322
 
2033
- case 48:
2034
- result = toResult(body);
2035
-
2036
- if (!callback) {
2037
- _context5.next = 53;
2038
- break;
2039
- }
2040
-
2041
- callback(null, result);
2042
- _context5.next = 54;
2043
- break;
2044
-
2045
- case 53:
2046
- return _context5.abrupt("return", result);
2047
-
2048
- case 54:
2049
- return _context5.abrupt("return", subscribeNext());
2050
-
2051
- case 55:
2052
- case "end":
2053
- return _context5.stop();
2054
- }
2055
- }
2056
- }, _callee5, null, [[15, 22]]);
2057
- }));
1323
+ return null;
1324
+ };
2058
1325
 
2059
- return function loadImpl(_x3, _x4) {
2060
- return _ref3.apply(this, arguments);
2061
- };
2062
- }();
1326
+ const continueWait = async wait => {
1327
+ if (!unsubscribed) {
1328
+ if (wait) {
1329
+ await new Promise(resolve => setTimeout(() => resolve(), this.pollInterval * 1000));
1330
+ }
2063
1331
 
2064
- var promise = requestPromise.then(function (requestInstance) {
2065
- return mutexPromise(requestInstance.subscribe(loadImpl));
2066
- });
1332
+ return next();
1333
+ }
2067
1334
 
2068
- if (callback) {
2069
- return {
2070
- unsubscribe: function () {
2071
- var _unsubscribe = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
2072
- var requestInstance;
2073
- return _regeneratorRuntime.wrap(function _callee6$(_context6) {
2074
- while (1) {
2075
- switch (_context6.prev = _context6.next) {
2076
- case 0:
2077
- _context6.next = 2;
2078
- return requestPromise;
2079
-
2080
- case 2:
2081
- requestInstance = _context6.sent;
2082
- unsubscribed = true;
2083
-
2084
- if (!requestInstance.unsubscribe) {
2085
- _context6.next = 6;
2086
- break;
2087
- }
2088
-
2089
- return _context6.abrupt("return", requestInstance.unsubscribe());
2090
-
2091
- case 6:
2092
- return _context6.abrupt("return", null);
2093
-
2094
- case 7:
2095
- case "end":
2096
- return _context6.stop();
2097
- }
2098
- }
2099
- }, _callee6);
2100
- }));
2101
-
2102
- function unsubscribe() {
2103
- return _unsubscribe.apply(this, arguments);
2104
- }
1335
+ return null;
1336
+ };
2105
1337
 
2106
- return unsubscribe;
2107
- }()
2108
- };
2109
- } else {
2110
- return promise;
1338
+ if (options.subscribe && !skipAuthorizationUpdate) {
1339
+ await this.updateTransportAuthorization();
2111
1340
  }
2112
- }
2113
- }, {
2114
- key: "updateTransportAuthorization",
2115
- value: function () {
2116
- var _updateTransportAuthorization = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() {
2117
- var _this2 = this;
2118
-
2119
- return _regeneratorRuntime.wrap(function _callee8$(_context8) {
2120
- while (1) {
2121
- switch (_context8.prev = _context8.next) {
2122
- case 0:
2123
- if (!this.updateAuthorizationPromise) {
2124
- _context8.next = 4;
2125
- break;
2126
- }
2127
-
2128
- _context8.next = 3;
2129
- return this.updateAuthorizationPromise;
2130
-
2131
- case 3:
2132
- return _context8.abrupt("return");
2133
-
2134
- case 4:
2135
- if (!(typeof this.apiToken === 'function')) {
2136
- _context8.next = 8;
2137
- break;
2138
- }
2139
-
2140
- this.updateAuthorizationPromise = new Promise( /*#__PURE__*/function () {
2141
- var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(resolve, reject) {
2142
- var token;
2143
- return _regeneratorRuntime.wrap(function _callee7$(_context7) {
2144
- while (1) {
2145
- switch (_context7.prev = _context7.next) {
2146
- case 0:
2147
- _context7.prev = 0;
2148
- _context7.next = 3;
2149
- return _this2.apiToken();
2150
-
2151
- case 3:
2152
- token = _context7.sent;
2153
-
2154
- if (_this2.transport.authorization !== token) {
2155
- _this2.transport.authorization = token;
2156
- }
2157
-
2158
- resolve();
2159
- _context7.next = 11;
2160
- break;
2161
-
2162
- case 8:
2163
- _context7.prev = 8;
2164
- _context7.t0 = _context7["catch"](0);
2165
- reject(_context7.t0);
2166
-
2167
- case 11:
2168
- _context7.prev = 11;
2169
- _this2.updateAuthorizationPromise = null;
2170
- return _context7.finish(11);
2171
-
2172
- case 14:
2173
- case "end":
2174
- return _context7.stop();
2175
- }
2176
- }
2177
- }, _callee7, null, [[0, 8, 11, 14]]);
2178
- }));
2179
-
2180
- return function (_x6, _x7) {
2181
- return _ref6.apply(this, arguments);
2182
- };
2183
- }());
2184
- _context8.next = 8;
2185
- return this.updateAuthorizationPromise;
2186
-
2187
- case 8:
2188
- case "end":
2189
- return _context8.stop();
2190
- }
2191
- }
2192
- }, _callee8, this);
2193
- }));
2194
1341
 
2195
- function updateTransportAuthorization() {
2196
- return _updateTransportAuthorization.apply(this, arguments);
1342
+ skipAuthorizationUpdate = false;
1343
+
1344
+ if (response.status === 502) {
1345
+ await checkMutex();
1346
+ return continueWait(true);
2197
1347
  }
2198
1348
 
2199
- return updateTransportAuthorization;
2200
- }()
2201
- /**
2202
- * Add system properties to a query object.
2203
- * @param {Query} query
2204
- * @param {string} responseFormat
2205
- * @returns {void}
2206
- * @private
2207
- */
1349
+ let body = {};
1350
+ let text = '';
2208
1351
 
2209
- }, {
2210
- key: "patchQueryInternal",
2211
- value: function patchQueryInternal(query, responseFormat) {
2212
- if (responseFormat === ResultType.COMPACT && query.responseFormat !== ResultType.COMPACT) {
2213
- return _objectSpread(_objectSpread({}, query), {}, {
2214
- responseFormat: ResultType.COMPACT
2215
- });
2216
- } else {
2217
- return query;
1352
+ try {
1353
+ text = await response.text();
1354
+ body = JSON.parse(text);
1355
+ } catch (_) {
1356
+ body.error = text;
2218
1357
  }
2219
- }
2220
- /**
2221
- * Process result fetched from the gateway#load method according
2222
- * to the network protocol.
2223
- * @param {*} response
2224
- * @returns ResultSet
2225
- * @private
2226
- */
2227
1358
 
2228
- }, {
2229
- key: "loadResponseInternal",
2230
- value: function loadResponseInternal(response) {
2231
- if (response.results.length && response.results[0].query.responseFormat && response.results[0].query.responseFormat === ResultType.COMPACT) {
2232
- response.results.forEach(function (result, j) {
2233
- var data = [];
2234
- result.data.dataset.forEach(function (r) {
2235
- var row = {};
2236
- result.data.members.forEach(function (m, i) {
2237
- row[m] = r[i];
2238
- });
2239
- data.push(row);
2240
- });
2241
- response.results[j].data = data;
2242
- });
1359
+ if (body.error === 'Continue wait') {
1360
+ await checkMutex();
1361
+
1362
+ if (options.progressCallback) {
1363
+ options.progressCallback(new ProgressResult(body));
1364
+ }
1365
+
1366
+ return continueWait();
2243
1367
  }
2244
1368
 
2245
- return new ResultSet(response, {
2246
- parseDateMeasures: this.parseDateMeasures
2247
- });
2248
- }
2249
- /**
2250
- * Fetch data for the passed `query`. Operates with the
2251
- * `ApiGateway#load` method to fetch the data.
2252
- * @param {Query | Query[]} query
2253
- * @param {LoadMethodOptions | undefined} options
2254
- * @param {LoadMethodCallback<ResultSet> | undefined} callback
2255
- * @param {string} responseFormat
2256
- * @returns {undefined | Promise<ResultSet>}
2257
- */
1369
+ if (response.status !== 200) {
1370
+ await checkMutex();
2258
1371
 
2259
- }, {
2260
- key: "load",
2261
- value: function load(query, options, callback) {
2262
- var _this3 = this;
1372
+ if (!options.subscribe && requestInstance.unsubscribe) {
1373
+ await requestInstance.unsubscribe();
1374
+ }
2263
1375
 
2264
- var responseFormat = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ResultType.DEFAULT;
1376
+ const error = new RequestError(body.error, body, response.status); // TODO error class
2265
1377
 
2266
- if (responseFormat === ResultType.COMPACT) {
2267
- if (Array.isArray(query)) {
2268
- query = query.map(function (q) {
2269
- return _this3.patchQueryInternal(q, ResultType.COMPACT);
2270
- });
1378
+ if (callback) {
1379
+ callback(error);
2271
1380
  } else {
2272
- query = this.patchQueryInternal(query, ResultType.COMPACT);
1381
+ throw error;
2273
1382
  }
1383
+
1384
+ return subscribeNext();
2274
1385
  }
2275
1386
 
2276
- return this.loadMethod(function () {
2277
- return _this3.request('load', {
2278
- query: query,
2279
- queryType: 'multi'
2280
- });
2281
- }, this.loadResponseInternal.bind(this), options, callback);
2282
- }
2283
- /**
2284
- * Allows you to fetch data and receive updates over time. Operates
2285
- * with the `ApiGateway#load` method to fetch the data.
2286
- * @link real-time-data-fetch
2287
- * @param {Query | Query[]} query
2288
- * @param {LoadMethodOptions | null} options
2289
- * @param {LoadMethodCallback<ResultSet> | undefined} callback
2290
- * @param {string} responseFormat
2291
- * @returns {void}
2292
- */
1387
+ await checkMutex();
2293
1388
 
2294
- }, {
2295
- key: "subscribe",
2296
- value: function subscribe(query, options, callback) {
2297
- var _this4 = this;
1389
+ if (!options.subscribe && requestInstance.unsubscribe) {
1390
+ await requestInstance.unsubscribe();
1391
+ }
2298
1392
 
2299
- var responseFormat = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ResultType.DEFAULT;
1393
+ const result = toResult(body);
2300
1394
 
2301
- if (responseFormat === ResultType.COMPACT) {
2302
- if (Array.isArray(query)) {
2303
- query = query.map(function (q) {
2304
- return _this4.patchQueryInternal(q, ResultType.COMPACT);
2305
- });
2306
- } else {
2307
- query = this.patchQueryInternal(query, ResultType.COMPACT);
2308
- }
1395
+ if (callback) {
1396
+ callback(null, result);
1397
+ } else {
1398
+ return result;
2309
1399
  }
2310
1400
 
2311
- return this.loadMethod(function () {
2312
- return _this4.request('subscribe', {
2313
- query: query,
2314
- queryType: 'multi'
2315
- });
2316
- }, this.loadResponseInternal.bind(this), _objectSpread(_objectSpread({}, options), {}, {
2317
- subscribe: true
2318
- }), callback);
1401
+ return subscribeNext();
1402
+ };
1403
+
1404
+ const promise = requestPromise.then(requestInstance => mutexPromise(requestInstance.subscribe(loadImpl)));
1405
+
1406
+ if (callback) {
1407
+ return {
1408
+ unsubscribe: async () => {
1409
+ const requestInstance = await requestPromise;
1410
+ unsubscribed = true;
1411
+
1412
+ if (requestInstance.unsubscribe) {
1413
+ return requestInstance.unsubscribe();
1414
+ }
1415
+
1416
+ return null;
1417
+ }
1418
+ };
1419
+ } else {
1420
+ return promise;
2319
1421
  }
2320
- }, {
2321
- key: "sql",
2322
- value: function sql(query, options, callback) {
2323
- var _this5 = this;
1422
+ }
1423
+
1424
+ async updateTransportAuthorization() {
1425
+ if (this.updateAuthorizationPromise) {
1426
+ await this.updateAuthorizationPromise;
1427
+ return;
1428
+ }
1429
+
1430
+ if (typeof this.apiToken === 'function') {
1431
+ this.updateAuthorizationPromise = new Promise(async (resolve, reject) => {
1432
+ try {
1433
+ const token = await this.apiToken();
2324
1434
 
2325
- return this.loadMethod(function () {
2326
- return _this5.request('sql', {
2327
- query: query
1435
+ if (this.transport.authorization !== token) {
1436
+ this.transport.authorization = token;
1437
+ }
1438
+
1439
+ resolve();
1440
+ } catch (error) {
1441
+ reject(error);
1442
+ } finally {
1443
+ this.updateAuthorizationPromise = null;
1444
+ }
1445
+ });
1446
+ await this.updateAuthorizationPromise;
1447
+ }
1448
+ }
1449
+ /**
1450
+ * Add system properties to a query object.
1451
+ * @param {Query} query
1452
+ * @param {string} responseFormat
1453
+ * @returns {void}
1454
+ * @private
1455
+ */
1456
+
1457
+
1458
+ patchQueryInternal(query, responseFormat) {
1459
+ if (responseFormat === ResultType.COMPACT && query.responseFormat !== ResultType.COMPACT) {
1460
+ return { ...query,
1461
+ responseFormat: ResultType.COMPACT
1462
+ };
1463
+ } else {
1464
+ return query;
1465
+ }
1466
+ }
1467
+ /**
1468
+ * Process result fetched from the gateway#load method according
1469
+ * to the network protocol.
1470
+ * @param {*} response
1471
+ * @returns ResultSet
1472
+ * @private
1473
+ */
1474
+
1475
+
1476
+ loadResponseInternal(response) {
1477
+ if (response.results.length && response.results[0].query.responseFormat && response.results[0].query.responseFormat === ResultType.COMPACT) {
1478
+ response.results.forEach((result, j) => {
1479
+ const data = [];
1480
+ result.data.dataset.forEach(r => {
1481
+ const row = {};
1482
+ result.data.members.forEach((m, i) => {
1483
+ row[m] = r[i];
1484
+ });
1485
+ data.push(row);
2328
1486
  });
2329
- }, function (response) {
2330
- return Array.isArray(response) ? response.map(function (body) {
2331
- return new SqlQuery(body);
2332
- }) : new SqlQuery(response);
2333
- }, options, callback);
1487
+ response.results[j].data = data;
1488
+ });
2334
1489
  }
2335
- }, {
2336
- key: "meta",
2337
- value: function meta(options, callback) {
2338
- var _this6 = this;
2339
-
2340
- return this.loadMethod(function () {
2341
- return _this6.request('meta');
2342
- }, function (body) {
2343
- return new Meta(body);
2344
- }, options, callback);
1490
+
1491
+ return new ResultSet(response, {
1492
+ parseDateMeasures: this.parseDateMeasures
1493
+ });
1494
+ }
1495
+
1496
+ load(query, options, callback, responseFormat = ResultType.DEFAULT) {
1497
+ if (responseFormat === ResultType.COMPACT) {
1498
+ if (Array.isArray(query)) {
1499
+ query = query.map(q => this.patchQueryInternal(q, ResultType.COMPACT));
1500
+ } else {
1501
+ query = this.patchQueryInternal(query, ResultType.COMPACT);
1502
+ }
2345
1503
  }
2346
- }, {
2347
- key: "dryRun",
2348
- value: function dryRun(query, options, callback) {
2349
- var _this7 = this;
2350
1504
 
2351
- return this.loadMethod(function () {
2352
- return _this7.request('dry-run', {
2353
- query: query
2354
- });
2355
- }, function (response) {
2356
- return response;
2357
- }, options, callback);
1505
+ return this.loadMethod(() => this.request('load', {
1506
+ query,
1507
+ queryType: 'multi'
1508
+ }), this.loadResponseInternal.bind(this), options, callback);
1509
+ }
1510
+
1511
+ subscribe(query, options, callback, responseFormat = ResultType.DEFAULT) {
1512
+ if (responseFormat === ResultType.COMPACT) {
1513
+ if (Array.isArray(query)) {
1514
+ query = query.map(q => this.patchQueryInternal(q, ResultType.COMPACT));
1515
+ } else {
1516
+ query = this.patchQueryInternal(query, ResultType.COMPACT);
1517
+ }
2358
1518
  }
2359
- }]);
2360
1519
 
2361
- return CubejsApi;
2362
- }();
1520
+ return this.loadMethod(() => this.request('subscribe', {
1521
+ query,
1522
+ queryType: 'multi'
1523
+ }), this.loadResponseInternal.bind(this), { ...options,
1524
+ subscribe: true
1525
+ }, callback);
1526
+ }
2363
1527
 
2364
- var index = (function (apiToken, options) {
2365
- return new CubejsApi(apiToken, options);
2366
- });
1528
+ sql(query, options, callback) {
1529
+ return this.loadMethod(() => this.request('sql', {
1530
+ query
1531
+ }), response => Array.isArray(response) ? response.map(body => new SqlQuery(body)) : new SqlQuery(response), options, callback);
1532
+ }
1533
+
1534
+ meta(options, callback) {
1535
+ return this.loadMethod(() => this.request('meta'), body => new Meta(body), options, callback);
1536
+ }
1537
+
1538
+ dryRun(query, options, callback) {
1539
+ return this.loadMethod(() => this.request('dry-run', {
1540
+ query
1541
+ }), response => response, options, callback);
1542
+ }
1543
+
1544
+ }
1545
+
1546
+ var index = ((apiToken, options) => new CubejsApi(apiToken, options));
2367
1547
 
2368
1548
  export default index;
2369
1549
  export { CubejsApi, DEFAULT_GRANULARITY, GRANULARITIES, HttpTransport, RequestError, ResultSet, aliasSeries, areQueriesEqual, defaultHeuristics, defaultOrder, flattenFilters, getOrderMembersFromOrder, getQueryMembers, isQueryPresent, moveItemInArray, movePivotItem, removeEmptyQueryFields, validateQuery };