UNPKG

45 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7var tslib = require('tslib');
8var jsMagic = require('js-magic');
9var axios = _interopDefault(require('axios'));
10var catchDecorator = require('@magna_shogun/catch-decorator');
11
12function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
13 try {
14 var info = gen[key](arg);
15 var value = info.value;
16 } catch (error) {
17 reject(error);
18 return;
19 }
20
21 if (info.done) {
22 resolve(value);
23 } else {
24 Promise.resolve(value).then(_next, _throw);
25 }
26}
27
28function _asyncToGenerator(fn) {
29 return function () {
30 var self = this,
31 args = arguments;
32 return new Promise(function (resolve, reject) {
33 var gen = fn.apply(self, args);
34
35 function _next(value) {
36 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
37 }
38
39 function _throw(err) {
40 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
41 }
42
43 _next(undefined);
44 });
45 };
46}
47
48function _extends() {
49 _extends = Object.assign || function (target) {
50 for (var i = 1; i < arguments.length; i++) {
51 var source = arguments[i];
52
53 for (var key in source) {
54 if (Object.prototype.hasOwnProperty.call(source, key)) {
55 target[key] = source[key];
56 }
57 }
58 }
59
60 return target;
61 };
62
63 return _extends.apply(this, arguments);
64}
65
66function _objectWithoutPropertiesLoose(source, excluded) {
67 if (source == null) return {};
68 var target = {};
69 var sourceKeys = Object.keys(source);
70 var key, i;
71
72 for (i = 0; i < sourceKeys.length; i++) {
73 key = sourceKeys[i];
74 if (excluded.indexOf(key) >= 0) continue;
75 target[key] = source[key];
76 }
77
78 return target;
79}
80
81function createCommonjsModule(fn, module) {
82 return module = { exports: {} }, fn(module, module.exports), module.exports;
83}
84
85var runtime_1 = createCommonjsModule(function (module) {
86/**
87 * Copyright (c) 2014-present, Facebook, Inc.
88 *
89 * This source code is licensed under the MIT license found in the
90 * LICENSE file in the root directory of this source tree.
91 */
92
93var runtime = (function (exports) {
94
95 var Op = Object.prototype;
96 var hasOwn = Op.hasOwnProperty;
97 var undefined$1; // More compressible than void 0.
98 var $Symbol = typeof Symbol === "function" ? Symbol : {};
99 var iteratorSymbol = $Symbol.iterator || "@@iterator";
100 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
101 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
102
103 function define(obj, key, value) {
104 Object.defineProperty(obj, key, {
105 value: value,
106 enumerable: true,
107 configurable: true,
108 writable: true
109 });
110 return obj[key];
111 }
112 try {
113 // IE 8 has a broken Object.defineProperty that only works on DOM objects.
114 define({}, "");
115 } catch (err) {
116 define = function(obj, key, value) {
117 return obj[key] = value;
118 };
119 }
120
121 function wrap(innerFn, outerFn, self, tryLocsList) {
122 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
123 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
124 var generator = Object.create(protoGenerator.prototype);
125 var context = new Context(tryLocsList || []);
126
127 // The ._invoke method unifies the implementations of the .next,
128 // .throw, and .return methods.
129 generator._invoke = makeInvokeMethod(innerFn, self, context);
130
131 return generator;
132 }
133 exports.wrap = wrap;
134
135 // Try/catch helper to minimize deoptimizations. Returns a completion
136 // record like context.tryEntries[i].completion. This interface could
137 // have been (and was previously) designed to take a closure to be
138 // invoked without arguments, but in all the cases we care about we
139 // already have an existing method we want to call, so there's no need
140 // to create a new function object. We can even get away with assuming
141 // the method takes exactly one argument, since that happens to be true
142 // in every case, so we don't have to touch the arguments object. The
143 // only additional allocation required is the completion record, which
144 // has a stable shape and so hopefully should be cheap to allocate.
145 function tryCatch(fn, obj, arg) {
146 try {
147 return { type: "normal", arg: fn.call(obj, arg) };
148 } catch (err) {
149 return { type: "throw", arg: err };
150 }
151 }
152
153 var GenStateSuspendedStart = "suspendedStart";
154 var GenStateSuspendedYield = "suspendedYield";
155 var GenStateExecuting = "executing";
156 var GenStateCompleted = "completed";
157
158 // Returning this object from the innerFn has the same effect as
159 // breaking out of the dispatch switch statement.
160 var ContinueSentinel = {};
161
162 // Dummy constructor functions that we use as the .constructor and
163 // .constructor.prototype properties for functions that return Generator
164 // objects. For full spec compliance, you may wish to configure your
165 // minifier not to mangle the names of these two functions.
166 function Generator() {}
167 function GeneratorFunction() {}
168 function GeneratorFunctionPrototype() {}
169
170 // This is a polyfill for %IteratorPrototype% for environments that
171 // don't natively support it.
172 var IteratorPrototype = {};
173 IteratorPrototype[iteratorSymbol] = function () {
174 return this;
175 };
176
177 var getProto = Object.getPrototypeOf;
178 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
179 if (NativeIteratorPrototype &&
180 NativeIteratorPrototype !== Op &&
181 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
182 // This environment has a native %IteratorPrototype%; use it instead
183 // of the polyfill.
184 IteratorPrototype = NativeIteratorPrototype;
185 }
186
187 var Gp = GeneratorFunctionPrototype.prototype =
188 Generator.prototype = Object.create(IteratorPrototype);
189 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
190 GeneratorFunctionPrototype.constructor = GeneratorFunction;
191 GeneratorFunction.displayName = define(
192 GeneratorFunctionPrototype,
193 toStringTagSymbol,
194 "GeneratorFunction"
195 );
196
197 // Helper for defining the .next, .throw, and .return methods of the
198 // Iterator interface in terms of a single ._invoke method.
199 function defineIteratorMethods(prototype) {
200 ["next", "throw", "return"].forEach(function(method) {
201 define(prototype, method, function(arg) {
202 return this._invoke(method, arg);
203 });
204 });
205 }
206
207 exports.isGeneratorFunction = function(genFun) {
208 var ctor = typeof genFun === "function" && genFun.constructor;
209 return ctor
210 ? ctor === GeneratorFunction ||
211 // For the native GeneratorFunction constructor, the best we can
212 // do is to check its .name property.
213 (ctor.displayName || ctor.name) === "GeneratorFunction"
214 : false;
215 };
216
217 exports.mark = function(genFun) {
218 if (Object.setPrototypeOf) {
219 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
220 } else {
221 genFun.__proto__ = GeneratorFunctionPrototype;
222 define(genFun, toStringTagSymbol, "GeneratorFunction");
223 }
224 genFun.prototype = Object.create(Gp);
225 return genFun;
226 };
227
228 // Within the body of any async function, `await x` is transformed to
229 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
230 // `hasOwn.call(value, "__await")` to determine if the yielded value is
231 // meant to be awaited.
232 exports.awrap = function(arg) {
233 return { __await: arg };
234 };
235
236 function AsyncIterator(generator, PromiseImpl) {
237 function invoke(method, arg, resolve, reject) {
238 var record = tryCatch(generator[method], generator, arg);
239 if (record.type === "throw") {
240 reject(record.arg);
241 } else {
242 var result = record.arg;
243 var value = result.value;
244 if (value &&
245 typeof value === "object" &&
246 hasOwn.call(value, "__await")) {
247 return PromiseImpl.resolve(value.__await).then(function(value) {
248 invoke("next", value, resolve, reject);
249 }, function(err) {
250 invoke("throw", err, resolve, reject);
251 });
252 }
253
254 return PromiseImpl.resolve(value).then(function(unwrapped) {
255 // When a yielded Promise is resolved, its final value becomes
256 // the .value of the Promise<{value,done}> result for the
257 // current iteration.
258 result.value = unwrapped;
259 resolve(result);
260 }, function(error) {
261 // If a rejected Promise was yielded, throw the rejection back
262 // into the async generator function so it can be handled there.
263 return invoke("throw", error, resolve, reject);
264 });
265 }
266 }
267
268 var previousPromise;
269
270 function enqueue(method, arg) {
271 function callInvokeWithMethodAndArg() {
272 return new PromiseImpl(function(resolve, reject) {
273 invoke(method, arg, resolve, reject);
274 });
275 }
276
277 return previousPromise =
278 // If enqueue has been called before, then we want to wait until
279 // all previous Promises have been resolved before calling invoke,
280 // so that results are always delivered in the correct order. If
281 // enqueue has not been called before, then it is important to
282 // call invoke immediately, without waiting on a callback to fire,
283 // so that the async generator function has the opportunity to do
284 // any necessary setup in a predictable way. This predictability
285 // is why the Promise constructor synchronously invokes its
286 // executor callback, and why async functions synchronously
287 // execute code before the first await. Since we implement simple
288 // async functions in terms of async generators, it is especially
289 // important to get this right, even though it requires care.
290 previousPromise ? previousPromise.then(
291 callInvokeWithMethodAndArg,
292 // Avoid propagating failures to Promises returned by later
293 // invocations of the iterator.
294 callInvokeWithMethodAndArg
295 ) : callInvokeWithMethodAndArg();
296 }
297
298 // Define the unified helper method that is used to implement .next,
299 // .throw, and .return (see defineIteratorMethods).
300 this._invoke = enqueue;
301 }
302
303 defineIteratorMethods(AsyncIterator.prototype);
304 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
305 return this;
306 };
307 exports.AsyncIterator = AsyncIterator;
308
309 // Note that simple async functions are implemented on top of
310 // AsyncIterator objects; they just return a Promise for the value of
311 // the final result produced by the iterator.
312 exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
313 if (PromiseImpl === void 0) PromiseImpl = Promise;
314
315 var iter = new AsyncIterator(
316 wrap(innerFn, outerFn, self, tryLocsList),
317 PromiseImpl
318 );
319
320 return exports.isGeneratorFunction(outerFn)
321 ? iter // If outerFn is a generator, return the full iterator.
322 : iter.next().then(function(result) {
323 return result.done ? result.value : iter.next();
324 });
325 };
326
327 function makeInvokeMethod(innerFn, self, context) {
328 var state = GenStateSuspendedStart;
329
330 return function invoke(method, arg) {
331 if (state === GenStateExecuting) {
332 throw new Error("Generator is already running");
333 }
334
335 if (state === GenStateCompleted) {
336 if (method === "throw") {
337 throw arg;
338 }
339
340 // Be forgiving, per 25.3.3.3.3 of the spec:
341 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
342 return doneResult();
343 }
344
345 context.method = method;
346 context.arg = arg;
347
348 while (true) {
349 var delegate = context.delegate;
350 if (delegate) {
351 var delegateResult = maybeInvokeDelegate(delegate, context);
352 if (delegateResult) {
353 if (delegateResult === ContinueSentinel) continue;
354 return delegateResult;
355 }
356 }
357
358 if (context.method === "next") {
359 // Setting context._sent for legacy support of Babel's
360 // function.sent implementation.
361 context.sent = context._sent = context.arg;
362
363 } else if (context.method === "throw") {
364 if (state === GenStateSuspendedStart) {
365 state = GenStateCompleted;
366 throw context.arg;
367 }
368
369 context.dispatchException(context.arg);
370
371 } else if (context.method === "return") {
372 context.abrupt("return", context.arg);
373 }
374
375 state = GenStateExecuting;
376
377 var record = tryCatch(innerFn, self, context);
378 if (record.type === "normal") {
379 // If an exception is thrown from innerFn, we leave state ===
380 // GenStateExecuting and loop back for another invocation.
381 state = context.done
382 ? GenStateCompleted
383 : GenStateSuspendedYield;
384
385 if (record.arg === ContinueSentinel) {
386 continue;
387 }
388
389 return {
390 value: record.arg,
391 done: context.done
392 };
393
394 } else if (record.type === "throw") {
395 state = GenStateCompleted;
396 // Dispatch the exception by looping back around to the
397 // context.dispatchException(context.arg) call above.
398 context.method = "throw";
399 context.arg = record.arg;
400 }
401 }
402 };
403 }
404
405 // Call delegate.iterator[context.method](context.arg) and handle the
406 // result, either by returning a { value, done } result from the
407 // delegate iterator, or by modifying context.method and context.arg,
408 // setting context.delegate to null, and returning the ContinueSentinel.
409 function maybeInvokeDelegate(delegate, context) {
410 var method = delegate.iterator[context.method];
411 if (method === undefined$1) {
412 // A .throw or .return when the delegate iterator has no .throw
413 // method always terminates the yield* loop.
414 context.delegate = null;
415
416 if (context.method === "throw") {
417 // Note: ["return"] must be used for ES3 parsing compatibility.
418 if (delegate.iterator["return"]) {
419 // If the delegate iterator has a return method, give it a
420 // chance to clean up.
421 context.method = "return";
422 context.arg = undefined$1;
423 maybeInvokeDelegate(delegate, context);
424
425 if (context.method === "throw") {
426 // If maybeInvokeDelegate(context) changed context.method from
427 // "return" to "throw", let that override the TypeError below.
428 return ContinueSentinel;
429 }
430 }
431
432 context.method = "throw";
433 context.arg = new TypeError(
434 "The iterator does not provide a 'throw' method");
435 }
436
437 return ContinueSentinel;
438 }
439
440 var record = tryCatch(method, delegate.iterator, context.arg);
441
442 if (record.type === "throw") {
443 context.method = "throw";
444 context.arg = record.arg;
445 context.delegate = null;
446 return ContinueSentinel;
447 }
448
449 var info = record.arg;
450
451 if (! info) {
452 context.method = "throw";
453 context.arg = new TypeError("iterator result is not an object");
454 context.delegate = null;
455 return ContinueSentinel;
456 }
457
458 if (info.done) {
459 // Assign the result of the finished delegate to the temporary
460 // variable specified by delegate.resultName (see delegateYield).
461 context[delegate.resultName] = info.value;
462
463 // Resume execution at the desired location (see delegateYield).
464 context.next = delegate.nextLoc;
465
466 // If context.method was "throw" but the delegate handled the
467 // exception, let the outer generator proceed normally. If
468 // context.method was "next", forget context.arg since it has been
469 // "consumed" by the delegate iterator. If context.method was
470 // "return", allow the original .return call to continue in the
471 // outer generator.
472 if (context.method !== "return") {
473 context.method = "next";
474 context.arg = undefined$1;
475 }
476
477 } else {
478 // Re-yield the result returned by the delegate method.
479 return info;
480 }
481
482 // The delegate iterator is finished, so forget it and continue with
483 // the outer generator.
484 context.delegate = null;
485 return ContinueSentinel;
486 }
487
488 // Define Generator.prototype.{next,throw,return} in terms of the
489 // unified ._invoke helper method.
490 defineIteratorMethods(Gp);
491
492 define(Gp, toStringTagSymbol, "Generator");
493
494 // A Generator should always return itself as the iterator object when the
495 // @@iterator function is called on it. Some browsers' implementations of the
496 // iterator prototype chain incorrectly implement this, causing the Generator
497 // object to not be returned from this call. This ensures that doesn't happen.
498 // See https://github.com/facebook/regenerator/issues/274 for more details.
499 Gp[iteratorSymbol] = function() {
500 return this;
501 };
502
503 Gp.toString = function() {
504 return "[object Generator]";
505 };
506
507 function pushTryEntry(locs) {
508 var entry = { tryLoc: locs[0] };
509
510 if (1 in locs) {
511 entry.catchLoc = locs[1];
512 }
513
514 if (2 in locs) {
515 entry.finallyLoc = locs[2];
516 entry.afterLoc = locs[3];
517 }
518
519 this.tryEntries.push(entry);
520 }
521
522 function resetTryEntry(entry) {
523 var record = entry.completion || {};
524 record.type = "normal";
525 delete record.arg;
526 entry.completion = record;
527 }
528
529 function Context(tryLocsList) {
530 // The root entry object (effectively a try statement without a catch
531 // or a finally block) gives us a place to store values thrown from
532 // locations where there is no enclosing try statement.
533 this.tryEntries = [{ tryLoc: "root" }];
534 tryLocsList.forEach(pushTryEntry, this);
535 this.reset(true);
536 }
537
538 exports.keys = function(object) {
539 var keys = [];
540 for (var key in object) {
541 keys.push(key);
542 }
543 keys.reverse();
544
545 // Rather than returning an object with a next method, we keep
546 // things simple and return the next function itself.
547 return function next() {
548 while (keys.length) {
549 var key = keys.pop();
550 if (key in object) {
551 next.value = key;
552 next.done = false;
553 return next;
554 }
555 }
556
557 // To avoid creating an additional object, we just hang the .value
558 // and .done properties off the next function object itself. This
559 // also ensures that the minifier will not anonymize the function.
560 next.done = true;
561 return next;
562 };
563 };
564
565 function values(iterable) {
566 if (iterable) {
567 var iteratorMethod = iterable[iteratorSymbol];
568 if (iteratorMethod) {
569 return iteratorMethod.call(iterable);
570 }
571
572 if (typeof iterable.next === "function") {
573 return iterable;
574 }
575
576 if (!isNaN(iterable.length)) {
577 var i = -1, next = function next() {
578 while (++i < iterable.length) {
579 if (hasOwn.call(iterable, i)) {
580 next.value = iterable[i];
581 next.done = false;
582 return next;
583 }
584 }
585
586 next.value = undefined$1;
587 next.done = true;
588
589 return next;
590 };
591
592 return next.next = next;
593 }
594 }
595
596 // Return an iterator with no values.
597 return { next: doneResult };
598 }
599 exports.values = values;
600
601 function doneResult() {
602 return { value: undefined$1, done: true };
603 }
604
605 Context.prototype = {
606 constructor: Context,
607
608 reset: function(skipTempReset) {
609 this.prev = 0;
610 this.next = 0;
611 // Resetting context._sent for legacy support of Babel's
612 // function.sent implementation.
613 this.sent = this._sent = undefined$1;
614 this.done = false;
615 this.delegate = null;
616
617 this.method = "next";
618 this.arg = undefined$1;
619
620 this.tryEntries.forEach(resetTryEntry);
621
622 if (!skipTempReset) {
623 for (var name in this) {
624 // Not sure about the optimal order of these conditions:
625 if (name.charAt(0) === "t" &&
626 hasOwn.call(this, name) &&
627 !isNaN(+name.slice(1))) {
628 this[name] = undefined$1;
629 }
630 }
631 }
632 },
633
634 stop: function() {
635 this.done = true;
636
637 var rootEntry = this.tryEntries[0];
638 var rootRecord = rootEntry.completion;
639 if (rootRecord.type === "throw") {
640 throw rootRecord.arg;
641 }
642
643 return this.rval;
644 },
645
646 dispatchException: function(exception) {
647 if (this.done) {
648 throw exception;
649 }
650
651 var context = this;
652 function handle(loc, caught) {
653 record.type = "throw";
654 record.arg = exception;
655 context.next = loc;
656
657 if (caught) {
658 // If the dispatched exception was caught by a catch block,
659 // then let that catch block handle the exception normally.
660 context.method = "next";
661 context.arg = undefined$1;
662 }
663
664 return !! caught;
665 }
666
667 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
668 var entry = this.tryEntries[i];
669 var record = entry.completion;
670
671 if (entry.tryLoc === "root") {
672 // Exception thrown outside of any try block that could handle
673 // it, so set the completion value of the entire function to
674 // throw the exception.
675 return handle("end");
676 }
677
678 if (entry.tryLoc <= this.prev) {
679 var hasCatch = hasOwn.call(entry, "catchLoc");
680 var hasFinally = hasOwn.call(entry, "finallyLoc");
681
682 if (hasCatch && hasFinally) {
683 if (this.prev < entry.catchLoc) {
684 return handle(entry.catchLoc, true);
685 } else if (this.prev < entry.finallyLoc) {
686 return handle(entry.finallyLoc);
687 }
688
689 } else if (hasCatch) {
690 if (this.prev < entry.catchLoc) {
691 return handle(entry.catchLoc, true);
692 }
693
694 } else if (hasFinally) {
695 if (this.prev < entry.finallyLoc) {
696 return handle(entry.finallyLoc);
697 }
698
699 } else {
700 throw new Error("try statement without catch or finally");
701 }
702 }
703 }
704 },
705
706 abrupt: function(type, arg) {
707 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
708 var entry = this.tryEntries[i];
709 if (entry.tryLoc <= this.prev &&
710 hasOwn.call(entry, "finallyLoc") &&
711 this.prev < entry.finallyLoc) {
712 var finallyEntry = entry;
713 break;
714 }
715 }
716
717 if (finallyEntry &&
718 (type === "break" ||
719 type === "continue") &&
720 finallyEntry.tryLoc <= arg &&
721 arg <= finallyEntry.finallyLoc) {
722 // Ignore the finally entry if control is not jumping to a
723 // location outside the try/catch block.
724 finallyEntry = null;
725 }
726
727 var record = finallyEntry ? finallyEntry.completion : {};
728 record.type = type;
729 record.arg = arg;
730
731 if (finallyEntry) {
732 this.method = "next";
733 this.next = finallyEntry.finallyLoc;
734 return ContinueSentinel;
735 }
736
737 return this.complete(record);
738 },
739
740 complete: function(record, afterLoc) {
741 if (record.type === "throw") {
742 throw record.arg;
743 }
744
745 if (record.type === "break" ||
746 record.type === "continue") {
747 this.next = record.arg;
748 } else if (record.type === "return") {
749 this.rval = this.arg = record.arg;
750 this.method = "return";
751 this.next = "end";
752 } else if (record.type === "normal" && afterLoc) {
753 this.next = afterLoc;
754 }
755
756 return ContinueSentinel;
757 },
758
759 finish: function(finallyLoc) {
760 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
761 var entry = this.tryEntries[i];
762 if (entry.finallyLoc === finallyLoc) {
763 this.complete(entry.completion, entry.afterLoc);
764 resetTryEntry(entry);
765 return ContinueSentinel;
766 }
767 }
768 },
769
770 "catch": function(tryLoc) {
771 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
772 var entry = this.tryEntries[i];
773 if (entry.tryLoc === tryLoc) {
774 var record = entry.completion;
775 if (record.type === "throw") {
776 var thrown = record.arg;
777 resetTryEntry(entry);
778 }
779 return thrown;
780 }
781 }
782
783 // The context.catch method must only be called with a location
784 // argument that corresponds to a known catch block.
785 throw new Error("illegal catch attempt");
786 },
787
788 delegateYield: function(iterable, resultName, nextLoc) {
789 this.delegate = {
790 iterator: values(iterable),
791 resultName: resultName,
792 nextLoc: nextLoc
793 };
794
795 if (this.method === "next") {
796 // Deliberately forget the last sent value so that we don't
797 // accidentally pass it on to the delegate.
798 this.arg = undefined$1;
799 }
800
801 return ContinueSentinel;
802 }
803 };
804
805 // Regardless of whether this script is executing as a CommonJS module
806 // or not, return the runtime object so that we can declare the variable
807 // regeneratorRuntime in the outer scope, which allows this module to be
808 // injected easily by `bin/regenerator --include-runtime script.js`.
809 return exports;
810
811}(
812 // If this script is executing as a CommonJS module, use module.exports
813 // as the regeneratorRuntime namespace. Otherwise create a new empty
814 // object. Either way, the resulting object will be used to initialize
815 // the regeneratorRuntime variable at the top of this file.
816 module.exports
817));
818
819try {
820 regeneratorRuntime = runtime;
821} catch (accidentalStrictMode) {
822 // This module should not be running in strict mode, so the above
823 // assignment should always work unless something is misconfigured. Just
824 // in case runtime.js accidentally runs in strict mode, we can escape
825 // strict mode using a global Function call. This could conceivably fail
826 // if a Content Security Policy forbids using Function, but in that case
827 // the proper solution is to fix the accidental strict mode problem. If
828 // you've misconfigured your bundler to force strict mode and applied a
829 // CSP to forbid Function, and you're not willing to fix either of those
830 // problems, please detail your unique predicament in a GitHub issue.
831 Function("r", "regeneratorRuntime = r")(runtime);
832}
833});
834
835var HttpRequestErrorHandler = /*#__PURE__*/function () {
836 function HttpRequestErrorHandler(logger, httpRequestErrorService, strategy) {
837 /**
838 * @var noThrowStrategies List of strategies excluded from error throwing
839 *
840 * @memberof HttpRequestHandler
841 */
842 this.noThrowStrategies = ['reject', 'silent'];
843 this.logger = logger;
844 this.httpRequestErrorService = httpRequestErrorService;
845 this.strategy = strategy;
846 }
847 /**
848 * Process and Error
849 *
850 * @param {*} error Error instance or message
851 * @throws Request error context
852 * @returns {void}
853 */
854
855
856 var _proto = HttpRequestErrorHandler.prototype;
857
858 _proto.process = function process(error) {
859 if (this.logger && this.logger.warn) {
860 this.logger.warn('API ERROR', error);
861 }
862
863 var errorContext = error;
864
865 if (typeof error === 'string') {
866 errorContext = new Error(error);
867 }
868
869 if (this.httpRequestErrorService) {
870 if (typeof this.httpRequestErrorService.process !== 'undefined') {
871 this.httpRequestErrorService.process(errorContext);
872 } else if (typeof this.httpRequestErrorService === 'function') {
873 this.httpRequestErrorService(errorContext);
874 }
875 }
876
877 if (!this.noThrowStrategies.includes(this.strategy)) {
878 throw errorContext;
879 }
880 };
881
882 return HttpRequestErrorHandler;
883}();
884
885/**
886 * Generic Request Handler
887 * It creates an Axios instance and handles requests within that instance
888 * It handles errors depending on a chosen error handling strategy
889 */
890
891exports.HttpRequestHandler = /*#__PURE__*/function () {
892 /**
893 * Creates an instance of HttpRequestHandler
894 *
895 * @param {string} baseURL Base URL for all API calls
896 * @param {number} timeout Request timeout
897 * @param {string} strategy Error Handling Strategy
898 * @param {string} flattenResponse Whether to flatten response "data" object within "data" one
899 * @param {*} logger Instance of Logger Class
900 * @param {*} httpRequestErrorService Instance of Error Service Class
901 *
902 * @memberof HttpRequestHandler
903 */
904 function HttpRequestHandler(_ref) {
905 var _ref$baseURL = _ref.baseURL,
906 baseURL = _ref$baseURL === void 0 ? '' : _ref$baseURL,
907 _ref$timeout = _ref.timeout,
908 timeout = _ref$timeout === void 0 ? null : _ref$timeout,
909 _ref$strategy = _ref.strategy,
910 strategy = _ref$strategy === void 0 ? null : _ref$strategy,
911 _ref$flattenResponse = _ref.flattenResponse,
912 flattenResponse = _ref$flattenResponse === void 0 ? null : _ref$flattenResponse,
913 _ref$logger = _ref.logger,
914 logger = _ref$logger === void 0 ? null : _ref$logger,
915 _ref$httpRequestError = _ref.httpRequestErrorService,
916 httpRequestErrorService = _ref$httpRequestError === void 0 ? null : _ref$httpRequestError,
917 config = _objectWithoutPropertiesLoose(_ref, ["baseURL", "timeout", "strategy", "flattenResponse", "logger", "httpRequestErrorService"]);
918
919 /**
920 * @var timeout Request timeout
921 *
922 * @memberof HttpRequestHandler
923 */
924 this.timeout = 30000;
925 /**
926 * @var strategy Request timeout
927 *
928 * @memberof HttpRequestHandler
929 */
930
931 this.strategy = 'silent';
932 /**
933 * @var flattenResponse Response flattening
934 *
935 * @memberof HttpRequestHandler
936 */
937
938 this.flattenResponse = true;
939 this.timeout = timeout !== null ? timeout : this.timeout;
940 this.strategy = strategy !== null ? strategy : this.strategy;
941 this.flattenResponse = flattenResponse !== null ? flattenResponse : this.flattenResponse;
942 this.logger = logger || global.console || window.console || null;
943 this.httpRequestErrorService = httpRequestErrorService;
944 this.requestInstance = axios.create(_extends({}, config, {
945 baseURL: baseURL,
946 timeout: this.timeout
947 }));
948 }
949 /**
950 * Get Provider Instance
951 *
952 * @returns {AxiosInstance} Provider's instance
953 * @memberof HttpRequestHandler
954 */
955
956
957 var _proto = HttpRequestHandler.prototype;
958
959 _proto.getInstance = function getInstance() {
960 return this.requestInstance;
961 }
962 /**
963 * Intercept Request
964 *
965 * @param {*} callback callback to use before request
966 * @returns {void}
967 * @memberof HttpRequestHandler
968 */
969 ;
970
971 _proto.interceptRequest = function interceptRequest(callback) {
972 this.getInstance().interceptors.request.use(callback);
973 }
974 /**
975 * POST Request
976 *
977 * @param {string} url Url
978 * @param {*} data Payload
979 * @param {AxiosRequestConfig} config Config
980 * @throws {Error} If request fails
981 * @returns {Promise} Request response or error info
982 * @memberof HttpRequestHandler
983 */
984 ;
985
986 _proto.post = function post(url, data, config) {
987 if (data === void 0) {
988 data = null;
989 }
990
991 if (config === void 0) {
992 config = null;
993 }
994
995 return this.handleRequest({
996 type: 'post',
997 url: url,
998 data: data,
999 config: config
1000 });
1001 }
1002 /**
1003 * GET Request
1004 *
1005 * @param {string} url Url
1006 * @param {*} data Payload
1007 * @param {AxiosRequestConfig} config Config
1008 * @throws {Error} If request fails
1009 * @returns {Promise} Request response or error info
1010 * @memberof HttpRequestHandler
1011 */
1012 ;
1013
1014 _proto.get = function get(url, data, config) {
1015 if (data === void 0) {
1016 data = null;
1017 }
1018
1019 if (config === void 0) {
1020 config = null;
1021 }
1022
1023 return this.handleRequest({
1024 type: 'get',
1025 url: url,
1026 data: data,
1027 config: config
1028 });
1029 }
1030 /**
1031 * PUT Request
1032 *
1033 * @param {string} url Url
1034 * @param {*} data Payload
1035 * @param {AxiosRequestConfig} config Config
1036 * @throws {Error} If request fails
1037 * @returns {Promise} Request response or error info
1038 * @memberof HttpRequestHandler
1039 */
1040 ;
1041
1042 _proto.put = function put(url, data, config) {
1043 if (data === void 0) {
1044 data = null;
1045 }
1046
1047 if (config === void 0) {
1048 config = null;
1049 }
1050
1051 return this.handleRequest({
1052 type: 'put',
1053 url: url,
1054 data: data,
1055 config: config
1056 });
1057 }
1058 /**
1059 * DELETE Request
1060 *
1061 * @param {string} url Url
1062 * @param {*} data Payload
1063 * @param {AxiosRequestConfig} config Config
1064 * @throws {Error} If request fails
1065 * @returns {Promise} Request response or error info
1066 * @memberof HttpRequestHandler
1067 */
1068 ;
1069
1070 _proto["delete"] = function _delete(url, data, config) {
1071 if (data === void 0) {
1072 data = null;
1073 }
1074
1075 if (config === void 0) {
1076 config = null;
1077 }
1078
1079 return this.handleRequest({
1080 type: 'delete',
1081 url: url,
1082 data: data,
1083 config: config
1084 });
1085 }
1086 /**
1087 * PATCH Request
1088 *
1089 * @param {string} url Url
1090 * @param {*} data Payload
1091 * @param {AxiosRequestConfig} config Config
1092 * @throws {Error} If request fails
1093 * @returns {Promise} Request response or error info
1094 * @memberof HttpRequestHandler
1095 */
1096 ;
1097
1098 _proto.patch = function patch(url, data, config) {
1099 if (data === void 0) {
1100 data = null;
1101 }
1102
1103 if (config === void 0) {
1104 config = null;
1105 }
1106
1107 return this.handleRequest({
1108 type: 'patch',
1109 url: url,
1110 data: data,
1111 config: config
1112 });
1113 }
1114 /**
1115 * HEAD Request
1116 *
1117 * @param {string} url Url
1118 * @param {*} data Payload
1119 * @param {AxiosRequestConfig} config Config
1120 * @throws {Error} If request fails
1121 * @returns {Promise} Request response or error info
1122 * @memberof HttpRequestHandler
1123 */
1124 ;
1125
1126 _proto.head = function head(url, data, config) {
1127 if (data === void 0) {
1128 data = null;
1129 }
1130
1131 if (config === void 0) {
1132 config = null;
1133 }
1134
1135 return this.handleRequest({
1136 type: 'head',
1137 url: url,
1138 data: data,
1139 config: config
1140 });
1141 }
1142 /**
1143 * Get Provider Instance
1144 *
1145 * @param {Error} err Error instance
1146 * @returns {AxiosInstance} Provider's instance
1147 * @memberof HttpRequestHandler
1148 */
1149 ;
1150
1151 _proto.processRequestError = function processRequestError(err) {
1152 return new HttpRequestErrorHandler(this.logger, this.httpRequestErrorService, this.strategy).process(err);
1153 }
1154 /**
1155 * Handle Request depending on used strategy
1156 *
1157 * @param {object} payload Payload
1158 * @param {string} payload.type Request type
1159 * @param {string} payload.url Request url
1160 * @param {*} payload.data Request data
1161 * @param {AxiosRequestConfig} payload.config Config to modify request
1162 * @throws {Error}
1163 * @returns {Promise} Response Data
1164 * @memberof HttpRequestHandler
1165 */
1166 ;
1167
1168 _proto.handleRequest =
1169 /*#__PURE__*/
1170 function () {
1171 var _handleRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(_ref2) {
1172 var _extends2;
1173
1174 var type, url, _ref2$data, data, _ref2$config, config, response, requestConfig, key;
1175
1176 return runtime_1.wrap(function _callee$(_context) {
1177 while (1) {
1178 switch (_context.prev = _context.next) {
1179 case 0:
1180 type = _ref2.type, url = _ref2.url, _ref2$data = _ref2.data, data = _ref2$data === void 0 ? null : _ref2$data, _ref2$config = _ref2.config, config = _ref2$config === void 0 ? null : _ref2$config;
1181 response = null;
1182 requestConfig = config || {};
1183 key = type === 'get' || type === 'head' ? 'params' : 'data';
1184 requestConfig = _extends({}, requestConfig, (_extends2 = {
1185 url: url,
1186 method: type
1187 }, _extends2[key] = data || {}, _extends2));
1188 _context.t0 = this.strategy;
1189 _context.next = _context.t0 === 'silent' ? 8 : _context.t0 === 'reject' ? 22 : _context.t0 === 'throwError' ? 33 : 33;
1190 break;
1191
1192 case 8:
1193 _context.prev = 8;
1194 _context.next = 11;
1195 return this.requestInstance.request(requestConfig);
1196
1197 case 11:
1198 response = _context.sent;
1199 _context.next = 21;
1200 break;
1201
1202 case 14:
1203 _context.prev = 14;
1204 _context.t1 = _context["catch"](8);
1205 this.processRequestError(_context.t1);
1206 _context.next = 19;
1207 return new Promise(function () {
1208 return null;
1209 });
1210
1211 case 19:
1212 response = _context.sent;
1213 return _context.abrupt("return", response);
1214
1215 case 21:
1216 return _context.abrupt("break", 36);
1217
1218 case 22:
1219 _context.prev = 22;
1220 _context.next = 25;
1221 return this.requestInstance.request(requestConfig);
1222
1223 case 25:
1224 response = _context.sent;
1225 _context.next = 32;
1226 break;
1227
1228 case 28:
1229 _context.prev = 28;
1230 _context.t2 = _context["catch"](22);
1231 this.processRequestError(_context.t2);
1232 return _context.abrupt("return", Promise.reject(_context.t2));
1233
1234 case 32:
1235 return _context.abrupt("break", 36);
1236
1237 case 33:
1238 _context.next = 35;
1239 return this.requestInstance.request(requestConfig);
1240
1241 case 35:
1242 response = _context.sent;
1243
1244 case 36:
1245 return _context.abrupt("return", this.processResponseData(response));
1246
1247 case 37:
1248 case "end":
1249 return _context.stop();
1250 }
1251 }
1252 }, _callee, this, [[8, 14], [22, 28]]);
1253 }));
1254
1255 function handleRequest(_x) {
1256 return _handleRequest.apply(this, arguments);
1257 }
1258
1259 return handleRequest;
1260 }() // eslint-disable-next-line class-methods-use-this
1261 ;
1262
1263 _proto.processResponseData = function processResponseData(response) {
1264 if (response.data) {
1265 if (!this.flattenResponse) {
1266 return response;
1267 } // Special case of data property within Axios data object
1268 // This is in fact a proper response but we may want to flatten it
1269 // To ease developers' lives when obtaining the response
1270
1271
1272 if (typeof response.data === 'object' && response.data.data && Object.keys(response.data).length === 1) {
1273 return response.data.data;
1274 }
1275
1276 return response.data;
1277 }
1278
1279 return null;
1280 };
1281
1282 return HttpRequestHandler;
1283}();
1284
1285exports.HttpRequestHandler = /*#__PURE__*/tslib.__decorate([/*#__PURE__*/catchDecorator.CatchAll(function (err, ctx) {
1286 return ctx.processRequestError(err);
1287})], exports.HttpRequestHandler);
1288
1289/**
1290 * Handles dispatching of API requests
1291 */
1292
1293exports.ApiHandler = /*#__PURE__*/function () {
1294 /**
1295 * Creates an instance of API Handler
1296 *
1297 * @param {string} apiUrl Base URL for all API calls
1298 * @param {number} timeout Request timeout
1299 * @param {string} strategy Error Handling Strategy
1300 * @param {string} flattenResponse Whether to flatten response "data" object within "data" one
1301 * @param {*} logger Instance of Logger Class
1302 * @param {*} httpRequestErrorService Instance of Error Service Class
1303 *
1304 * @memberof ApiHandler
1305 */
1306 function ApiHandler(_ref) {
1307 var apiUrl = _ref.apiUrl,
1308 apiEndpoints = _ref.apiEndpoints,
1309 _ref$timeout = _ref.timeout,
1310 timeout = _ref$timeout === void 0 ? null : _ref$timeout,
1311 _ref$strategy = _ref.strategy,
1312 strategy = _ref$strategy === void 0 ? null : _ref$strategy,
1313 _ref$flattenResponse = _ref.flattenResponse,
1314 flattenResponse = _ref$flattenResponse === void 0 ? null : _ref$flattenResponse,
1315 _ref$logger = _ref.logger,
1316 logger = _ref$logger === void 0 ? null : _ref$logger,
1317 _ref$httpRequestError = _ref.httpRequestErrorService,
1318 httpRequestErrorService = _ref$httpRequestError === void 0 ? null : _ref$httpRequestError,
1319 config = _objectWithoutPropertiesLoose(_ref, ["apiUrl", "apiEndpoints", "timeout", "strategy", "flattenResponse", "logger", "httpRequestErrorService"]);
1320
1321 /**
1322 * Api Url
1323 *
1324 * @memberof ApiHandler
1325 */
1326 this.apiUrl = '';
1327 this.apiUrl = apiUrl;
1328 this.apiEndpoints = apiEndpoints;
1329 this.logger = logger;
1330 this.httpRequestHandler = new exports.HttpRequestHandler(_extends({}, config, {
1331 baseURL: this.apiUrl,
1332 timeout: timeout,
1333 strategy: strategy,
1334 flattenResponse: flattenResponse,
1335 logger: logger,
1336 httpRequestErrorService: httpRequestErrorService
1337 }));
1338 }
1339 /**
1340 * Get Provider Instance
1341 *
1342 * @returns {AxiosInstance} Provider's instance
1343 * @memberof ApiHandler
1344 */
1345
1346
1347 var _proto = ApiHandler.prototype;
1348
1349 _proto.getInstance = function getInstance() {
1350 return this.httpRequestHandler.getInstance();
1351 }
1352 /**
1353 * Maps all API requests
1354 *
1355 * @param {*} prop Caller
1356 * @returns {Function} Tailored request function
1357 * @memberof ApiHandler
1358 */
1359 ;
1360
1361 _proto.__get = function __get(prop) {
1362 if (prop in this) {
1363 return this[prop];
1364 } // Prevent handler from running for non-existent endpoints
1365
1366
1367 if (!this.apiEndpoints[prop]) {
1368 return this.handleNonImplemented.bind(this, prop);
1369 }
1370
1371 return this.handleRequest.bind(this, prop);
1372 }
1373 /**
1374 * Handle Single API Request
1375 *
1376 * @param {*} args Arguments
1377 * @returns {Promise} Resolvable API provider promise
1378 * @memberof ApiHandler
1379 */
1380 ;
1381
1382 _proto.handleRequest =
1383 /*#__PURE__*/
1384 function () {
1385 var _handleRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1386 var prop,
1387 api,
1388 queryParams,
1389 uriParams,
1390 requestConfig,
1391 uri,
1392 requestData,
1393 responseData,
1394 _args = arguments;
1395 return runtime_1.wrap(function _callee$(_context) {
1396 while (1) {
1397 switch (_context.prev = _context.next) {
1398 case 0:
1399 prop = _args.length <= 0 ? undefined : _args[0];
1400 api = this.apiEndpoints[prop];
1401 queryParams = (_args.length <= 1 ? undefined : _args[1]) || {};
1402 uriParams = (_args.length <= 2 ? undefined : _args[2]) || {};
1403 requestConfig = (_args.length <= 3 ? undefined : _args[3]) || {};
1404 uri = api.url.replace(/:[a-z]+/ig, function (str) {
1405 return uriParams[str.substr(1)] ? uriParams[str.substr(1)] : str;
1406 });
1407 requestData = _extends({}, queryParams);
1408 responseData = null;
1409 _context.next = 10;
1410 return this.httpRequestHandler[api.method](uri, requestData, requestConfig);
1411
1412 case 10:
1413 responseData = _context.sent;
1414 return _context.abrupt("return", responseData);
1415
1416 case 12:
1417 case "end":
1418 return _context.stop();
1419 }
1420 }
1421 }, _callee, this);
1422 }));
1423
1424 function handleRequest() {
1425 return _handleRequest.apply(this, arguments);
1426 }
1427
1428 return handleRequest;
1429 }()
1430 /**
1431 * Triggered when trying to use non-existent endpoints
1432 * @param prop Method Name
1433 * @returns {Promise}
1434 * @memberof ApiHandler
1435 */
1436 ;
1437
1438 _proto.handleNonImplemented = function handleNonImplemented(prop) {
1439 if (this.logger && this.logger.log) {
1440 this.logger.log(prop + " endpoint not implemented.");
1441 }
1442
1443 return Promise.resolve(null);
1444 };
1445
1446 return ApiHandler;
1447}();
1448
1449exports.ApiHandler = /*#__PURE__*/tslib.__decorate([jsMagic.applyMagic], exports.ApiHandler);
1450var createApiFetcher = function createApiFetcher(options) {
1451 return new exports.ApiHandler(options);
1452};
1453
1454exports.HttpRequestErrorHandler = HttpRequestErrorHandler;
1455exports.createApiFetcher = createApiFetcher;
1456//# sourceMappingURL=axios-multi-api.cjs.development.js.map