@nextgis/ngw-connector 1.16.8 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,94 +1,4 @@
1
- /** Bundle of @nextgis/ngw-connector; version: 1.16.8; author: NextGIS */
2
- /******************************************************************************
3
- Copyright (c) Microsoft Corporation.
4
-
5
- Permission to use, copy, modify, and/or distribute this software for any
6
- purpose with or without fee is hereby granted.
7
-
8
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
9
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
11
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
- PERFORMANCE OF THIS SOFTWARE.
15
- ***************************************************************************** */
16
- /* global Reflect, Promise */
17
-
18
- var extendStatics = function(d, b) {
19
- extendStatics = Object.setPrototypeOf ||
20
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
22
- return extendStatics(d, b);
23
- };
24
-
25
- function __extends(d, b) {
26
- if (typeof b !== "function" && b !== null)
27
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
28
- extendStatics(d, b);
29
- function __() { this.constructor = d; }
30
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31
- }
32
-
33
- var __assign = function() {
34
- __assign = Object.assign || function __assign(t) {
35
- for (var s, i = 1, n = arguments.length; i < n; i++) {
36
- s = arguments[i];
37
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
38
- }
39
- return t;
40
- };
41
- return __assign.apply(this, arguments);
42
- };
43
-
44
- function __awaiter(thisArg, _arguments, P, generator) {
45
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
46
- return new (P || (P = Promise))(function (resolve, reject) {
47
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
48
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
49
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
50
- step((generator = generator.apply(thisArg, _arguments || [])).next());
51
- });
52
- }
53
-
54
- function __generator(thisArg, body) {
55
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
56
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
57
- function verb(n) { return function (v) { return step([n, v]); }; }
58
- function step(op) {
59
- if (f) throw new TypeError("Generator is already executing.");
60
- while (_) try {
61
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
62
- if (y = 0, t) op = [op[0] & 2, t.value];
63
- switch (op[0]) {
64
- case 0: case 1: t = op; break;
65
- case 4: _.label++; return { value: op[1], done: false };
66
- case 5: _.label++; y = op[1]; op = [0]; continue;
67
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
68
- default:
69
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
70
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
71
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
72
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
73
- if (t[2]) _.ops.pop();
74
- _.trys.pop(); continue;
75
- }
76
- op = body.call(thisArg, _);
77
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
78
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
79
- }
80
- }
81
-
82
- function __spreadArray(to, from, pack) {
83
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
84
- if (ar || !(i in from)) {
85
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
86
- ar[i] = from[i];
87
- }
88
- }
89
- return to.concat(ar || Array.prototype.slice.call(from));
90
- }
91
-
1
+ /** Bundle of @nextgis/ngw-connector; version: 1.17.0; author: NextGIS */
92
2
  var events = {exports: {}};
93
3
 
94
4
  var R = typeof Reflect === 'object' ? Reflect : null;
@@ -565,1686 +475,1605 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
565
475
  }
566
476
  }
567
477
 
568
- var CancelError = /** @class */ (function (_super) {
569
- __extends(CancelError, _super);
570
- function CancelError() {
571
- var _this = _super.call(this) || this;
572
- _this.name = 'CancelError';
573
- Object.setPrototypeOf(_this, CancelError.prototype);
574
- return _this;
575
- }
576
- return CancelError;
577
- }(Error));
578
-
579
- var PromiseControl = /** @class */ (function () {
580
- function PromiseControl(options) {
581
- if (options === void 0) { options = {}; }
582
- this.options = options;
583
- this._promises = new Map();
584
- }
585
- Object.defineProperty(PromiseControl.prototype, "isLoaded", {
586
- get: function () {
587
- return this._promises.size > 0;
588
- },
589
- enumerable: false,
590
- configurable: true
591
- });
592
- PromiseControl.prototype.remove = function (promise) {
593
- if (this._promises.has(promise)) {
594
- this._promises.delete(promise);
595
- this._onStop();
596
- }
597
- };
598
- PromiseControl.prototype.get = function (promise) {
599
- return this._promises.get(promise);
600
- };
601
- PromiseControl.prototype.add = function (promise, name) {
602
- var _this = this;
603
- var key = name ? name : promise;
604
- var exist = this._promises.get(key);
605
- if (this.options.onStart && !this.isLoaded) {
606
- this.options.onStart();
607
- }
608
- if (exist) {
609
- return exist;
610
- }
611
- this._promises.set(key, promise);
612
- promise.finally(function () {
613
- _this.remove(key);
614
- });
615
- return promise;
616
- };
617
- PromiseControl.prototype.abort = function () {
618
- if (this.isLoaded) {
619
- this._promises.forEach(function (x) {
620
- if (x.cancel) {
621
- x.cancel();
622
- }
623
- });
624
- this._promises.clear();
625
- this._onStop();
626
- }
627
- };
628
- PromiseControl.prototype.waitFunc = function (func, name) {
629
- if (name === void 0) { name = ''; }
630
- name = name || func.name;
631
- var exist = this.get(name);
632
- if (exist) {
633
- return exist;
634
- }
635
- return this.add(func(), name);
636
- };
637
- PromiseControl.prototype.WaitForMe = function (name) {
638
- if (name === void 0) { name = ''; }
639
- var get = this.get.bind(this);
640
- var add = this.add.bind(this);
641
- return function (target, key, descriptor) {
642
- var originalMethod = descriptor.value;
643
- name = name || key;
644
- descriptor.value = function () {
645
- var args = [];
646
- for (var _i = 0; _i < arguments.length; _i++) {
647
- args[_i] = arguments[_i];
648
- }
649
- var exist = get(name);
650
- if (exist) {
651
- return exist;
652
- }
653
- var result = add(originalMethod.apply(this, args), name);
654
- return result;
655
- };
656
- return descriptor;
657
- };
658
- };
659
- /** @deprecated use {@link PromiseControl.WaitForMe } instead */
660
- PromiseControl.prototype.GetOrCreateDecorator = function (name) {
661
- if (name === void 0) { name = ''; }
662
- return this.WaitForMe(name);
663
- };
664
- PromiseControl.prototype._onStop = function () {
665
- if (this.options.onStop && !this.isLoaded) {
666
- this.options.onStop();
667
- }
668
- };
669
- return PromiseControl;
670
- }());
671
-
672
- var TimeoutError = /** @class */ (function (_super) {
673
- __extends(TimeoutError, _super);
674
- function TimeoutError() {
675
- var _this = _super.call(this) || this;
676
- _this.name = 'TimeoutError';
677
- Object.setPrototypeOf(_this, TimeoutError.prototype);
678
- return _this;
679
- }
680
- return TimeoutError;
681
- }(Error));
682
-
683
- var handleCallback = function (resolve, reject, callback, r) {
684
- try {
685
- resolve(callback(r));
686
- }
687
- catch (e) {
688
- reject(e);
689
- }
690
- };
691
- var ID$1 = 0;
692
- /**
693
- * Promise that can be canceled
694
- *
695
- * @example
696
- * Catch `CancelError`
697
- * ```javascript
698
- * import CancelablePromise from "@nextgis/cancelable-promise";
699
- *
700
- * const promise = new CancelablePromise((resolve, reject) => {
701
- * setTimeout(() => resolve(), 100);
702
- * }).catch((er) => {
703
- * if (er.name === "CancelError") {
704
- * // handle cancel error
705
- * }
706
- * throw er;
707
- * });
708
- *
709
- * promise.cancel();
710
- * ```
711
- * @example
712
- * Handle `onCancel` callback
713
- * ```javascript
714
- * import CancelablePromise from "@nextgis/cancelable-promise";
715
- *
716
- * const promise = new CancelablePromise((resolve, reject, onCancel) => {
717
- * const xhr = new XMLHttpRequest();
718
- * xhr.open("GET", url, true);
719
- * xhr.onload = () => {
720
- * resolve(xhr.responseText);
721
- * };
722
- * xhr.onerror = (er) => {
723
- * reject(er);
724
- * };
725
- *
726
- * onCancel(() => {
727
- * xhr.abort();
728
- * });
729
- *
730
- * xhr.send();
731
- * });
732
- *
733
- * promise.cancel();
734
- * ```
735
- */
736
- var CancelablePromise$1 = /** @class */ (function () {
737
- function CancelablePromise(executor, timeout) {
738
- var _this = this;
739
- this.id = ID$1++;
740
- this._isCanceled = false;
741
- this._isPending = true;
742
- this._cancelHandlers = [];
743
- this._children = [];
744
- this._cancelPromise = new Promise(function (resolve_, reject_) {
745
- _this._setCanceledCallback = function (er) { return resolve_(er || new CancelError()); };
746
- });
747
- var promises = [
748
- this._cancelPromise,
749
- new Promise(function (resolve, reject) {
750
- var onResolve = function (value) {
751
- if (value instanceof CancelablePromise) {
752
- _this.attach(value);
753
- }
754
- else {
755
- _this._isPending = false;
756
- }
757
- // TODO: fix types, `undefined` not allowed since 19.12.2020
758
- resolve(value);
759
- };
760
- var onReject = function (error) {
761
- _this._isPending = false;
762
- reject(error);
763
- };
764
- var onCancel = function (handler) {
765
- if (!_this._isPending) {
766
- throw new Error('The `onCancel` handler was attached after the promise settled.');
767
- }
768
- _this._cancelHandlers.push(handler);
769
- };
770
- return executor(onResolve, onReject, onCancel);
771
- }),
772
- ];
773
- if (timeout) {
774
- promises.push(new Promise(function (resolve, reject) {
775
- setTimeout(function () {
776
- if (_this._isPending) {
777
- try {
778
- _this.cancel();
779
- }
780
- finally {
781
- reject(new TimeoutError());
782
- }
783
- }
784
- }, timeout);
785
- }));
786
- }
787
- this._promise = Promise.race(promises);
788
- }
789
- CancelablePromise.createControl = function (opt) {
790
- return new PromiseControl(opt);
791
- };
792
- CancelablePromise.resolve = function (value) {
793
- return new CancelablePromise(function (resolve) { return resolve(value); });
794
- };
795
- CancelablePromise.reject = function (value) {
796
- return new CancelablePromise(function (resolve, reject) { return reject(value); });
797
- };
798
- CancelablePromise.all = function (values) {
799
- var _this = this;
800
- return new CancelablePromise(function (resolve, reject) {
801
- Promise.all(values).then(resolve).catch(reject);
802
- }).catch(function (er) {
803
- if (er instanceof _this.CancelError) {
804
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
805
- var v = values_1[_i];
806
- var v_ = v;
807
- if ('cancel' in v_) {
808
- v_.cancel();
809
- }
810
- }
811
- }
812
- throw er;
813
- });
814
- };
815
- CancelablePromise.prototype.attach = function (p) {
816
- if (this._isCanceled) {
817
- p.cancel();
818
- }
819
- else {
820
- this._children.push(p);
821
- }
822
- };
823
- CancelablePromise.prototype.then = function (onfulfilled, onrejected) {
824
- var _this = this;
825
- var p = new CancelablePromise(function (resolve, reject) {
826
- if (_this._promise) {
827
- var reject_1 = function (r) {
828
- if (onrejected) {
829
- handleCallback(resolve, reject, onrejected, r);
830
- }
831
- else {
832
- reject(r);
833
- }
834
- };
835
- _this._promise.then(function (r) {
836
- if (_this._isCanceled) {
837
- reject_1(r);
838
- }
839
- else {
840
- if (onfulfilled) {
841
- handleCallback(resolve, reject, onfulfilled, r);
842
- }
843
- else {
844
- resolve(r);
845
- }
846
- }
847
- }, reject_1);
848
- }
849
- });
850
- p._parentPromise = this;
851
- this._children.push(p);
852
- return p;
853
- };
854
- CancelablePromise.prototype.catch = function (onrejected) {
855
- if (this._isCanceled && onrejected) {
856
- onrejected(new CancelError());
857
- }
858
- return this.then(undefined, onrejected);
859
- };
860
- CancelablePromise.prototype.finally = function (onfinally) {
861
- if (this._promise) {
862
- return this._promise.finally(onfinally);
863
- }
864
- if (this._isCanceled) {
865
- return Promise.reject(new CancelError());
866
- }
867
- return Promise.reject(onfinally);
868
- };
869
- CancelablePromise.prototype.cancel = function () {
870
- // No reason to run cancel action if promise is already complete
871
- if (this._isCanceled || !this._isPending) {
872
- return this;
873
- }
874
- this._isCanceled = true;
875
- var parent = this._getTopParent();
876
- if (parent) {
877
- parent.cancel();
878
- }
879
- if (this._children) {
880
- this._children.forEach(function (x) { return x.cancel(); });
881
- }
882
- if (this._isPending) {
883
- if (this._cancelHandlers.length) {
884
- try {
885
- for (var _i = 0, _a = this._cancelHandlers; _i < _a.length; _i++) {
886
- var handler = _a[_i];
887
- handler();
888
- }
889
- }
890
- catch (error) {
891
- // this._setCanceledCallback(error);
892
- }
893
- }
894
- if (this._setCanceledCallback) {
895
- this._setCanceledCallback();
896
- }
897
- }
898
- this._destroy();
899
- return this;
900
- };
901
- CancelablePromise.prototype._getTopParent = function () {
902
- var parent = this._parentPromise;
903
- var hasParent = !!parent;
904
- while (hasParent) {
905
- if (parent && parent._parentPromise) {
906
- parent = parent._parentPromise;
907
- hasParent = !!parent;
908
- }
909
- else {
910
- hasParent = false;
911
- }
912
- }
913
- return parent;
914
- };
915
- CancelablePromise.prototype._destroy = function () {
916
- this._setCanceledCallback = undefined;
917
- this._cancelPromise = undefined;
918
- this._promise = undefined;
919
- };
920
- CancelablePromise.CancelError = CancelError;
921
- CancelablePromise.TimeoutError = TimeoutError;
922
- CancelablePromise.PromiseControl = PromiseControl;
923
- return CancelablePromise;
924
- }());
478
+ class CancelError extends Error {
479
+ constructor() {
480
+ super();
481
+ this.name = 'CancelError';
482
+ Object.setPrototypeOf(this, CancelError.prototype);
483
+ }
484
+ }
485
+
486
+ class PromiseControl {
487
+ constructor(options = {}) {
488
+ this.options = options;
489
+ this._promises = new Map();
490
+ }
491
+ get isLoaded() {
492
+ return this._promises.size > 0;
493
+ }
494
+ remove(promise) {
495
+ if (this._promises.has(promise)) {
496
+ this._promises.delete(promise);
497
+ this._onStop();
498
+ }
499
+ }
500
+ get(promise) {
501
+ return this._promises.get(promise);
502
+ }
503
+ add(promise, name) {
504
+ const key = name ? name : promise;
505
+ const exist = this._promises.get(key);
506
+ if (this.options.onStart && !this.isLoaded) {
507
+ this.options.onStart();
508
+ }
509
+ if (exist) {
510
+ return exist;
511
+ }
512
+ this._promises.set(key, promise);
513
+ promise.finally(() => {
514
+ this.remove(key);
515
+ });
516
+ return promise;
517
+ }
518
+ abort() {
519
+ if (this.isLoaded) {
520
+ this._promises.forEach((x) => {
521
+ if (x.cancel) {
522
+ x.cancel();
523
+ }
524
+ });
525
+ this._promises.clear();
526
+ this._onStop();
527
+ }
528
+ }
529
+ waitFunc(func, name = '') {
530
+ name = name || func.name;
531
+ const exist = this.get(name);
532
+ if (exist) {
533
+ return exist;
534
+ }
535
+ return this.add(func(), name);
536
+ }
537
+ WaitForMe(name = '') {
538
+ const get = this.get.bind(this);
539
+ const add = this.add.bind(this);
540
+ return function (target, key, descriptor) {
541
+ const originalMethod = descriptor.value;
542
+ name = name || key;
543
+ descriptor.value = function (...args) {
544
+ const exist = get(name);
545
+ if (exist) {
546
+ return exist;
547
+ }
548
+ const result = add(originalMethod.apply(this, args), name);
549
+ return result;
550
+ };
551
+ return descriptor;
552
+ };
553
+ }
554
+ /** @deprecated use {@link PromiseControl.WaitForMe } instead */
555
+ GetOrCreateDecorator(name = '') {
556
+ return this.WaitForMe(name);
557
+ }
558
+ _onStop() {
559
+ if (this.options.onStop && !this.isLoaded) {
560
+ this.options.onStop();
561
+ }
562
+ }
563
+ }
564
+
565
+ class TimeoutError extends Error {
566
+ constructor() {
567
+ super();
568
+ this.name = 'TimeoutError';
569
+ Object.setPrototypeOf(this, TimeoutError.prototype);
570
+ }
571
+ }
572
+
573
+ const handleCallback = (resolve, reject, callback, r) => {
574
+ try {
575
+ resolve(callback(r));
576
+ }
577
+ catch (e) {
578
+ reject(e);
579
+ }
580
+ };
581
+ let ID$1 = 0;
582
+ /**
583
+ * Promise that can be canceled
584
+ *
585
+ * @example
586
+ * Catch `CancelError`
587
+ * ```javascript
588
+ * import CancelablePromise from "@nextgis/cancelable-promise";
589
+ *
590
+ * const promise = new CancelablePromise((resolve, reject) => {
591
+ * setTimeout(() => resolve(), 100);
592
+ * }).catch((er) => {
593
+ * if (er.name === "CancelError") {
594
+ * // handle cancel error
595
+ * }
596
+ * throw er;
597
+ * });
598
+ *
599
+ * promise.cancel();
600
+ * ```
601
+ * @example
602
+ * Handle `onCancel` callback
603
+ * ```javascript
604
+ * import CancelablePromise from "@nextgis/cancelable-promise";
605
+ *
606
+ * const promise = new CancelablePromise((resolve, reject, onCancel) => {
607
+ * const xhr = new XMLHttpRequest();
608
+ * xhr.open("GET", url, true);
609
+ * xhr.onload = () => {
610
+ * resolve(xhr.responseText);
611
+ * };
612
+ * xhr.onerror = (er) => {
613
+ * reject(er);
614
+ * };
615
+ *
616
+ * onCancel(() => {
617
+ * xhr.abort();
618
+ * });
619
+ *
620
+ * xhr.send();
621
+ * });
622
+ *
623
+ * promise.cancel();
624
+ * ```
625
+ */
626
+ class CancelablePromise$1 {
627
+ constructor(executor, timeout) {
628
+ this.id = ID$1++;
629
+ this._isCanceled = false;
630
+ this._isPending = true;
631
+ this._cancelHandlers = [];
632
+ this._children = [];
633
+ this._cancelPromise = new Promise((resolve_, reject_) => {
634
+ this._setCanceledCallback = (er) => resolve_(er || new CancelError());
635
+ });
636
+ const promises = [
637
+ this._cancelPromise,
638
+ new Promise((resolve, reject) => {
639
+ const onResolve = (value) => {
640
+ if (value instanceof CancelablePromise$1) {
641
+ this.attach(value);
642
+ }
643
+ else {
644
+ this._isPending = false;
645
+ }
646
+ // TODO: fix types, `undefined` not allowed since 19.12.2020
647
+ resolve(value);
648
+ };
649
+ const onReject = (error) => {
650
+ this._isPending = false;
651
+ reject(error);
652
+ };
653
+ const onCancel = (handler) => {
654
+ if (!this._isPending) {
655
+ throw new Error('The `onCancel` handler was attached after the promise settled.');
656
+ }
657
+ this._cancelHandlers.push(handler);
658
+ };
659
+ return executor(onResolve, onReject, onCancel);
660
+ }),
661
+ ];
662
+ if (timeout) {
663
+ promises.push(new Promise((resolve, reject) => {
664
+ setTimeout(() => {
665
+ if (this._isPending) {
666
+ try {
667
+ this.cancel();
668
+ }
669
+ finally {
670
+ reject(new TimeoutError());
671
+ }
672
+ }
673
+ }, timeout);
674
+ }));
675
+ }
676
+ this._promise = Promise.race(promises);
677
+ }
678
+ static createControl(opt) {
679
+ return new PromiseControl(opt);
680
+ }
681
+ static resolve(value) {
682
+ return new CancelablePromise$1((resolve) => resolve(value));
683
+ }
684
+ static reject(value) {
685
+ return new CancelablePromise$1((resolve, reject) => reject(value));
686
+ }
687
+ static all(values) {
688
+ return new CancelablePromise$1((resolve, reject) => {
689
+ Promise.all(values).then(resolve).catch(reject);
690
+ }).catch((er) => {
691
+ if (er instanceof this.CancelError) {
692
+ for (const v of values) {
693
+ const v_ = v;
694
+ if ('cancel' in v_) {
695
+ v_.cancel();
696
+ }
697
+ }
698
+ }
699
+ throw er;
700
+ });
701
+ }
702
+ attach(p) {
703
+ if (this._isCanceled) {
704
+ p.cancel();
705
+ }
706
+ else {
707
+ this._children.push(p);
708
+ }
709
+ }
710
+ then(onfulfilled, onrejected) {
711
+ const p = new CancelablePromise$1((resolve, reject) => {
712
+ if (this._promise) {
713
+ const reject_ = (r) => {
714
+ if (onrejected) {
715
+ handleCallback(resolve, reject, onrejected, r);
716
+ }
717
+ else {
718
+ reject(r);
719
+ }
720
+ };
721
+ this._promise.then((r) => {
722
+ if (this._isCanceled) {
723
+ reject_(r);
724
+ }
725
+ else {
726
+ if (onfulfilled) {
727
+ handleCallback(resolve, reject, onfulfilled, r);
728
+ }
729
+ else {
730
+ resolve(r);
731
+ }
732
+ }
733
+ }, reject_);
734
+ }
735
+ });
736
+ p._parentPromise = this;
737
+ this._children.push(p);
738
+ return p;
739
+ }
740
+ catch(onrejected) {
741
+ if (this._isCanceled && onrejected) {
742
+ onrejected(new CancelError());
743
+ }
744
+ return this.then(undefined, onrejected);
745
+ }
746
+ finally(onfinally) {
747
+ if (this._promise) {
748
+ return this._promise.finally(onfinally);
749
+ }
750
+ if (this._isCanceled) {
751
+ return Promise.reject(new CancelError());
752
+ }
753
+ return Promise.reject(onfinally);
754
+ }
755
+ cancel() {
756
+ // No reason to run cancel action if promise is already complete
757
+ if (this._isCanceled || !this._isPending) {
758
+ return this;
759
+ }
760
+ this._isCanceled = true;
761
+ const parent = this._getTopParent();
762
+ if (parent) {
763
+ parent.cancel();
764
+ }
765
+ if (this._children) {
766
+ this._children.forEach((x) => x.cancel());
767
+ }
768
+ if (this._isPending) {
769
+ if (this._cancelHandlers.length) {
770
+ try {
771
+ for (const handler of this._cancelHandlers) {
772
+ handler();
773
+ }
774
+ }
775
+ catch (error) {
776
+ // this._setCanceledCallback(error);
777
+ }
778
+ }
779
+ if (this._setCanceledCallback) {
780
+ this._setCanceledCallback();
781
+ }
782
+ }
783
+ this._destroy();
784
+ return this;
785
+ }
786
+ _getTopParent() {
787
+ let parent = this._parentPromise;
788
+ let hasParent = !!parent;
789
+ while (hasParent) {
790
+ if (parent && parent._parentPromise) {
791
+ parent = parent._parentPromise;
792
+ hasParent = !!parent;
793
+ }
794
+ else {
795
+ hasParent = false;
796
+ }
797
+ }
798
+ return parent;
799
+ }
800
+ _destroy() {
801
+ this._setCanceledCallback = undefined;
802
+ this._cancelPromise = undefined;
803
+ this._promise = undefined;
804
+ }
805
+ }
806
+ CancelablePromise$1.CancelError = CancelError;
807
+ CancelablePromise$1.TimeoutError = TimeoutError;
808
+ CancelablePromise$1.PromiseControl = PromiseControl;
925
809
  Object.setPrototypeOf(CancelablePromise$1.prototype, Promise.prototype);
926
810
 
927
- /**
928
- * A promise you can stop
929
- *
930
- * @packageDocumentation
931
- * @module cancelable-promise
932
- */
811
+ /**
812
+ * A promise you can stop
813
+ *
814
+ * @packageDocumentation
815
+ * @module cancelable-promise
816
+ */
933
817
  var CancelablePromise = CancelablePromise$1;
934
818
 
935
- /**
936
- * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
937
- *
938
- * @param val - The object.
939
- * @returns Returns true if the object is defined, returns false otherwise.
940
- *
941
- * @example
942
- * ```javascript
943
- * if (defined(positions)) {
944
- * doSomething();
945
- * } else {
946
- * doSomethingElse();
947
- * }
948
- * ```
949
- */
950
- function defined(val) {
951
- return val !== undefined && val !== null;
952
- }
953
- /**
954
- * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
955
- *
956
- * @param val - The object.
957
- * @returns Returns true if the object is defined and not empty string, returns false otherwise.
958
- *
959
- * @example
960
- * ```javascript
961
- * full('foo') // true
962
- * full('') // false
963
- * full(undefined) // false
964
- * full(0) // true
965
- * ```
966
- */
967
- function full(val) {
968
- return typeof val === 'string' ? !!val : defined(val);
819
+ /**
820
+ * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
821
+ *
822
+ * @param val - The object.
823
+ * @returns Returns true if the object is defined, returns false otherwise.
824
+ *
825
+ * @example
826
+ * ```javascript
827
+ * if (defined(positions)) {
828
+ * doSomething();
829
+ * } else {
830
+ * doSomethingElse();
831
+ * }
832
+ * ```
833
+ */
834
+ function defined(val) {
835
+ return val !== undefined && val !== null;
836
+ }
837
+ /**
838
+ * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
839
+ *
840
+ * @param val - The object.
841
+ * @returns Returns true if the object is defined and not empty string, returns false otherwise.
842
+ *
843
+ * @example
844
+ * ```javascript
845
+ * full('foo') // true
846
+ * full('') // false
847
+ * full(undefined) // false
848
+ * full(0) // true
849
+ * ```
850
+ */
851
+ function full(val) {
852
+ return typeof val === 'string' ? !!val : defined(val);
969
853
  }
970
854
 
971
- function isEqual(a, b, o, p) {
972
- if (a instanceof Array) {
973
- if (!(b instanceof Array))
974
- return false;
975
- //if (compareObjects(oVal, pVal === false) return false
976
- //would work, too, and perhaps is a better fit, still, this is easy, too
977
- return b.sort().join('') === a.sort().join('');
978
- }
979
- else if (a instanceof Date) {
980
- if (!(b instanceof Date))
981
- return false;
982
- return '' + a === '' + b;
983
- }
984
- else if (a instanceof Function) {
985
- if (!(b instanceof Function))
986
- return false;
987
- //ignore functions, or check them regardless?
988
- }
989
- else if (a instanceof Object) {
990
- if (!(b instanceof Object))
991
- return false;
992
- if (a === o) {
993
- return b === p;
994
- }
995
- else {
996
- return objectDeepEqual(a, b);
997
- }
998
- }
999
- return a === b;
1000
- }
1001
- // based on https://stackoverflow.com/a/13143059
1002
- function objectDeepEqual(o, p) {
1003
- var keysO = Object.keys(o).sort();
1004
- var keysP = Object.keys(p).sort();
1005
- if (keysO.length !== keysP.length)
1006
- return false;
1007
- if (keysO.join('') !== keysP.join(''))
1008
- return false;
1009
- for (var i = 0; i < keysO.length; i++) {
1010
- var oVal = o[keysO[i]];
1011
- var pVal = p[keysP[i]];
1012
- if (!isEqual(oVal, pVal, o, p)) {
1013
- return false;
1014
- }
1015
- }
1016
- return true;
855
+ function isEqual(a, b, o, p) {
856
+ if (a instanceof Array) {
857
+ if (!(b instanceof Array))
858
+ return false;
859
+ //if (compareObjects(oVal, pVal === false) return false
860
+ //would work, too, and perhaps is a better fit, still, this is easy, too
861
+ return b.sort().join('') === a.sort().join('');
862
+ }
863
+ else if (a instanceof Date) {
864
+ if (!(b instanceof Date))
865
+ return false;
866
+ return '' + a === '' + b;
867
+ }
868
+ else if (a instanceof Function) {
869
+ if (!(b instanceof Function))
870
+ return false;
871
+ //ignore functions, or check them regardless?
872
+ }
873
+ else if (a instanceof Object) {
874
+ if (!(b instanceof Object))
875
+ return false;
876
+ if (a === o) {
877
+ return b === p;
878
+ }
879
+ else {
880
+ return objectDeepEqual(a, b);
881
+ }
882
+ }
883
+ return a === b;
884
+ }
885
+ // based on https://stackoverflow.com/a/13143059
886
+ function objectDeepEqual(o, p) {
887
+ const keysO = Object.keys(o).sort();
888
+ const keysP = Object.keys(p).sort();
889
+ if (keysO.length !== keysP.length)
890
+ return false;
891
+ if (keysO.join('') !== keysP.join(''))
892
+ return false;
893
+ for (let i = 0; i < keysO.length; i++) {
894
+ const oVal = o[keysO[i]];
895
+ const pVal = p[keysP[i]];
896
+ if (!isEqual(oVal, pVal, o, p)) {
897
+ return false;
898
+ }
899
+ }
900
+ return true;
1017
901
  }
1018
902
 
1019
- function objectRemoveEmpty(obj) {
1020
- var newObj = {};
1021
- Object.keys(obj).forEach(function (key) {
1022
- if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
1023
- newObj[key] = objectRemoveEmpty(obj[key]);
1024
- }
1025
- else if (obj[key] !== undefined) {
1026
- newObj[key] = obj[key];
1027
- }
1028
- });
1029
- return newObj;
903
+ function objectRemoveEmpty(obj) {
904
+ const newObj = {};
905
+ Object.keys(obj).forEach((key) => {
906
+ if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
907
+ newObj[key] = objectRemoveEmpty(obj[key]);
908
+ }
909
+ else if (obj[key] !== undefined) {
910
+ newObj[key] = obj[key];
911
+ }
912
+ });
913
+ return newObj;
1030
914
  }
1031
915
 
1032
- function fixUrlStr(url) {
1033
- // remove double slash
1034
- return url.replace(/([^:]\/)\/+/g, '$1');
916
+ function fixUrlStr(url) {
917
+ // remove double slash
918
+ return url.replace(/([^:]\/)\/+/g, '$1');
1035
919
  }
1036
920
 
1037
- /**
1038
- * @example
1039
- * ```javascript
1040
- * const cache1 = new Cache();
1041
- * cache1.add('foo', 'value');
1042
- *
1043
- * const cache2 = new Cache();
1044
- * cache2.match('foo'); // value
1045
- *
1046
- * const cache3 = new Cache({ namespace: 'foo' });
1047
- * cache3.match('foo'); // undefined
1048
- * ```
1049
- *
1050
- * @example
1051
- * ```javascript
1052
- * let COUNTER = 0;
1053
- * const createPromise = () => new Promise((res) => {
1054
- * COUNTER++
1055
- * setTimeout(() => res('Ok'), 300)
1056
- * });
1057
- *
1058
- * const cache = new Cache();
1059
- * for (let i = 0; i < 10; i++) {
1060
- * cache.add('foo', createPromise).then((data) => {
1061
- * console.log(data); // 'Ok'
1062
- * });
1063
- * }
1064
- * console.log(COUNTER); // 1
1065
- * ```
1066
- */
1067
- var Cache$1 = /** @class */ (function () {
1068
- function Cache(options) {
1069
- if (options === void 0) { options = {}; }
1070
- var _a;
1071
- this.cache = [];
1072
- var namespace = (_a = options.namespace) !== null && _a !== void 0 ? _a : 'default';
1073
- if (Cache.instance[namespace]) {
1074
- return Cache.instance[namespace];
1075
- }
1076
- Cache.instance[namespace] = this;
1077
- return this;
1078
- }
1079
- Cache.prototype.clean = function () {
1080
- this.cache.length = 0;
1081
- };
1082
- Cache.prototype.all = function () {
1083
- return this.cache;
1084
- };
1085
- /**
1086
- * Caching only a non-empty value.
1087
- *
1088
- * Useful for get or create strategy
1089
- * @example
1090
- * ```javascript
1091
- * const cache = new Cache();
1092
- * const getItemFunc = () => fetch(url).then((data) => {
1093
- * return data.json(); // undefined
1094
- * });
1095
- * const item = await cache.addFull('foo', getItemFunc);
1096
- * if (!item) {
1097
- * await createItem(); // 'New item'
1098
- * }
1099
- *
1100
- * // somewhere else in the code
1101
- * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
1102
- * console.log(resp); // 'New item'
1103
- * })
1104
- *
1105
- * ```
1106
- */
1107
- Cache.prototype.addFull = function (key, valueToSet, props) {
1108
- return this.add(key, valueToSet, props, true);
1109
- };
1110
- Cache.prototype.add = function (key, valueToSet, props, onlyFull) {
1111
- var _this = this;
1112
- var exist = this._find(key, props);
1113
- if (!exist) {
1114
- var value = void 0;
1115
- if (valueToSet instanceof Function) {
1116
- value = valueToSet();
1117
- }
1118
- else {
1119
- value = valueToSet;
1120
- }
1121
- var props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
1122
- var cacheItem = {
1123
- key: key,
1124
- value: value,
1125
- props: props_,
1126
- // TODO: remove backward compatibility use only props
1127
- options: props_,
1128
- };
1129
- if (onlyFull && !full(value)) {
1130
- return value;
1131
- }
1132
- this.cache.push(cacheItem);
1133
- if (value instanceof Promise) {
1134
- value.catch(function (er) {
1135
- _this.delete(key, props);
1136
- throw er;
1137
- });
1138
- if (onlyFull) {
1139
- value.then(function (x) {
1140
- if (!full(x)) {
1141
- _this.delete(key, props);
1142
- }
1143
- return x;
1144
- });
1145
- }
1146
- return value;
1147
- }
1148
- return value;
1149
- }
1150
- else {
1151
- return exist.value;
1152
- }
1153
- };
1154
- Cache.prototype.match = function (key, props) {
1155
- var cacheRecord = this._find(key, props);
1156
- if (cacheRecord) {
1157
- return cacheRecord.value;
1158
- }
1159
- };
1160
- Cache.prototype.matchAll = function (key, props) {
1161
- var _this = this;
1162
- if (key) {
1163
- return this.cache
1164
- .filter(function (x) { return _this._filter(x, key, props); })
1165
- .map(function (x) { return x.value; });
1166
- }
1167
- return this.cache.map(function (x) { return x.value; });
1168
- };
1169
- Cache.prototype.delete = function (keyOrItem, props) {
1170
- var _this = this;
1171
- var exist = [];
1172
- if (typeof keyOrItem === 'string') {
1173
- exist = this.cache.filter(function (x) { return _this._filter(x, keyOrItem, props); });
1174
- }
1175
- else {
1176
- exist.push(keyOrItem);
1177
- }
1178
- for (var _i = 0, exist_1 = exist; _i < exist_1.length; _i++) {
1179
- var e = exist_1[_i];
1180
- var index = this.cache.indexOf(e);
1181
- this.cache.splice(index, 1);
1182
- }
1183
- };
1184
- Cache.prototype._find = function (key, props) {
1185
- var _this = this;
1186
- return this.cache.find(function (x) { return _this._filter(x, key, props); });
1187
- };
1188
- Cache.prototype._filter = function (item, key, props) {
1189
- if (item.key === key) {
1190
- if (props) {
1191
- // TODO: remove backward compatibility
1192
- var itemProps = item.props || item.options;
1193
- return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
1194
- }
1195
- return true;
1196
- }
1197
- return false;
1198
- };
1199
- Cache.instance = {};
1200
- return Cache;
1201
- }());
1202
-
1203
- /**
1204
- * Caching for asynchronous functions
1205
- *
1206
- * @packageDocumentation
1207
- * @module cache
1208
- */
921
+ /**
922
+ * @example
923
+ * ```javascript
924
+ * const cache1 = new Cache();
925
+ * cache1.add('foo', 'value');
926
+ *
927
+ * const cache2 = new Cache();
928
+ * cache2.match('foo'); // value
929
+ *
930
+ * const cache3 = new Cache({ namespace: 'foo' });
931
+ * cache3.match('foo'); // undefined
932
+ * ```
933
+ *
934
+ * @example
935
+ * ```javascript
936
+ * let COUNTER = 0;
937
+ * const createPromise = () => new Promise((res) => {
938
+ * COUNTER++
939
+ * setTimeout(() => res('Ok'), 300)
940
+ * });
941
+ *
942
+ * const cache = new Cache();
943
+ * for (let i = 0; i < 10; i++) {
944
+ * cache.add('foo', createPromise).then((data) => {
945
+ * console.log(data); // 'Ok'
946
+ * });
947
+ * }
948
+ * console.log(COUNTER); // 1
949
+ * ```
950
+ */
951
+ class Cache$1 {
952
+ constructor(options = {}) {
953
+ var _a;
954
+ this.cache = [];
955
+ const namespace = (_a = options.namespace) !== null && _a !== void 0 ? _a : 'default';
956
+ if (Cache$1.instance[namespace]) {
957
+ return Cache$1.instance[namespace];
958
+ }
959
+ Cache$1.instance[namespace] = this;
960
+ return this;
961
+ }
962
+ clean() {
963
+ this.cache.length = 0;
964
+ }
965
+ all() {
966
+ return this.cache;
967
+ }
968
+ /**
969
+ * Caching only a non-empty value.
970
+ *
971
+ * Useful for get or create strategy
972
+ * @example
973
+ * ```javascript
974
+ * const cache = new Cache();
975
+ * const getItemFunc = () => fetch(url).then((data) => {
976
+ * return data.json(); // undefined
977
+ * });
978
+ * const item = await cache.addFull('foo', getItemFunc);
979
+ * if (!item) {
980
+ * await createItem(); // 'New item'
981
+ * }
982
+ *
983
+ * // somewhere else in the code
984
+ * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
985
+ * console.log(resp); // 'New item'
986
+ * })
987
+ *
988
+ * ```
989
+ */
990
+ addFull(key, valueToSet, props) {
991
+ return this.add(key, valueToSet, props, true);
992
+ }
993
+ add(key, valueToSet, props, onlyFull) {
994
+ const exist = this._find(key, props);
995
+ if (!exist) {
996
+ let value;
997
+ if (valueToSet instanceof Function) {
998
+ value = valueToSet();
999
+ }
1000
+ else {
1001
+ value = valueToSet;
1002
+ }
1003
+ const props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
1004
+ const cacheItem = {
1005
+ key,
1006
+ value,
1007
+ props: props_,
1008
+ // TODO: remove backward compatibility use only props
1009
+ options: props_,
1010
+ };
1011
+ if (onlyFull && !full(value)) {
1012
+ return value;
1013
+ }
1014
+ this.cache.push(cacheItem);
1015
+ if (value instanceof Promise) {
1016
+ value.catch((er) => {
1017
+ this.delete(key, props);
1018
+ throw er;
1019
+ });
1020
+ if (onlyFull) {
1021
+ value.then((x) => {
1022
+ if (!full(x)) {
1023
+ this.delete(key, props);
1024
+ }
1025
+ return x;
1026
+ });
1027
+ }
1028
+ return value;
1029
+ }
1030
+ return value;
1031
+ }
1032
+ else {
1033
+ return exist.value;
1034
+ }
1035
+ }
1036
+ match(key, props) {
1037
+ const cacheRecord = this._find(key, props);
1038
+ if (cacheRecord) {
1039
+ return cacheRecord.value;
1040
+ }
1041
+ }
1042
+ matchAll(key, props) {
1043
+ if (key) {
1044
+ return this.cache
1045
+ .filter((x) => this._filter(x, key, props))
1046
+ .map((x) => x.value);
1047
+ }
1048
+ return this.cache.map((x) => x.value);
1049
+ }
1050
+ delete(keyOrItem, props) {
1051
+ let exist = [];
1052
+ if (typeof keyOrItem === 'string') {
1053
+ exist = this.cache.filter((x) => this._filter(x, keyOrItem, props));
1054
+ }
1055
+ else {
1056
+ exist.push(keyOrItem);
1057
+ }
1058
+ for (const e of exist) {
1059
+ const index = this.cache.indexOf(e);
1060
+ this.cache.splice(index, 1);
1061
+ }
1062
+ }
1063
+ _find(key, props) {
1064
+ return this.cache.find((x) => this._filter(x, key, props));
1065
+ }
1066
+ _filter(item, key, props) {
1067
+ if (item.key === key) {
1068
+ if (props) {
1069
+ // TODO: remove backward compatibility
1070
+ const itemProps = item.props || item.options;
1071
+ return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
1072
+ }
1073
+ return true;
1074
+ }
1075
+ return false;
1076
+ }
1077
+ }
1078
+ Cache$1.instance = {};
1079
+
1080
+ /**
1081
+ * Caching for asynchronous functions
1082
+ *
1083
+ * @packageDocumentation
1084
+ * @module cache
1085
+ */
1209
1086
  var Cache = Cache$1;
1210
1087
 
1211
- /**
1212
- * Thrown when...
1213
- */
1214
- var NetworkError = /** @class */ (function (_super) {
1215
- __extends(NetworkError, _super);
1216
- function NetworkError(url) {
1217
- var _this = _super.call(this) || this;
1218
- _this.name = 'NetworkError';
1219
- Object.setPrototypeOf(_this, NetworkError.prototype);
1220
- _this.message = "Unable to request ".concat(url, ".\n Possibly invalid NGW URL entered or CORS not configured to get request from ").concat(location.origin); // /control-panel/cors
1221
- return _this;
1222
- }
1223
- return NetworkError;
1224
- }(Error));
1225
-
1226
- /**
1227
- * Thrown when...
1228
- */
1229
- var NgwError = /** @class */ (function (_super) {
1230
- __extends(NgwError, _super);
1231
- function NgwError(er) {
1232
- var _this = _super.call(this) || this;
1233
- _this.name = 'NgwError';
1234
- Object.assign(_this, er);
1235
- Object.setPrototypeOf(_this, NgwError.prototype);
1236
- return _this;
1237
- }
1238
- return NgwError;
1239
- }(Error));
1240
-
1241
- function isObject(val) {
1242
- return Object.prototype.toString.call(val) === '[object Object]';
1088
+ /**
1089
+ * Thrown when...
1090
+ */
1091
+ class NetworkError extends Error {
1092
+ constructor(url) {
1093
+ super();
1094
+ this.name = 'NetworkError';
1095
+ Object.setPrototypeOf(this, NetworkError.prototype);
1096
+ this.message = `Unable to request ${url}.
1097
+ Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`; // /control-panel/cors
1098
+ }
1099
+ }
1100
+
1101
+ /**
1102
+ * Thrown when...
1103
+ */
1104
+ class NgwError extends Error {
1105
+ constructor(er) {
1106
+ super();
1107
+ this.name = 'NgwError';
1108
+ Object.assign(this, er);
1109
+ Object.setPrototypeOf(this, NgwError.prototype);
1110
+ }
1111
+ }
1112
+
1113
+ function isObject(val) {
1114
+ return Object.prototype.toString.call(val) === '[object Object]';
1115
+ }
1116
+
1117
+ let loadData;
1118
+ // @ts-ignore
1119
+ {
1120
+ loadData = (url, callback, options = {}, error, onCancel) => {
1121
+ options.method = options.method || 'GET';
1122
+ const xhr = new XMLHttpRequest();
1123
+ xhr.open(options.method || 'GET', url, true); // true for asynchronous
1124
+ if (options.responseType === 'blob') {
1125
+ xhr.responseType = options.responseType;
1126
+ }
1127
+ const getResponseText = () => {
1128
+ try {
1129
+ return JSON.parse(xhr.responseText);
1130
+ }
1131
+ catch (er) {
1132
+ return xhr.responseText;
1133
+ }
1134
+ };
1135
+ const processingResponse = (forError = false) => {
1136
+ const cb = forError ? error : callback;
1137
+ if (options.responseType === 'blob') {
1138
+ cb(xhr.response);
1139
+ }
1140
+ else {
1141
+ if (xhr.responseText) {
1142
+ cb(getResponseText());
1143
+ }
1144
+ else {
1145
+ error({ message: '' });
1146
+ }
1147
+ }
1148
+ };
1149
+ xhr.onload = () => {
1150
+ if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1151
+ error(new NgwError(getResponseText()));
1152
+ }
1153
+ processingResponse();
1154
+ };
1155
+ // xhr.onreadystatechange = () => {
1156
+ // if (
1157
+ // (xhr.readyState === 4 && xhr.status === 200) ||
1158
+ // (xhr.readyState === 3 && xhr.status === 201)
1159
+ // ) {
1160
+ // processingResponse();
1161
+ // } else if (xhr.readyState === 3 && xhr.status === 400) {
1162
+ // processingResponse();
1163
+ // } else if (xhr.readyState === 4 && xhr.status === 500) {
1164
+ // processingResponse();
1165
+ // } else if (xhr.readyState === 4 && xhr.status === 401) {
1166
+ // error(xhr.statusText);
1167
+ // } else if (xhr.readyState === 4) {
1168
+ // error('request error');
1169
+ // }
1170
+ // };
1171
+ xhr.onerror = (er) => {
1172
+ if (xhr.status === 0) {
1173
+ error(new NetworkError(url));
1174
+ }
1175
+ else {
1176
+ error(er);
1177
+ }
1178
+ };
1179
+ xhr.upload.onprogress = function (e) {
1180
+ if (e.lengthComputable) {
1181
+ const percentComplete = (e.loaded / e.total) * 100;
1182
+ if (options.onProgress) {
1183
+ options.onProgress(percentComplete, e);
1184
+ }
1185
+ // console.log(percentComplete + '% uploaded');
1186
+ }
1187
+ };
1188
+ const headers = options.headers;
1189
+ if (headers) {
1190
+ for (const h in headers) {
1191
+ const header = headers[h];
1192
+ if (typeof header === 'string') {
1193
+ xhr.setRequestHeader(h, header);
1194
+ }
1195
+ }
1196
+ }
1197
+ if (options.withCredentials !== undefined) {
1198
+ xhr.withCredentials = options.withCredentials;
1199
+ }
1200
+ let data;
1201
+ if (options.file) {
1202
+ data = new FormData();
1203
+ data.append('file', options.file);
1204
+ if (options.data) {
1205
+ for (const d in options.data) {
1206
+ data.append(d, data[d]);
1207
+ }
1208
+ }
1209
+ }
1210
+ else {
1211
+ data = options.data
1212
+ ? typeof options.data === 'string'
1213
+ ? options.data
1214
+ : JSON.stringify(options.data)
1215
+ : null;
1216
+ }
1217
+ if (onCancel) {
1218
+ onCancel(() => {
1219
+ xhr.abort();
1220
+ });
1221
+ }
1222
+ xhr.send(data);
1223
+ };
1243
1224
  }
1244
1225
 
1245
- var loadData;
1246
- // @ts-ignore
1247
- {
1248
- loadData = function (url, callback, options, error, onCancel) {
1249
- if (options === void 0) { options = {}; }
1250
- options.method = options.method || 'GET';
1251
- var xhr = new XMLHttpRequest();
1252
- xhr.open(options.method || 'GET', url, true); // true for asynchronous
1253
- if (options.responseType === 'blob') {
1254
- xhr.responseType = options.responseType;
1255
- }
1256
- var getResponseText = function () {
1257
- try {
1258
- return JSON.parse(xhr.responseText);
1259
- }
1260
- catch (er) {
1261
- return xhr.responseText;
1262
- }
1263
- };
1264
- var processingResponse = function (forError) {
1265
- if (forError === void 0) { forError = false; }
1266
- var cb = forError ? error : callback;
1267
- if (options.responseType === 'blob') {
1268
- cb(xhr.response);
1269
- }
1270
- else {
1271
- if (xhr.responseText) {
1272
- cb(getResponseText());
1273
- }
1274
- else {
1275
- error({ message: '' });
1276
- }
1277
- }
1278
- };
1279
- xhr.onload = function () {
1280
- if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1281
- error(new NgwError(getResponseText()));
1282
- }
1283
- processingResponse();
1284
- };
1285
- // xhr.onreadystatechange = () => {
1286
- // if (
1287
- // (xhr.readyState === 4 && xhr.status === 200) ||
1288
- // (xhr.readyState === 3 && xhr.status === 201)
1289
- // ) {
1290
- // processingResponse();
1291
- // } else if (xhr.readyState === 3 && xhr.status === 400) {
1292
- // processingResponse();
1293
- // } else if (xhr.readyState === 4 && xhr.status === 500) {
1294
- // processingResponse();
1295
- // } else if (xhr.readyState === 4 && xhr.status === 401) {
1296
- // error(xhr.statusText);
1297
- // } else if (xhr.readyState === 4) {
1298
- // error('request error');
1299
- // }
1300
- // };
1301
- xhr.onerror = function (er) {
1302
- if (xhr.status === 0) {
1303
- error(new NetworkError(url));
1304
- }
1305
- else {
1306
- error(er);
1307
- }
1308
- };
1309
- xhr.upload.onprogress = function (e) {
1310
- if (e.lengthComputable) {
1311
- var percentComplete = (e.loaded / e.total) * 100;
1312
- if (options.onProgress) {
1313
- options.onProgress(percentComplete, e);
1314
- }
1315
- // console.log(percentComplete + '% uploaded');
1316
- }
1317
- };
1318
- var headers = options.headers;
1319
- if (headers) {
1320
- for (var h in headers) {
1321
- var header = headers[h];
1322
- if (typeof header === 'string') {
1323
- xhr.setRequestHeader(h, header);
1324
- }
1325
- }
1326
- }
1327
- if (options.withCredentials !== undefined) {
1328
- xhr.withCredentials = options.withCredentials;
1329
- }
1330
- var data;
1331
- if (options.file) {
1332
- data = new FormData();
1333
- data.append('file', options.file);
1334
- if (options.data) {
1335
- for (var d in options.data) {
1336
- data.append(d, data[d]);
1337
- }
1338
- }
1339
- }
1340
- else {
1341
- data = options.data
1342
- ? typeof options.data === 'string'
1343
- ? options.data
1344
- : JSON.stringify(options.data)
1345
- : null;
1346
- }
1347
- if (onCancel) {
1348
- onCancel(function () {
1349
- xhr.abort();
1350
- });
1351
- }
1352
- xhr.send(data);
1353
- };
1226
+ // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
1227
+ const templateRe = /\{ *([\w_-]+) *\}/g;
1228
+ function template(str, data) {
1229
+ return str.replace(templateRe, (s, key) => {
1230
+ let value = data[key];
1231
+ if (value === undefined) {
1232
+ throw new Error('No value provided for letiable ' + s);
1233
+ }
1234
+ else if (typeof value === 'function') {
1235
+ value = value(data);
1236
+ }
1237
+ return value;
1238
+ });
1354
1239
  }
1355
1240
 
1356
- // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
1357
- var templateRe = /\{ *([\w_-]+) *\}/g;
1358
- function template(str, data) {
1359
- return str.replace(templateRe, function (s, key) {
1360
- var value = data[key];
1361
- if (value === undefined) {
1362
- throw new Error('No value provided for letiable ' + s);
1363
- }
1364
- else if (typeof value === 'function') {
1365
- value = value(data);
1366
- }
1367
- return value;
1368
- });
1241
+ function apiRequest(opt) {
1242
+ const params = opt.params;
1243
+ return new CancelablePromise((resolve, reject) => {
1244
+ opt.connector
1245
+ .connect()
1246
+ .then((apiItems) => {
1247
+ let apiItem = apiItems && apiItems[opt.name];
1248
+ if (apiItem) {
1249
+ apiItem = [...apiItem];
1250
+ let url = apiItem.shift();
1251
+ if (apiItem.length) {
1252
+ const replaceParams = {};
1253
+ for (let fry = 0; fry < apiItem.length; fry++) {
1254
+ const arg = apiItem[fry];
1255
+ replaceParams[fry] = '{' + arg + '}';
1256
+ if (params[arg] === undefined) {
1257
+ throw new Error('`' + arg + '`' + ' url api argument is not specified');
1258
+ }
1259
+ }
1260
+ if (url) {
1261
+ url = template(url, replaceParams);
1262
+ }
1263
+ }
1264
+ // Transfer part of the parameters from `params` to the URL string
1265
+ if (params) {
1266
+ const paramArray = [];
1267
+ const paramList = params.paramList;
1268
+ if (Array.isArray(paramList)) {
1269
+ delete params.paramList;
1270
+ paramList.forEach((x) => {
1271
+ paramArray.push(`${x[0]}=${x[1]}`);
1272
+ });
1273
+ }
1274
+ for (const p in params) {
1275
+ if (apiItem.indexOf(p) === -1) {
1276
+ paramArray.push(`${p}=${params[p]}`);
1277
+ }
1278
+ }
1279
+ if (paramArray.length) {
1280
+ url = url + '?' + paramArray.join('&');
1281
+ }
1282
+ }
1283
+ if (url) {
1284
+ resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
1285
+ }
1286
+ else {
1287
+ reject(new Error('request url is not set'));
1288
+ }
1289
+ }
1290
+ else {
1291
+ resolve(undefined);
1292
+ }
1293
+ })
1294
+ .catch((er) => {
1295
+ reject(er);
1296
+ });
1297
+ });
1298
+ }
1299
+
1300
+ /**
1301
+ * Thrown when ...
1302
+ */
1303
+ class ResourceNotFoundError extends NgwError {
1304
+ constructor(obj) {
1305
+ super(obj);
1306
+ this.name = 'ResourceNotFoundError';
1307
+ this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
1308
+ Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
1309
+ }
1310
+ }
1311
+
1312
+ /**
1313
+ * Thrown when ...
1314
+ */
1315
+ class InsufficientPermissionsError extends NgwError {
1316
+ constructor(obj) {
1317
+ super(obj);
1318
+ this.name = 'InsufficientPermissionsError';
1319
+ this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
1320
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1321
+ }
1322
+ }
1323
+
1324
+ const CONNECTORS = [];
1325
+ function addConnector(connector) {
1326
+ CONNECTORS.push(connector);
1327
+ }
1328
+ function findConnector(options) {
1329
+ return CONNECTORS.find((x) => {
1330
+ if (x.options.baseUrl === options.baseUrl) {
1331
+ if (options.auth) {
1332
+ if (x.options.auth) {
1333
+ return objectDeepEqual(x.options.auth, options.auth);
1334
+ }
1335
+ }
1336
+ else {
1337
+ // if auth not in find options; use first connector with same url
1338
+ return true;
1339
+ }
1340
+ }
1341
+ });
1342
+ }
1343
+ function removeConnector(connector) {
1344
+ const index = CONNECTORS.indexOf(connector);
1345
+ if (index !== -1) {
1346
+ CONNECTORS.splice(index, 1);
1347
+ }
1369
1348
  }
1370
1349
 
1371
- function apiRequest(opt) {
1372
- var params = opt.params;
1373
- return new CancelablePromise(function (resolve, reject) {
1374
- opt.connector
1375
- .connect()
1376
- .then(function (apiItems) {
1377
- var apiItem = apiItems && apiItems[opt.name];
1378
- if (apiItem) {
1379
- apiItem = __spreadArray([], apiItem, true);
1380
- var url = apiItem.shift();
1381
- if (apiItem.length) {
1382
- var replaceParams = {};
1383
- for (var fry = 0; fry < apiItem.length; fry++) {
1384
- var arg = apiItem[fry];
1385
- replaceParams[fry] = '{' + arg + '}';
1386
- if (params[arg] === undefined) {
1387
- throw new Error('`' + arg + '`' + ' url api argument is not specified');
1388
- }
1389
- }
1390
- if (url) {
1391
- url = template(url, replaceParams);
1392
- }
1393
- }
1394
- // Transfer part of the parameters from `params` to the URL string
1395
- if (params) {
1396
- var paramArray_1 = [];
1397
- var paramList = params.paramList;
1398
- if (Array.isArray(paramList)) {
1399
- delete params.paramList;
1400
- paramList.forEach(function (x) {
1401
- paramArray_1.push("".concat(x[0], "=").concat(x[1]));
1402
- });
1403
- }
1404
- for (var p in params) {
1405
- if (apiItem.indexOf(p) === -1) {
1406
- paramArray_1.push("".concat(p, "=").concat(params[p]));
1407
- }
1408
- }
1409
- if (paramArray_1.length) {
1410
- url = url + '?' + paramArray_1.join('&');
1411
- }
1412
- }
1413
- if (url) {
1414
- resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
1415
- }
1416
- else {
1417
- reject(new Error('request url is not set'));
1418
- }
1419
- }
1420
- else {
1421
- resolve(undefined);
1422
- }
1423
- })
1424
- .catch(function (er) {
1425
- reject(er);
1426
- });
1427
- });
1350
+ const exclude = ['description'];
1351
+ /**
1352
+ * @remarks
1353
+ * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
1354
+ *
1355
+ * ```
1356
+ * { keyname, owner_user: { id }} > { keyname, owner_user__id }
1357
+ * ```
1358
+ *
1359
+ * @param resource - Any property from NGW resource item
1360
+ */
1361
+ function resourceToQuery(resource, prefix = '') {
1362
+ prefix = prefix ? prefix + '__' : '';
1363
+ const query = {};
1364
+ for (const [key, value] of Object.entries(resource)) {
1365
+ if (exclude.indexOf(key) === -1) {
1366
+ if (isObject(value)) {
1367
+ if (key === 'owner_user') {
1368
+ const children = resourceToQuery(value, key);
1369
+ Object.assign(query, children);
1370
+ }
1371
+ else if (key === 'parent' && 'id' in value) {
1372
+ query.parent_id = value.id;
1373
+ }
1374
+ }
1375
+ else if (defined(value)) {
1376
+ query[prefix + key] = value;
1377
+ }
1378
+ }
1379
+ }
1380
+ return query;
1428
1381
  }
1429
1382
 
1430
- /**
1431
- * Thrown when ...
1432
- */
1433
- var ResourceNotFoundError = /** @class */ (function (_super) {
1434
- __extends(ResourceNotFoundError, _super);
1435
- function ResourceNotFoundError(obj) {
1436
- var _this = _super.call(this, obj) || this;
1437
- _this.name = 'ResourceNotFoundError';
1438
- _this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
1439
- Object.setPrototypeOf(_this, ResourceNotFoundError.prototype);
1440
- return _this;
1441
- }
1442
- return ResourceNotFoundError;
1443
- }(NgwError));
1444
-
1445
- /**
1446
- * Thrown when ...
1447
- */
1448
- var InsufficientPermissionsError = /** @class */ (function (_super) {
1449
- __extends(InsufficientPermissionsError, _super);
1450
- function InsufficientPermissionsError(obj) {
1451
- var _this = _super.call(this, obj) || this;
1452
- _this.name = 'InsufficientPermissionsError';
1453
- _this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
1454
- Object.setPrototypeOf(_this, InsufficientPermissionsError.prototype);
1455
- return _this;
1456
- }
1457
- return InsufficientPermissionsError;
1458
- }(NgwError));
1459
-
1460
- var CONNECTORS = [];
1461
- function addConnector(connector) {
1462
- CONNECTORS.push(connector);
1463
- }
1464
- function findConnector(options) {
1465
- return CONNECTORS.find(function (x) {
1466
- if (x.options.baseUrl === options.baseUrl) {
1467
- if (options.auth) {
1468
- if (x.options.auth) {
1469
- return objectDeepEqual(x.options.auth, options.auth);
1470
- }
1471
- }
1472
- else {
1473
- // if auth not in find options; use first connector with same url
1474
- return true;
1475
- }
1476
- }
1477
- });
1478
- }
1479
- function removeConnector(connector) {
1480
- var index = CONNECTORS.indexOf(connector);
1481
- if (index !== -1) {
1482
- CONNECTORS.splice(index, 1);
1483
- }
1383
+ function resourceCompare(res1, res2) {
1384
+ return objectDeepEqual(res1, res2);
1484
1385
  }
1485
1386
 
1486
- var exclude = ['description'];
1487
- /**
1488
- * @remarks
1489
- * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
1490
- *
1491
- * ```
1492
- * { keyname, owner_user: { id }} > { keyname, owner_user__id }
1493
- * ```
1494
- *
1495
- * @param resource - Any property from NGW resource item
1496
- */
1497
- function resourceToQuery(resource, prefix) {
1498
- if (prefix === void 0) { prefix = ''; }
1499
- prefix = prefix ? prefix + '__' : '';
1500
- var query = {};
1501
- for (var _i = 0, _a = Object.entries(resource); _i < _a.length; _i++) {
1502
- var _b = _a[_i], key = _b[0], value = _b[1];
1503
- if (exclude.indexOf(key) === -1) {
1504
- if (isObject(value)) {
1505
- if (key === 'owner_user') {
1506
- var children = resourceToQuery(value, key);
1507
- Object.assign(query, children);
1508
- }
1509
- else if (key === 'parent' && 'id' in value) {
1510
- query.parent_id = value.id;
1511
- }
1512
- }
1513
- else if (defined(value)) {
1514
- query[prefix + key] = value;
1515
- }
1516
- }
1517
- }
1518
- return query;
1387
+ class ResourcesControl {
1388
+ constructor(connector) {
1389
+ this.connector = connector;
1390
+ this.cache = new Cache();
1391
+ }
1392
+ // -------------------------------------------------------------------------
1393
+ // Resource Methods
1394
+ // -------------------------------------------------------------------------
1395
+ /**
1396
+ * Receive resource from NGW by id, keyname or search-object parameter.
1397
+ * @param resource - Resource id, keyname or search-object
1398
+ *
1399
+ * @remarks
1400
+ * Fetching resource would be cached to speed up next call
1401
+ */
1402
+ getOne(resource, requestOptions) {
1403
+ const cache = new Cache();
1404
+ const forCache = {};
1405
+ const opt = { ...requestOptions, cache: false };
1406
+ if (typeof resource === 'string') {
1407
+ forCache.keyname = resource;
1408
+ }
1409
+ else if (typeof resource === 'number') {
1410
+ forCache.id = resource;
1411
+ }
1412
+ else if (isObject(resource)) {
1413
+ if (resource.id !== undefined) {
1414
+ forCache.id = resource.id;
1415
+ }
1416
+ else if (resource.keyname) {
1417
+ forCache.keyname = resource.keyname;
1418
+ }
1419
+ }
1420
+ const makeRequest = () => {
1421
+ if (typeof resource === 'string') {
1422
+ return this._fetchResourceBy({ keyname: resource }, opt);
1423
+ }
1424
+ else if (typeof resource === 'number') {
1425
+ return this._fetchResourceById(resource, opt);
1426
+ }
1427
+ else if (isObject(resource)) {
1428
+ return this._fetchResourceBy(resource, opt);
1429
+ }
1430
+ return CancelablePromise.resolve(undefined);
1431
+ };
1432
+ return cache.addFull('resource', makeRequest, forCache);
1433
+ }
1434
+ getOneOrFail(resource, requestOptions) {
1435
+ return this.getOne(resource, requestOptions).then((res) => {
1436
+ if (res) {
1437
+ return res;
1438
+ }
1439
+ throw new ResourceNotFoundError();
1440
+ });
1441
+ }
1442
+ /**
1443
+ * A fast way to retrieve resource ID for any resource definition.
1444
+ * @param resource - Any available resource definition
1445
+ *
1446
+ * @remarks
1447
+ * There are situations when exactly the resource id is needed
1448
+ * (for example, to compose the correct request to the api)
1449
+ * then this method will come in handy to facilitate the extraction of the identifier
1450
+ * if the resource is specified through a keyname or other parameters.
1451
+ */
1452
+ getId(resource, requestOptions) {
1453
+ if (typeof resource === 'number') {
1454
+ return CancelablePromise.resolve(resource);
1455
+ }
1456
+ else if (typeof resource === 'string' || isObject(resource)) {
1457
+ return this.getOne(resource, requestOptions).then((res) => {
1458
+ if (res) {
1459
+ return res.resource.id;
1460
+ }
1461
+ });
1462
+ }
1463
+ return CancelablePromise.resolve(undefined);
1464
+ }
1465
+ /**
1466
+ * A fast way to retrieve resource ID for any resource definition.
1467
+ * @param resource - Any available resource definition
1468
+ *
1469
+ * @remarks
1470
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1471
+ * To not make one more checks if the resource is definitely exists
1472
+ */
1473
+ getIdOrFail(resource, requestOptions) {
1474
+ return this.getId(resource, requestOptions).then((resp) => {
1475
+ if (resp === undefined) {
1476
+ throw new Error();
1477
+ }
1478
+ return resp;
1479
+ });
1480
+ }
1481
+ getMany(resource, requestOptions) {
1482
+ return this._resourceCacheFilter(resource).then((items) => {
1483
+ if (!items.length) {
1484
+ const query = {};
1485
+ if (resource.keyname) {
1486
+ query.keyname = resource.keyname;
1487
+ }
1488
+ else {
1489
+ Object.assign(query, resourceToQuery(resource));
1490
+ }
1491
+ return this.connector
1492
+ .get('resource.search', requestOptions, {
1493
+ serialization: 'full',
1494
+ ...query,
1495
+ })
1496
+ .then((resources) => {
1497
+ if (resources) {
1498
+ for (const x of resources) {
1499
+ this.cache.add('resource.item', CancelablePromise.resolve(x), {
1500
+ id: x.resource.id,
1501
+ });
1502
+ }
1503
+ }
1504
+ return resources;
1505
+ });
1506
+ }
1507
+ return items;
1508
+ });
1509
+ }
1510
+ getParent(resource, requestOptions) {
1511
+ return this.getOne(resource, requestOptions).then((child) => {
1512
+ if (child) {
1513
+ return this.getOne(child.resource.parent.id, requestOptions);
1514
+ }
1515
+ return CancelablePromise.resolve(undefined);
1516
+ });
1517
+ }
1518
+ getChildrenOf(resource, requestOptions) {
1519
+ return this.getIdOrFail(resource).then((parent) => this._getChildrenOf(parent, requestOptions));
1520
+ }
1521
+ update(resource, data) {
1522
+ return this.getId(resource).then((id) => {
1523
+ if (id !== undefined) {
1524
+ return this.connector.put('resource.item', { data }, { id });
1525
+ }
1526
+ });
1527
+ }
1528
+ /**
1529
+ * Fast way to delete resource from NGW and clean cache.
1530
+ * @param resource - Resource definition
1531
+ */
1532
+ delete(resource) {
1533
+ return this.getId(resource).then((id) => {
1534
+ if (id !== undefined) {
1535
+ return this.connector.delete('resource.item', null, { id }).then(() => {
1536
+ this._cleanResourceItemCache(id);
1537
+ return undefined;
1538
+ });
1539
+ }
1540
+ });
1541
+ }
1542
+ _getChildrenOf(parent, requestOptions, _items = []) {
1543
+ return this.connector
1544
+ .get('resource.collection', { cache: true, ...requestOptions }, {
1545
+ parent,
1546
+ })
1547
+ .then((items) => {
1548
+ const recursivePromises = [];
1549
+ for (const item of items) {
1550
+ this.cache.add('resource.item', CancelablePromise.resolve(item), {
1551
+ id: item.resource.id,
1552
+ });
1553
+ _items.push(item);
1554
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
1555
+ recursivePromises.push(this._getChildrenOf(item.resource.id, requestOptions, _items));
1556
+ }
1557
+ }
1558
+ if (recursivePromises.length) {
1559
+ return CancelablePromise.all(recursivePromises).then(() => {
1560
+ return _items;
1561
+ });
1562
+ }
1563
+ return _items;
1564
+ });
1565
+ }
1566
+ async _cleanResourceItemCache(id) {
1567
+ const all = this.cache.all();
1568
+ const toDelete = [];
1569
+ for (const c of all) {
1570
+ const cid = c.options && c.options.id;
1571
+ if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {
1572
+ if (typeof cid === 'number') {
1573
+ if (cid === id) {
1574
+ toDelete.push(c);
1575
+ }
1576
+ }
1577
+ else {
1578
+ const rid = await this.getId(cid);
1579
+ if (rid === id) {
1580
+ toDelete.push(c);
1581
+ }
1582
+ }
1583
+ }
1584
+ }
1585
+ for (const d of toDelete) {
1586
+ this.cache.delete(d);
1587
+ }
1588
+ }
1589
+ _fetchResourceById(id, requestOptions) {
1590
+ const promise = () => this.connector.get('resource.item', requestOptions, { id });
1591
+ return this.cache
1592
+ .add('resource.item', promise, {
1593
+ id,
1594
+ })
1595
+ .catch((er) => {
1596
+ if (!(er instanceof ResourceNotFoundError)) {
1597
+ throw er;
1598
+ }
1599
+ return undefined;
1600
+ });
1601
+ }
1602
+ _fetchResourceBy(resource, requestOptions) {
1603
+ return this.getMany(resource, requestOptions).then((resources) => {
1604
+ return resources[0];
1605
+ });
1606
+ }
1607
+ _resourceCacheFilter(resource) {
1608
+ return CancelablePromise.all(this.cache.matchAll('resource.item')).then((resources) => {
1609
+ const items = [];
1610
+ resources.filter((x) => {
1611
+ if (x) {
1612
+ // identical by uniq props
1613
+ if (resource.keyname && x.resource.keyname) {
1614
+ return resource.keyname === x.resource.keyname;
1615
+ }
1616
+ if (defined(resource.id) && defined(x.resource.id)) {
1617
+ return resource.id === x.resource.id;
1618
+ }
1619
+ return resourceCompare(resource, x.resource);
1620
+ }
1621
+ });
1622
+ return items;
1623
+ });
1624
+ }
1519
1625
  }
1520
1626
 
1521
- function resourceCompare(res1, res2) {
1522
- return objectDeepEqual(res1, res2);
1627
+ let ID = 0;
1628
+ class NgwConnector$1 {
1629
+ constructor(options) {
1630
+ this.options = options;
1631
+ this.id = ID++;
1632
+ this.emitter = new events.exports.EventEmitter();
1633
+ this.routeStr = '/api/component/pyramid/route';
1634
+ this.activeRequests = [];
1635
+ const exist = findConnector(options);
1636
+ if (exist) {
1637
+ return exist;
1638
+ }
1639
+ else {
1640
+ if (this.options.route) {
1641
+ this.routeStr = this.options.route;
1642
+ }
1643
+ if (this.options.requestTransform) {
1644
+ this.requestTransform = this.options.requestTransform;
1645
+ }
1646
+ this.resources = new ResourcesControl(this);
1647
+ addConnector(this);
1648
+ }
1649
+ }
1650
+ static create(options) {
1651
+ return new this(options);
1652
+ }
1653
+ setRequestTransform(requestTransform) {
1654
+ this.requestTransform = requestTransform;
1655
+ }
1656
+ /**
1657
+ * Fast way to specify the connection address to NextGIS Web.
1658
+ * The current connection will be severed.
1659
+ * @param baseUrl - NGW url
1660
+ */
1661
+ setNgw(baseUrl) {
1662
+ this.logout();
1663
+ this.options.baseUrl = baseUrl;
1664
+ addConnector(this);
1665
+ }
1666
+ /**
1667
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
1668
+ * @remarks
1669
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1670
+ * Can be used to check connection.
1671
+ * @example
1672
+ * ```javascript
1673
+ * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1674
+ * connector.connect()
1675
+ * .then(() => console.log('Ok'))
1676
+ * .catch((er) => console.log('Connection problem', er));
1677
+ * ```
1678
+ */
1679
+ connect() {
1680
+ const cache = new Cache();
1681
+ const auth = this.options.auth;
1682
+ const makeConnect = () => new CancelablePromise((resolve, reject) => {
1683
+ const makeQuery = () => {
1684
+ return this.makeQuery(this.routeStr, {}, {})
1685
+ .then((route) => {
1686
+ resolve(route);
1687
+ })
1688
+ .catch((er) => {
1689
+ reject(er);
1690
+ });
1691
+ };
1692
+ if (auth) {
1693
+ const { login, password } = auth;
1694
+ if (login && password) {
1695
+ return this._login({ login, password })
1696
+ .then(() => {
1697
+ return makeQuery();
1698
+ })
1699
+ .catch((er) => reject(er));
1700
+ }
1701
+ }
1702
+ return makeQuery();
1703
+ });
1704
+ return cache.add('route', makeConnect, {
1705
+ id: this.id,
1706
+ auth,
1707
+ baseUrl: this.options.baseUrl,
1708
+ });
1709
+ }
1710
+ /**
1711
+ * Quick way to change NextGIS Web user.
1712
+ * @param credentials - New user credentials
1713
+ */
1714
+ login(credentials, options) {
1715
+ this.logout();
1716
+ addConnector(this);
1717
+ return this._login(credentials, options);
1718
+ }
1719
+ /**
1720
+ * Disconnecting a user. Aborting all current requests
1721
+ */
1722
+ logout() {
1723
+ this.abort();
1724
+ removeConnector(this);
1725
+ this.options.auth = undefined;
1726
+ this.user = undefined;
1727
+ this.emitter.emit('logout');
1728
+ this.resources.cache.clean();
1729
+ }
1730
+ getUserInfo(credentials, options) {
1731
+ if (this.user && this.user.id) {
1732
+ return CancelablePromise.resolve(this.user);
1733
+ }
1734
+ if (credentials) {
1735
+ this.options.auth = credentials;
1736
+ }
1737
+ const options_ = {
1738
+ headers: this.getAuthorizationHeaders(credentials),
1739
+ // withCredentials: true
1740
+ ...options,
1741
+ };
1742
+ // Do not use apiRequest('auth.current_user') to avoid circular-references
1743
+ return this.makeQuery('/api/component/auth/current_user', {}, options_);
1744
+ }
1745
+ /**
1746
+ * Obtaining the required Headers for authentication of requests in the NGW.
1747
+ */
1748
+ getAuthorizationHeaders(credentials) {
1749
+ const client = this.makeClientId(credentials);
1750
+ if (client) {
1751
+ return {
1752
+ Authorization: 'Basic ' + client,
1753
+ };
1754
+ }
1755
+ }
1756
+ makeClientId(credentials) {
1757
+ credentials = credentials || this.options.auth;
1758
+ if (credentials) {
1759
+ const { login, password } = credentials;
1760
+ const str = unescape(encodeURIComponent(`${login}:${password}`));
1761
+ // @ts-ignore
1762
+ {
1763
+ return window.btoa(str);
1764
+ }
1765
+ }
1766
+ }
1767
+ /** Stop all api requests */
1768
+ abort() {
1769
+ for (const req of this.activeRequests) {
1770
+ req.cancel();
1771
+ }
1772
+ this.activeRequests = [];
1773
+ }
1774
+ getActiveApiRequests() {
1775
+ return [...this.activeRequests];
1776
+ }
1777
+ /**
1778
+ * Send request to NGW api router.
1779
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1780
+ * @param params - Request item params or query params
1781
+ * @param requestOptions - Request options
1782
+ *
1783
+ * @example
1784
+ * ```javascript
1785
+ *
1786
+ * // there is such an NGW route item
1787
+ * // "feature_layer.feature.item": [
1788
+ * // "/api/resource/{0}/feature/{1}",
1789
+ * // "id",
1790
+ * // "fid"
1791
+ * // ],
1792
+ *
1793
+ * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
1794
+ * connector.apiRequest('feature_layer.feature.item', {
1795
+ * // request params for {0} and {1}
1796
+ * 'id': 2011,
1797
+ * 'fid': 101,
1798
+ * // query params
1799
+ * 'srs': 4326,
1800
+ * 'geom_format': 'geojson',
1801
+ * }, { method: 'GET' });
1802
+ * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
1803
+ *
1804
+ * ```
1805
+ */
1806
+ apiRequest(name, params_ = {}, requestOptions = {}) {
1807
+ var _a;
1808
+ const { method, headers, withCredentials, responseType } = requestOptions;
1809
+ const params = objectRemoveEmpty(params_);
1810
+ const makeApiRequest = () => apiRequest({ name, params, requestOptions, connector: this });
1811
+ if (requestOptions.cache && method === 'GET') {
1812
+ const cache = new Cache();
1813
+ return cache.add(name, makeApiRequest, {
1814
+ params,
1815
+ ...objectRemoveEmpty({
1816
+ headers,
1817
+ withCredentials,
1818
+ responseType,
1819
+ baseUrl: this.options.baseUrl,
1820
+ userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
1821
+ }),
1822
+ });
1823
+ }
1824
+ return makeApiRequest();
1825
+ }
1826
+ /**
1827
+ * Shortcut method for send POST request to NGW.
1828
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1829
+ * @param options - Request options
1830
+ * @param params - Request item params or query params
1831
+ *
1832
+ * @example
1833
+ * ```javascript
1834
+ * connector.post('resource.collection', { data: POST_PAYLOAD })
1835
+ * .then((newResource) => console.log(newResource))
1836
+ * .catch((error) => console.warn(error));
1837
+ * ```
1838
+ */
1839
+ post(name, options, params) {
1840
+ options = options || {};
1841
+ options.method = 'POST';
1842
+ return this.apiRequest(name, params, options);
1843
+ }
1844
+ /**
1845
+ * Shortcut method for send GET request to NGW.
1846
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1847
+ * @param options - Request options
1848
+ * @param params - Request item params or query params
1849
+ */
1850
+ get(name, options, params) {
1851
+ options = options || {};
1852
+ options.method = 'GET';
1853
+ return this.apiRequest(name, params, options);
1854
+ }
1855
+ /**
1856
+ * Shortcut method for send PATCH request to NGW.
1857
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1858
+ * @param options - Request options
1859
+ * @param params - Request item params or query params
1860
+ */
1861
+ patch(name, options, params) {
1862
+ options = options || {};
1863
+ options.method = 'PATCH';
1864
+ return this.apiRequest(name, params, options);
1865
+ }
1866
+ /**
1867
+ * Shortcut method for send PUT request to NGW.
1868
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1869
+ * @param options - Request options
1870
+ * @param params - Request item params or query params
1871
+ */
1872
+ put(name, options, params) {
1873
+ options = options || {};
1874
+ options.method = 'PUT';
1875
+ return this.apiRequest(name, params, options);
1876
+ }
1877
+ /**
1878
+ * Shortcut method for send DELETE request to NGW.
1879
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1880
+ * @param options - Request options
1881
+ * @param params - Request item params or query params
1882
+ */
1883
+ delete(name, options, params) {
1884
+ options = options || {};
1885
+ options.method = 'DELETE';
1886
+ return this.apiRequest(name, params, options);
1887
+ }
1888
+ /**
1889
+ * Send request to NGW.
1890
+ * @param url - URL address to NGW
1891
+ * @param params - Query params
1892
+ * @param options - Request options
1893
+ */
1894
+ makeQuery(url, params, options = {}) {
1895
+ url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
1896
+ if (url) {
1897
+ if (params) {
1898
+ url = template(url, params);
1899
+ }
1900
+ url = encodeURI(fixUrlStr(url));
1901
+ return this._loadData(url, options);
1902
+ }
1903
+ else {
1904
+ throw new Error('Empty `url` not allowed');
1905
+ }
1906
+ }
1907
+ // -------------------------------------------------------------------------
1908
+ // Resource Methods
1909
+ // -------------------------------------------------------------------------
1910
+ /**
1911
+ * {@link ResourcesControl.getOne}
1912
+ */
1913
+ getResource(resource, requestOptions) {
1914
+ return this.resources.getOne(resource, requestOptions);
1915
+ }
1916
+ /**
1917
+ * {@link ResourcesControl.getOneOrFail}
1918
+ */
1919
+ getResourceOrFail(resource, requestOptions) {
1920
+ return this.resources.getOneOrFail(resource, requestOptions);
1921
+ }
1922
+ /**
1923
+ * @deprecated - use {@link getResource}
1924
+ */
1925
+ getResourceBy(resource) {
1926
+ return this.resources.getOne(resource);
1927
+ }
1928
+ /**
1929
+ * @deprecated - use {@link getResource}
1930
+ */
1931
+ getResourceByKeyname(keyname) {
1932
+ return this.resources.getOne(keyname);
1933
+ }
1934
+ /**
1935
+ * @deprecated - use {@link getResource}
1936
+ */
1937
+ getResourceById(id) {
1938
+ return this.resources.getOne(id);
1939
+ }
1940
+ /**
1941
+ * {@link ResourcesControl.getId}
1942
+ */
1943
+ getResourceId(resource, requestOptions) {
1944
+ return this.resources.getId(resource, requestOptions);
1945
+ }
1946
+ /**
1947
+ * {@link ResourcesControl.getIdOrFail}
1948
+ */
1949
+ getResourceIdOrFail(resource, requestOptions) {
1950
+ return this.resources.getIdOrFail(resource, requestOptions);
1951
+ }
1952
+ /**
1953
+ * {@link ResourcesControl.getMany}
1954
+ */
1955
+ getResourcesBy(resource, requestOptions) {
1956
+ return this.resources.getMany(resource, requestOptions);
1957
+ }
1958
+ /**
1959
+ * {@link ResourcesControl.getParent}
1960
+ */
1961
+ getResourceParent(resource, requestOptions) {
1962
+ return this.resources.getParent(resource, requestOptions);
1963
+ }
1964
+ /**
1965
+ * {@link ResourcesControl.getChildrenOf}
1966
+ */
1967
+ getResourceChildren(resource, requestOptions) {
1968
+ return this.resources.getChildrenOf(resource, requestOptions);
1969
+ }
1970
+ /**
1971
+ * {@link ResourcesControl.update}
1972
+ */
1973
+ updateResource(resource, data) {
1974
+ return this.resources.update(resource, data);
1975
+ }
1976
+ /**
1977
+ * {@link ResourcesControl.delete}
1978
+ */
1979
+ deleteResource(resource) {
1980
+ return this.resources.delete(resource);
1981
+ }
1982
+ /**
1983
+ * @internal
1984
+ */
1985
+ _loadData(url, options) {
1986
+ options.responseType = options.responseType || 'json';
1987
+ const request = new CancelablePromise((resolve, reject, onCancel) => {
1988
+ if (this.user) {
1989
+ options = options || {};
1990
+ // options.withCredentials = true;
1991
+ options.headers = {
1992
+ ...this.getAuthorizationHeaders(),
1993
+ ...options.headers,
1994
+ };
1995
+ }
1996
+ if (this.requestTransform) {
1997
+ const [transUrl, transOptions] = this.requestTransform(url, options);
1998
+ url = transUrl;
1999
+ options = transOptions;
2000
+ }
2001
+ loadData(url, resolve, options, reject, onCancel);
2002
+ })
2003
+ .then((resp) => {
2004
+ this._cleanActiveRequests(request);
2005
+ return resp;
2006
+ })
2007
+ .catch((httpError) => {
2008
+ this._cleanActiveRequests(request);
2009
+ if (httpError instanceof CancelablePromise.CancelError) ;
2010
+ else {
2011
+ // @ts-ignore
2012
+ {
2013
+ console.warn('DEV WARN', httpError);
2014
+ }
2015
+ const er = this._handleHttpError(httpError);
2016
+ if (er) {
2017
+ throw er;
2018
+ }
2019
+ }
2020
+ });
2021
+ if (options.signal &&
2022
+ typeof options.signal.addEventListener === 'function') {
2023
+ options.signal.addEventListener('abort', () => {
2024
+ request.cancel();
2025
+ this._cleanActiveRequests(request);
2026
+ });
2027
+ }
2028
+ this.activeRequests.push(request);
2029
+ return request;
2030
+ }
2031
+ _login(credentials, options) {
2032
+ return this.getUserInfo(credentials, options)
2033
+ .then((data) => {
2034
+ this.user = data;
2035
+ this.emitter.emit('login', data);
2036
+ return data;
2037
+ })
2038
+ .catch((er) => {
2039
+ this.emitter.emit('login:error', er);
2040
+ throw er;
2041
+ });
2042
+ }
2043
+ _cleanActiveRequests(request) {
2044
+ const activeRequestIndex = this.activeRequests.indexOf(request);
2045
+ if (activeRequestIndex !== -1) {
2046
+ this.activeRequests.splice(activeRequestIndex, 1);
2047
+ }
2048
+ }
2049
+ _handleHttpError(er) {
2050
+ if (er) {
2051
+ if (er instanceof NgwError) {
2052
+ if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
2053
+ throw new ResourceNotFoundError(er);
2054
+ }
2055
+ else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
2056
+ throw new InsufficientPermissionsError(er);
2057
+ }
2058
+ }
2059
+ }
2060
+ return er;
2061
+ }
1523
2062
  }
2063
+ NgwConnector$1.errors = {
2064
+ NgwError,
2065
+ ResourceNotFoundError,
2066
+ };
1524
2067
 
1525
- var ResourcesControl = /** @class */ (function () {
1526
- function ResourcesControl(connector) {
1527
- this.connector = connector;
1528
- this.cache = new Cache();
1529
- }
1530
- // -------------------------------------------------------------------------
1531
- // Resource Methods
1532
- // -------------------------------------------------------------------------
1533
- /**
1534
- * Receive resource from NGW by id, keyname or search-object parameter.
1535
- * @param resource - Resource id, keyname or search-object
1536
- *
1537
- * @remarks
1538
- * Fetching resource would be cached to speed up next call
1539
- */
1540
- ResourcesControl.prototype.getOne = function (resource, requestOptions) {
1541
- var _this = this;
1542
- var cache = new Cache();
1543
- var forCache = {};
1544
- var opt = __assign(__assign({}, requestOptions), { cache: false });
1545
- if (typeof resource === 'string') {
1546
- forCache.keyname = resource;
1547
- }
1548
- else if (typeof resource === 'number') {
1549
- forCache.id = resource;
1550
- }
1551
- else if (isObject(resource)) {
1552
- if (resource.id !== undefined) {
1553
- forCache.id = resource.id;
1554
- }
1555
- else if (resource.keyname) {
1556
- forCache.keyname = resource.keyname;
1557
- }
1558
- }
1559
- var makeRequest = function () {
1560
- if (typeof resource === 'string') {
1561
- return _this._fetchResourceBy({ keyname: resource }, opt);
1562
- }
1563
- else if (typeof resource === 'number') {
1564
- return _this._fetchResourceById(resource, opt);
1565
- }
1566
- else if (isObject(resource)) {
1567
- return _this._fetchResourceBy(resource, opt);
1568
- }
1569
- return CancelablePromise.resolve(undefined);
1570
- };
1571
- return cache.addFull('resource', makeRequest, forCache);
1572
- };
1573
- ResourcesControl.prototype.getOneOrFail = function (resource, requestOptions) {
1574
- return this.getOne(resource, requestOptions).then(function (res) {
1575
- if (res) {
1576
- return res;
1577
- }
1578
- throw new ResourceNotFoundError();
1579
- });
1580
- };
1581
- /**
1582
- * A fast way to retrieve resource ID for any resource definition.
1583
- * @param resource - Any available resource definition
1584
- *
1585
- * @remarks
1586
- * There are situations when exactly the resource id is needed
1587
- * (for example, to compose the correct request to the api)
1588
- * then this method will come in handy to facilitate the extraction of the identifier
1589
- * if the resource is specified through a keyname or other parameters.
1590
- */
1591
- ResourcesControl.prototype.getId = function (resource, requestOptions) {
1592
- if (typeof resource === 'number') {
1593
- return CancelablePromise.resolve(resource);
1594
- }
1595
- else if (typeof resource === 'string' || isObject(resource)) {
1596
- return this.getOne(resource, requestOptions).then(function (res) {
1597
- if (res) {
1598
- return res.resource.id;
1599
- }
1600
- });
1601
- }
1602
- return CancelablePromise.resolve(undefined);
1603
- };
1604
- /**
1605
- * A fast way to retrieve resource ID for any resource definition.
1606
- * @param resource - Any available resource definition
1607
- *
1608
- * @remarks
1609
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1610
- * To not make one more checks if the resource is definitely exists
1611
- */
1612
- ResourcesControl.prototype.getIdOrFail = function (resource, requestOptions) {
1613
- return this.getId(resource, requestOptions).then(function (resp) {
1614
- if (resp === undefined) {
1615
- throw new Error();
1616
- }
1617
- return resp;
1618
- });
1619
- };
1620
- ResourcesControl.prototype.getMany = function (resource, requestOptions) {
1621
- var _this = this;
1622
- return this._resourceCacheFilter(resource).then(function (items) {
1623
- if (!items.length) {
1624
- var query = {};
1625
- if (resource.keyname) {
1626
- query.keyname = resource.keyname;
1627
- }
1628
- else {
1629
- Object.assign(query, resourceToQuery(resource));
1630
- }
1631
- return _this.connector
1632
- .get('resource.search', requestOptions, __assign({ serialization: 'full' }, query))
1633
- .then(function (resources) {
1634
- if (resources) {
1635
- for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
1636
- var x = resources_1[_i];
1637
- _this.cache.add('resource.item', CancelablePromise.resolve(x), {
1638
- id: x.resource.id,
1639
- });
1640
- }
1641
- }
1642
- return resources;
1643
- });
1644
- }
1645
- return items;
1646
- });
1647
- };
1648
- ResourcesControl.prototype.getParent = function (resource, requestOptions) {
1649
- var _this = this;
1650
- return this.getOne(resource, requestOptions).then(function (child) {
1651
- if (child) {
1652
- return _this.getOne(child.resource.parent.id, requestOptions);
1653
- }
1654
- return CancelablePromise.resolve(undefined);
1655
- });
1656
- };
1657
- ResourcesControl.prototype.getChildrenOf = function (resource, requestOptions) {
1658
- var _this = this;
1659
- return this.getIdOrFail(resource).then(function (parent) {
1660
- return _this._getChildrenOf(parent, requestOptions);
1661
- });
1662
- };
1663
- ResourcesControl.prototype.update = function (resource, data) {
1664
- var _this = this;
1665
- return this.getId(resource).then(function (id) {
1666
- if (id !== undefined) {
1667
- return _this.connector.put('resource.item', { data: data }, { id: id });
1668
- }
1669
- });
1670
- };
1671
- /**
1672
- * Fast way to delete resource from NGW and clean cache.
1673
- * @param resource - Resource definition
1674
- */
1675
- ResourcesControl.prototype.delete = function (resource) {
1676
- var _this = this;
1677
- return this.getId(resource).then(function (id) {
1678
- if (id !== undefined) {
1679
- return _this.connector.delete('resource.item', null, { id: id }).then(function () {
1680
- _this._cleanResourceItemCache(id);
1681
- return undefined;
1682
- });
1683
- }
1684
- });
1685
- };
1686
- ResourcesControl.prototype._getChildrenOf = function (parent, requestOptions, _items) {
1687
- var _this = this;
1688
- if (_items === void 0) { _items = []; }
1689
- return this.connector
1690
- .get('resource.collection', __assign({ cache: true }, requestOptions), {
1691
- parent: parent,
1692
- })
1693
- .then(function (items) {
1694
- var recursivePromises = [];
1695
- for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
1696
- var item = items_1[_i];
1697
- _this.cache.add('resource.item', CancelablePromise.resolve(item), {
1698
- id: item.resource.id,
1699
- });
1700
- _items.push(item);
1701
- if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
1702
- recursivePromises.push(_this._getChildrenOf(item.resource.id, requestOptions, _items));
1703
- }
1704
- }
1705
- if (recursivePromises.length) {
1706
- return CancelablePromise.all(recursivePromises).then(function () {
1707
- return _items;
1708
- });
1709
- }
1710
- return _items;
1711
- });
1712
- };
1713
- ResourcesControl.prototype._cleanResourceItemCache = function (id) {
1714
- return __awaiter(this, void 0, void 0, function () {
1715
- var all, toDelete, _i, all_1, c, cid, rid, _a, toDelete_1, d;
1716
- return __generator(this, function (_b) {
1717
- switch (_b.label) {
1718
- case 0:
1719
- all = this.cache.all();
1720
- toDelete = [];
1721
- _i = 0, all_1 = all;
1722
- _b.label = 1;
1723
- case 1:
1724
- if (!(_i < all_1.length)) return [3 /*break*/, 5];
1725
- c = all_1[_i];
1726
- cid = c.options && c.options.id;
1727
- if (!(['resource.item', 'resource'].includes(c.key) && cid !== undefined)) return [3 /*break*/, 4];
1728
- if (!(typeof cid === 'number')) return [3 /*break*/, 2];
1729
- if (cid === id) {
1730
- toDelete.push(c);
1731
- }
1732
- return [3 /*break*/, 4];
1733
- case 2: return [4 /*yield*/, this.getId(cid)];
1734
- case 3:
1735
- rid = _b.sent();
1736
- if (rid === id) {
1737
- toDelete.push(c);
1738
- }
1739
- _b.label = 4;
1740
- case 4:
1741
- _i++;
1742
- return [3 /*break*/, 1];
1743
- case 5:
1744
- for (_a = 0, toDelete_1 = toDelete; _a < toDelete_1.length; _a++) {
1745
- d = toDelete_1[_a];
1746
- this.cache.delete(d);
1747
- }
1748
- return [2 /*return*/];
1749
- }
1750
- });
1751
- });
1752
- };
1753
- ResourcesControl.prototype._fetchResourceById = function (id, requestOptions) {
1754
- var _this = this;
1755
- var promise = function () {
1756
- return _this.connector.get('resource.item', requestOptions, { id: id });
1757
- };
1758
- return this.cache
1759
- .add('resource.item', promise, {
1760
- id: id,
1761
- })
1762
- .catch(function (er) {
1763
- if (!(er instanceof ResourceNotFoundError)) {
1764
- throw er;
1765
- }
1766
- return undefined;
1767
- });
1768
- };
1769
- ResourcesControl.prototype._fetchResourceBy = function (resource, requestOptions) {
1770
- return this.getMany(resource, requestOptions).then(function (resources) {
1771
- return resources[0];
1772
- });
1773
- };
1774
- ResourcesControl.prototype._resourceCacheFilter = function (resource) {
1775
- return CancelablePromise.all(this.cache.matchAll('resource.item')).then(function (resources) {
1776
- var items = [];
1777
- resources.filter(function (x) {
1778
- if (x) {
1779
- // identical by uniq props
1780
- if (resource.keyname && x.resource.keyname) {
1781
- return resource.keyname === x.resource.keyname;
1782
- }
1783
- if (defined(resource.id) && defined(x.resource.id)) {
1784
- return resource.id === x.resource.id;
1785
- }
1786
- return resourceCompare(resource, x.resource);
1787
- }
1788
- });
1789
- return items;
1790
- });
1791
- };
1792
- return ResourcesControl;
1793
- }());
1794
-
1795
- var ID = 0;
1796
- var NgwConnector$1 = /** @class */ (function () {
1797
- function NgwConnector(options) {
1798
- this.options = options;
1799
- this.id = ID++;
1800
- this.emitter = new events.exports.EventEmitter();
1801
- this.routeStr = '/api/component/pyramid/route';
1802
- this.activeRequests = [];
1803
- var exist = findConnector(options);
1804
- if (exist) {
1805
- return exist;
1806
- }
1807
- else {
1808
- if (this.options.route) {
1809
- this.routeStr = this.options.route;
1810
- }
1811
- if (this.options.requestTransform) {
1812
- this.requestTransform = this.options.requestTransform;
1813
- }
1814
- this.resources = new ResourcesControl(this);
1815
- addConnector(this);
1816
- }
1817
- }
1818
- NgwConnector.create = function (options) {
1819
- return new this(options);
1820
- };
1821
- NgwConnector.prototype.setRequestTransform = function (requestTransform) {
1822
- this.requestTransform = requestTransform;
1823
- };
1824
- /**
1825
- * Fast way to specify the connection address to NextGIS Web.
1826
- * The current connection will be severed.
1827
- * @param baseUrl - NGW url
1828
- */
1829
- NgwConnector.prototype.setNgw = function (baseUrl) {
1830
- this.logout();
1831
- this.options.baseUrl = baseUrl;
1832
- addConnector(this);
1833
- };
1834
- /**
1835
- * Establishing a connection with NextGIS Web to fulfill all other requests.
1836
- * @remarks
1837
- * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1838
- * Can be used to check connection.
1839
- * @example
1840
- * ```javascript
1841
- * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1842
- * connector.connect()
1843
- * .then(() => console.log('Ok'))
1844
- * .catch((er) => console.log('Connection problem', er));
1845
- * ```
1846
- */
1847
- NgwConnector.prototype.connect = function () {
1848
- var _this = this;
1849
- var cache = new Cache();
1850
- var auth = this.options.auth;
1851
- var makeConnect = function () {
1852
- return new CancelablePromise(function (resolve, reject) {
1853
- var makeQuery = function () {
1854
- return _this.makeQuery(_this.routeStr, {}, {})
1855
- .then(function (route) {
1856
- resolve(route);
1857
- })
1858
- .catch(function (er) {
1859
- reject(er);
1860
- });
1861
- };
1862
- if (auth) {
1863
- var login = auth.login, password = auth.password;
1864
- if (login && password) {
1865
- return _this._login({ login: login, password: password })
1866
- .then(function () {
1867
- return makeQuery();
1868
- })
1869
- .catch(function (er) { return reject(er); });
1870
- }
1871
- }
1872
- return makeQuery();
1873
- });
1874
- };
1875
- return cache.add('route', makeConnect, {
1876
- id: this.id,
1877
- auth: auth,
1878
- baseUrl: this.options.baseUrl,
1879
- });
1880
- };
1881
- /**
1882
- * Quick way to change NextGIS Web user.
1883
- * @param credentials - New user credentials
1884
- */
1885
- NgwConnector.prototype.login = function (credentials, options) {
1886
- this.logout();
1887
- addConnector(this);
1888
- return this._login(credentials, options);
1889
- };
1890
- /**
1891
- * Disconnecting a user. Aborting all current requests
1892
- */
1893
- NgwConnector.prototype.logout = function () {
1894
- this.abort();
1895
- removeConnector(this);
1896
- this.options.auth = undefined;
1897
- this.user = undefined;
1898
- this.emitter.emit('logout');
1899
- this.resources.cache.clean();
1900
- };
1901
- NgwConnector.prototype.getUserInfo = function (credentials, options) {
1902
- if (this.user && this.user.id) {
1903
- return CancelablePromise.resolve(this.user);
1904
- }
1905
- if (credentials) {
1906
- this.options.auth = credentials;
1907
- }
1908
- var options_ = __assign({ headers: this.getAuthorizationHeaders(credentials) }, options);
1909
- // Do not use apiRequest('auth.current_user') to avoid circular-references
1910
- return this.makeQuery('/api/component/auth/current_user', {}, options_);
1911
- };
1912
- /**
1913
- * Obtaining the required Headers for authentication of requests in the NGW.
1914
- */
1915
- NgwConnector.prototype.getAuthorizationHeaders = function (credentials) {
1916
- var client = this.makeClientId(credentials);
1917
- if (client) {
1918
- return {
1919
- Authorization: 'Basic ' + client,
1920
- };
1921
- }
1922
- };
1923
- NgwConnector.prototype.makeClientId = function (credentials) {
1924
- credentials = credentials || this.options.auth;
1925
- if (credentials) {
1926
- var login = credentials.login, password = credentials.password;
1927
- var str = unescape(encodeURIComponent("".concat(login, ":").concat(password)));
1928
- // @ts-ignore
1929
- {
1930
- return window.btoa(str);
1931
- }
1932
- }
1933
- };
1934
- /** Stop all api requests */
1935
- NgwConnector.prototype.abort = function () {
1936
- for (var _i = 0, _a = this.activeRequests; _i < _a.length; _i++) {
1937
- var req = _a[_i];
1938
- req.cancel();
1939
- }
1940
- this.activeRequests = [];
1941
- };
1942
- NgwConnector.prototype.getActiveApiRequests = function () {
1943
- return __spreadArray([], this.activeRequests, true);
1944
- };
1945
- /**
1946
- * Send request to NGW api router.
1947
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1948
- * @param params - Request item params or query params
1949
- * @param requestOptions - Request options
1950
- *
1951
- * @example
1952
- * ```javascript
1953
- *
1954
- * // there is such an NGW route item
1955
- * // "feature_layer.feature.item": [
1956
- * // "/api/resource/{0}/feature/{1}",
1957
- * // "id",
1958
- * // "fid"
1959
- * // ],
1960
- *
1961
- * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
1962
- * connector.apiRequest('feature_layer.feature.item', {
1963
- * // request params for {0} and {1}
1964
- * 'id': 2011,
1965
- * 'fid': 101,
1966
- * // query params
1967
- * 'srs': 4326,
1968
- * 'geom_format': 'geojson',
1969
- * }, { method: 'GET' });
1970
- * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
1971
- *
1972
- * ```
1973
- */
1974
- NgwConnector.prototype.apiRequest = function (name, params_, requestOptions) {
1975
- var _this = this;
1976
- var _a;
1977
- if (params_ === void 0) { params_ = {}; }
1978
- if (requestOptions === void 0) { requestOptions = {}; }
1979
- var method = requestOptions.method, headers = requestOptions.headers, withCredentials = requestOptions.withCredentials, responseType = requestOptions.responseType;
1980
- var params = objectRemoveEmpty(params_);
1981
- var makeApiRequest = function () {
1982
- return apiRequest({ name: name, params: params, requestOptions: requestOptions, connector: _this });
1983
- };
1984
- if (requestOptions.cache && method === 'GET') {
1985
- var cache = new Cache();
1986
- return cache.add(name, makeApiRequest, __assign({ params: params }, objectRemoveEmpty({
1987
- headers: headers,
1988
- withCredentials: withCredentials,
1989
- responseType: responseType,
1990
- baseUrl: this.options.baseUrl,
1991
- userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
1992
- })));
1993
- }
1994
- return makeApiRequest();
1995
- };
1996
- /**
1997
- * Shortcut method for send POST request to NGW.
1998
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1999
- * @param options - Request options
2000
- * @param params - Request item params or query params
2001
- *
2002
- * @example
2003
- * ```javascript
2004
- * connector.post('resource.collection', { data: POST_PAYLOAD })
2005
- * .then((newResource) => console.log(newResource))
2006
- * .catch((error) => console.warn(error));
2007
- * ```
2008
- */
2009
- NgwConnector.prototype.post = function (name, options, params) {
2010
- options = options || {};
2011
- options.method = 'POST';
2012
- return this.apiRequest(name, params, options);
2013
- };
2014
- /**
2015
- * Shortcut method for send GET request to NGW.
2016
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2017
- * @param options - Request options
2018
- * @param params - Request item params or query params
2019
- */
2020
- NgwConnector.prototype.get = function (name, options, params) {
2021
- options = options || {};
2022
- options.method = 'GET';
2023
- return this.apiRequest(name, params, options);
2024
- };
2025
- /**
2026
- * Shortcut method for send PATCH request to NGW.
2027
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2028
- * @param options - Request options
2029
- * @param params - Request item params or query params
2030
- */
2031
- NgwConnector.prototype.patch = function (name, options, params) {
2032
- options = options || {};
2033
- options.method = 'PATCH';
2034
- return this.apiRequest(name, params, options);
2035
- };
2036
- /**
2037
- * Shortcut method for send PUT request to NGW.
2038
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2039
- * @param options - Request options
2040
- * @param params - Request item params or query params
2041
- */
2042
- NgwConnector.prototype.put = function (name, options, params) {
2043
- options = options || {};
2044
- options.method = 'PUT';
2045
- return this.apiRequest(name, params, options);
2046
- };
2047
- /**
2048
- * Shortcut method for send DELETE request to NGW.
2049
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2050
- * @param options - Request options
2051
- * @param params - Request item params or query params
2052
- */
2053
- NgwConnector.prototype.delete = function (name, options, params) {
2054
- options = options || {};
2055
- options.method = 'DELETE';
2056
- return this.apiRequest(name, params, options);
2057
- };
2058
- /**
2059
- * Send request to NGW.
2060
- * @param url - URL address to NGW
2061
- * @param params - Query params
2062
- * @param options - Request options
2063
- */
2064
- NgwConnector.prototype.makeQuery = function (url, params, options) {
2065
- if (options === void 0) { options = {}; }
2066
- url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
2067
- if (url) {
2068
- if (params) {
2069
- url = template(url, params);
2070
- }
2071
- url = encodeURI(fixUrlStr(url));
2072
- return this._loadData(url, options);
2073
- }
2074
- else {
2075
- throw new Error('Empty `url` not allowed');
2076
- }
2077
- };
2078
- // -------------------------------------------------------------------------
2079
- // Resource Methods
2080
- // -------------------------------------------------------------------------
2081
- /**
2082
- * {@link ResourcesControl.getOne}
2083
- */
2084
- NgwConnector.prototype.getResource = function (resource, requestOptions) {
2085
- return this.resources.getOne(resource, requestOptions);
2086
- };
2087
- /**
2088
- * {@link ResourcesControl.getOneOrFail}
2089
- */
2090
- NgwConnector.prototype.getResourceOrFail = function (resource, requestOptions) {
2091
- return this.resources.getOneOrFail(resource, requestOptions);
2092
- };
2093
- /**
2094
- * @deprecated - use {@link getResource}
2095
- */
2096
- NgwConnector.prototype.getResourceBy = function (resource) {
2097
- return this.resources.getOne(resource);
2098
- };
2099
- /**
2100
- * @deprecated - use {@link getResource}
2101
- */
2102
- NgwConnector.prototype.getResourceByKeyname = function (keyname) {
2103
- return this.resources.getOne(keyname);
2104
- };
2105
- /**
2106
- * @deprecated - use {@link getResource}
2107
- */
2108
- NgwConnector.prototype.getResourceById = function (id) {
2109
- return this.resources.getOne(id);
2110
- };
2111
- /**
2112
- * {@link ResourcesControl.getId}
2113
- */
2114
- NgwConnector.prototype.getResourceId = function (resource, requestOptions) {
2115
- return this.resources.getId(resource, requestOptions);
2116
- };
2117
- /**
2118
- * {@link ResourcesControl.getIdOrFail}
2119
- */
2120
- NgwConnector.prototype.getResourceIdOrFail = function (resource, requestOptions) {
2121
- return this.resources.getIdOrFail(resource, requestOptions);
2122
- };
2123
- /**
2124
- * {@link ResourcesControl.getMany}
2125
- */
2126
- NgwConnector.prototype.getResourcesBy = function (resource, requestOptions) {
2127
- return this.resources.getMany(resource, requestOptions);
2128
- };
2129
- /**
2130
- * {@link ResourcesControl.getParent}
2131
- */
2132
- NgwConnector.prototype.getResourceParent = function (resource, requestOptions) {
2133
- return this.resources.getParent(resource, requestOptions);
2134
- };
2135
- /**
2136
- * {@link ResourcesControl.getChildrenOf}
2137
- */
2138
- NgwConnector.prototype.getResourceChildren = function (resource, requestOptions) {
2139
- return this.resources.getChildrenOf(resource, requestOptions);
2140
- };
2141
- /**
2142
- * {@link ResourcesControl.update}
2143
- */
2144
- NgwConnector.prototype.updateResource = function (resource, data) {
2145
- return this.resources.update(resource, data);
2146
- };
2147
- /**
2148
- * {@link ResourcesControl.delete}
2149
- */
2150
- NgwConnector.prototype.deleteResource = function (resource) {
2151
- return this.resources.delete(resource);
2152
- };
2153
- /**
2154
- * @internal
2155
- */
2156
- NgwConnector.prototype._loadData = function (url, options) {
2157
- var _this = this;
2158
- options.responseType = options.responseType || 'json';
2159
- var request = new CancelablePromise(function (resolve, reject, onCancel) {
2160
- if (_this.user) {
2161
- options = options || {};
2162
- // options.withCredentials = true;
2163
- options.headers = __assign(__assign({}, _this.getAuthorizationHeaders()), options.headers);
2164
- }
2165
- if (_this.requestTransform) {
2166
- var _a = _this.requestTransform(url, options), transUrl = _a[0], transOptions = _a[1];
2167
- url = transUrl;
2168
- options = transOptions;
2169
- }
2170
- loadData(url, resolve, options, reject, onCancel);
2171
- })
2172
- .then(function (resp) {
2173
- _this._cleanActiveRequests(request);
2174
- return resp;
2175
- })
2176
- .catch(function (httpError) {
2177
- _this._cleanActiveRequests(request);
2178
- if (httpError instanceof CancelablePromise.CancelError) ;
2179
- else {
2180
- // @ts-ignore
2181
- {
2182
- console.warn('DEV WARN', httpError);
2183
- }
2184
- var er = _this._handleHttpError(httpError);
2185
- if (er) {
2186
- throw er;
2187
- }
2188
- }
2189
- });
2190
- if (options.signal &&
2191
- typeof options.signal.addEventListener === 'function') {
2192
- options.signal.addEventListener('abort', function () {
2193
- request.cancel();
2194
- _this._cleanActiveRequests(request);
2195
- });
2196
- }
2197
- this.activeRequests.push(request);
2198
- return request;
2199
- };
2200
- NgwConnector.prototype._login = function (credentials, options) {
2201
- var _this = this;
2202
- return this.getUserInfo(credentials, options)
2203
- .then(function (data) {
2204
- _this.user = data;
2205
- _this.emitter.emit('login', data);
2206
- return data;
2207
- })
2208
- .catch(function (er) {
2209
- _this.emitter.emit('login:error', er);
2210
- throw er;
2211
- });
2212
- };
2213
- NgwConnector.prototype._cleanActiveRequests = function (request) {
2214
- var activeRequestIndex = this.activeRequests.indexOf(request);
2215
- if (activeRequestIndex !== -1) {
2216
- this.activeRequests.splice(activeRequestIndex, 1);
2217
- }
2218
- };
2219
- NgwConnector.prototype._handleHttpError = function (er) {
2220
- if (er) {
2221
- if (er instanceof NgwError) {
2222
- if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
2223
- throw new ResourceNotFoundError(er);
2224
- }
2225
- else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
2226
- throw new InsufficientPermissionsError(er);
2227
- }
2228
- }
2229
- }
2230
- return er;
2231
- };
2232
- NgwConnector.errors = {
2233
- NgwError: NgwError,
2234
- ResourceNotFoundError: ResourceNotFoundError,
2235
- };
2236
- return NgwConnector;
2237
- }());
2238
-
2239
- /**
2240
- * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
2241
- *
2242
- * @remarks
2243
- * Make sure CORS is registered in the {@link https://docs.nextgis.com/docs_ngcom/source/CORS.html | NextGIS Web settings } to be able to send requests.
2244
- *
2245
- * @packageDocumentation
2246
- * @module ngw-connector
2247
- */
2068
+ /**
2069
+ * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
2070
+ *
2071
+ * @remarks
2072
+ * Make sure CORS is registered in the {@link https://docs.nextgis.com/docs_ngcom/source/CORS.html | NextGIS Web settings } to be able to send requests.
2073
+ *
2074
+ * @packageDocumentation
2075
+ * @module ngw-connector
2076
+ */
2248
2077
  var NgwConnector = NgwConnector$1;
2249
2078
 
2250
2079
  export { NgwConnector as default };