@nextgis/ngw-connector 3.0.0-alpha.4 → 3.0.0-alpha.6

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,4 +1,61 @@
1
- /** Bundle of @nextgis/ngw-connector; version: 3.0.0-alpha.4; author: NextGIS */
1
+ /** Bundle of @nextgis/ngw-connector; version: 3.0.0-alpha.6; author: NextGIS */
2
+ function defined(val) {
3
+ return val !== void 0 && val !== null;
4
+ }
5
+ function full(val) {
6
+ return typeof val === "string" ? !!val : defined(val);
7
+ }
8
+
9
+ function isEqual(a, b, o, p) {
10
+ if (a instanceof Array) {
11
+ if (!(b instanceof Array)) return false;
12
+ return b.sort().join("") === a.sort().join("");
13
+ } else if (a instanceof Date) {
14
+ if (!(b instanceof Date)) return false;
15
+ return "" + a === "" + b;
16
+ } else if (a instanceof Function) {
17
+ if (!(b instanceof Function)) return false;
18
+ } else if (a instanceof Object) {
19
+ if (!(b instanceof Object)) return false;
20
+ if (a === o) {
21
+ return b === p;
22
+ } else {
23
+ return objectDeepEqual(a, b);
24
+ }
25
+ }
26
+ return a === b;
27
+ }
28
+ function objectDeepEqual(o, p) {
29
+ const keysO = Object.keys(o).sort();
30
+ const keysP = Object.keys(p).sort();
31
+ if (keysO.length !== keysP.length) return false;
32
+ if (keysO.join("") !== keysP.join("")) return false;
33
+ for (let i = 0; i < keysO.length; i++) {
34
+ const oVal = o[keysO[i]];
35
+ const pVal = p[keysP[i]];
36
+ if (!isEqual(oVal, pVal, o, p)) {
37
+ return false;
38
+ }
39
+ }
40
+ return true;
41
+ }
42
+
43
+ function objectRemoveEmpty(obj) {
44
+ const newObj = {};
45
+ Object.keys(obj).forEach((key) => {
46
+ if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
47
+ newObj[key] = objectRemoveEmpty(obj[key]);
48
+ } else if (obj[key] !== void 0) {
49
+ newObj[key] = obj[key];
50
+ }
51
+ });
52
+ return newObj;
53
+ }
54
+
55
+ function fixUrlStr(url) {
56
+ return url.replace(/([^:]\/)\/+/g, "$1");
57
+ }
58
+
2
59
  var domain;
3
60
 
4
61
  // This constructor is used to store event handlers. Instantiating this is
@@ -29,7 +86,7 @@ EventEmitter.init = function() {
29
86
  this.domain = null;
30
87
  if (EventEmitter.usingDomains) {
31
88
  // if there is an active domain, then attach to it.
32
- if (domain.active ) ;
89
+ if (domain.active) ;
33
90
  }
34
91
 
35
92
  if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
@@ -471,69 +528,12 @@ function unwrapListeners(arr) {
471
528
  return ret;
472
529
  }
473
530
 
474
- function defined(val) {
475
- return val !== void 0 && val !== null;
476
- }
477
- function full(val) {
478
- return typeof val === "string" ? !!val : defined(val);
479
- }
480
-
481
- function isEqual(a, b, o, p) {
482
- if (a instanceof Array) {
483
- if (!(b instanceof Array)) return false;
484
- return b.sort().join("") === a.sort().join("");
485
- } else if (a instanceof Date) {
486
- if (!(b instanceof Date)) return false;
487
- return "" + a === "" + b;
488
- } else if (a instanceof Function) {
489
- if (!(b instanceof Function)) return false;
490
- } else if (a instanceof Object) {
491
- if (!(b instanceof Object)) return false;
492
- if (a === o) {
493
- return b === p;
494
- } else {
495
- return objectDeepEqual(a, b);
496
- }
497
- }
498
- return a === b;
499
- }
500
- function objectDeepEqual(o, p) {
501
- const keysO = Object.keys(o).sort();
502
- const keysP = Object.keys(p).sort();
503
- if (keysO.length !== keysP.length) return false;
504
- if (keysO.join("") !== keysP.join("")) return false;
505
- for (let i = 0; i < keysO.length; i++) {
506
- const oVal = o[keysO[i]];
507
- const pVal = p[keysP[i]];
508
- if (!isEqual(oVal, pVal, o, p)) {
509
- return false;
510
- }
511
- }
512
- return true;
513
- }
514
-
515
- function objectRemoveEmpty(obj) {
516
- const newObj = {};
517
- Object.keys(obj).forEach((key) => {
518
- if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
519
- newObj[key] = objectRemoveEmpty(obj[key]);
520
- } else if (obj[key] !== void 0) {
521
- newObj[key] = obj[key];
522
- }
523
- });
524
- return newObj;
525
- }
526
-
527
- function fixUrlStr(url) {
528
- return url.replace(/([^:]\/)\/+/g, "$1");
529
- }
530
-
531
- var __defProp$7 = Object.defineProperty;
532
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
533
- var __publicField$6 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
531
+ var __defProp$b = Object.defineProperty;
532
+ var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
533
+ var __publicField$8 = (obj, key, value) => __defNormalProp$b(obj, typeof key !== "symbol" ? key + "" : key, value);
534
534
  const _Cache = class _Cache {
535
535
  constructor(options = {}) {
536
- __publicField$6(this, "cache", []);
536
+ __publicField$8(this, "cache", []);
537
537
  var _a;
538
538
  const namespace = (_a = options.namespace) != null ? _a : "default";
539
539
  if (_Cache.instance[namespace]) {
@@ -639,12 +639,12 @@ const _Cache = class _Cache {
639
639
  return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
640
640
  }
641
641
  };
642
- __publicField$6(_Cache, "instance", {});
642
+ __publicField$8(_Cache, "instance", {});
643
643
  let Cache = _Cache;
644
644
 
645
645
  var pkg = {
646
646
  name: "@nextgis/ngw-connector",
647
- version: "3.0.0-alpha.4",
647
+ version: "3.0.0-alpha.6",
648
648
  _priority: 12,
649
649
  description: "A lightweight HTTP client optimized for use with NextGIS Web API",
650
650
  main: "index.js",
@@ -653,15 +653,15 @@ var pkg = {
653
653
  jsdelivr: "lib/ngw-connector.global.prod.js",
654
654
  types: "lib/index.d.ts",
655
655
  dependencies: {
656
- "@nextgis/cache": "^3.0.0-alpha.4",
657
- "@nextgis/cancelable-promise": "^3.0.0-alpha.3",
658
- "@nextgis/utils": "^3.0.0-alpha.4",
656
+ "@nextgis/cache": "^3.0.0-alpha.5",
657
+ "@nextgis/cancelable-promise": "^3.0.0-alpha.5",
658
+ "@nextgis/utils": "^3.0.0-alpha.5",
659
659
  "@types/events": "^3.0.0",
660
660
  events: "*",
661
661
  "form-data": "^4.0.0"
662
662
  },
663
663
  devDependencies: {
664
- "@nextgis/build-tools": "^3.0.0-alpha.3"
664
+ "@nextgis/build-tools": "^3.0.0-alpha.5"
665
665
  },
666
666
  scripts: {
667
667
  clean: "rimraf ./lib",
@@ -695,87 +695,179 @@ var pkg = {
695
695
  type: "git",
696
696
  url: "git://github.com/nextgis/nextgis_frontend.git"
697
697
  },
698
+ engines: {
699
+ node: ">=18.20.4"
700
+ },
698
701
  gitHead: "edc68033f914f6c95c4125b9738bba6d36e990b4"
699
702
  };
700
703
 
701
- var __defProp$6 = Object.defineProperty;
702
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
703
- var __publicField$5 = (obj, key, value) => __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
704
+ const CONNECTORS = [];
705
+ function addConnector(connector) {
706
+ CONNECTORS.push(connector);
707
+ }
708
+ function findConnector(options) {
709
+ return CONNECTORS.find((x) => {
710
+ if (x.options.baseUrl === options.baseUrl) {
711
+ if (options.auth) {
712
+ if (x.options.auth) {
713
+ return objectDeepEqual(x.options.auth, options.auth);
714
+ }
715
+ } else {
716
+ return true;
717
+ }
718
+ }
719
+ });
720
+ }
721
+ function removeConnector(connector) {
722
+ const index = CONNECTORS.indexOf(connector);
723
+ if (index !== -1) {
724
+ CONNECTORS.splice(index, 1);
725
+ }
726
+ }
727
+
728
+ class AbortError extends Error {
729
+ constructor(message = "AbortError") {
730
+ super(message);
731
+ this.name = "AbortError";
732
+ }
733
+ }
734
+
735
+ var __defProp$a = Object.defineProperty;
736
+ var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
737
+ var __publicField$7 = (obj, key, value) => __defNormalProp$a(obj, typeof key !== "symbol" ? key + "" : key, value);
704
738
  class NgwError extends Error {
705
739
  constructor(er) {
706
740
  super();
707
- __publicField$5(this, "name", "NgwError");
708
- __publicField$5(this, "title");
709
- __publicField$5(this, "message");
710
- __publicField$5(this, "detail");
711
- __publicField$5(this, "exception");
712
- __publicField$5(this, "status_code");
713
- __publicField$5(this, "data");
714
- __publicField$5(this, "guru_meditation");
741
+ __publicField$7(this, "name", "NgwError");
742
+ __publicField$7(this, "title");
743
+ __publicField$7(this, "message");
744
+ __publicField$7(this, "detail");
745
+ __publicField$7(this, "exception");
746
+ __publicField$7(this, "status_code");
747
+ __publicField$7(this, "data");
748
+ __publicField$7(this, "guru_meditation");
715
749
  Object.assign(this, er);
716
750
  Object.setPrototypeOf(this, NgwError.prototype);
717
751
  }
718
752
  }
719
753
 
720
- var __defProp$5 = Object.defineProperty;
721
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
722
- var __publicField$4 = (obj, key, value) => __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
754
+ var __defProp$9 = Object.defineProperty;
755
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
756
+ var __publicField$6 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
757
+ class InsufficientPermissionsError extends NgwError {
758
+ constructor(obj) {
759
+ super(obj);
760
+ __publicField$6(this, "name", "InsufficientPermissionsError");
761
+ __publicField$6(this, "exception", "nextgisweb.core.exception.InsufficientPermissions");
762
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
763
+ }
764
+ }
765
+
766
+ var __defProp$8 = Object.defineProperty;
767
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
768
+ var __publicField$5 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
723
769
  class ResourceNotFoundError extends NgwError {
724
770
  constructor(obj) {
725
771
  super(obj);
726
- __publicField$4(this, "name", "ResourceNotFoundError");
727
- __publicField$4(this, "exception", "nextgisweb.resource.exception.ResourceNotFound");
772
+ __publicField$5(this, "name", "ResourceNotFoundError");
773
+ __publicField$5(this, "exception", "nextgisweb.resource.exception.ResourceNotFound");
728
774
  Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
729
775
  }
730
776
  }
731
777
 
732
- function isObject(val) {
733
- return Object.prototype.toString.call(val) === "[object Object]";
778
+ var __defProp$7 = Object.defineProperty;
779
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
780
+ var __publicField$4 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
781
+ class BaseAPIError extends Error {
782
+ constructor(message) {
783
+ super(message || "Something went wrong.");
784
+ __publicField$4(this, "title");
785
+ this.name = "BaseAPIError";
786
+ this.title = "Unknown API error";
787
+ if (Error.captureStackTrace) {
788
+ Error.captureStackTrace(this, BaseAPIError);
789
+ }
790
+ }
734
791
  }
735
-
736
- function resourceCompare(res1, res2) {
737
- return objectDeepEqual(res1, res2);
792
+ class NetworksResponseError extends BaseAPIError {
793
+ // prettier-ignore
794
+ constructor(message) {
795
+ super(message || "There is no response from the server or problem connecting to server.");
796
+ __publicField$4(this, "detail");
797
+ this.title = "Network error";
798
+ this.detail = "Check network connectivity and try again later.";
799
+ }
738
800
  }
739
-
740
- const exclude = ["description"];
741
- function resourceToQuery(resource, prefix = "") {
742
- prefix = prefix ? prefix + "__" : "";
743
- const query = {};
744
- for (const [key, value] of Object.entries(resource)) {
745
- if (exclude.indexOf(key) === -1) {
746
- if (isObject(value)) {
747
- if (key === "owner_user") {
748
- const children = resourceToQuery(value, key);
749
- Object.assign(query, children);
750
- } else if (key === "parent" && "id" in value) {
751
- query.parent_id = value.id;
752
- }
753
- } else if (defined(value)) {
754
- query[prefix + key] = value;
755
- }
801
+ class InvalidResponseError extends BaseAPIError {
802
+ constructor(message) {
803
+ super(message || "Something went wrong.");
804
+ this.title = "Unexpected server response";
805
+ }
806
+ }
807
+ class ServerResponseError extends BaseAPIError {
808
+ constructor(data) {
809
+ super(data.message);
810
+ __publicField$4(this, "detail");
811
+ __publicField$4(this, "data");
812
+ this.title = data.title || this.title;
813
+ this.detail = data.detail || null;
814
+ this.data = data;
815
+ }
816
+ }
817
+ class LunkwillError extends Error {
818
+ // prettier-ignore
819
+ constructor(message, data = {}) {
820
+ super(message || "Unexpected error while processing long-running request.");
821
+ __publicField$4(this, "title");
822
+ __publicField$4(this, "data");
823
+ this.name = "LunkwillError";
824
+ this.title = "Long-running request error";
825
+ this.data = data;
826
+ if (Error.captureStackTrace) {
827
+ Error.captureStackTrace(this, LunkwillError);
756
828
  }
757
829
  }
758
- return query;
830
+ }
831
+ class LunkwillRequestCancelled extends LunkwillError {
832
+ constructor(data) {
833
+ super("Long-running request was cancelled.", data);
834
+ }
835
+ }
836
+ class LunkwillRequestFailed extends LunkwillError {
837
+ constructor(data) {
838
+ super(void 0, data);
839
+ }
759
840
  }
760
841
 
761
- var __defProp$4 = Object.defineProperty;
762
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
763
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
764
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
765
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
766
- var __spreadValues$2 = (a, b) => {
842
+ var __defProp$6 = Object.defineProperty;
843
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
844
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
845
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
846
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
847
+ var __spreadValues$4 = (a, b) => {
767
848
  for (var prop in b || (b = {}))
768
- if (__hasOwnProp$2.call(b, prop))
769
- __defNormalProp$4(a, prop, b[prop]);
770
- if (__getOwnPropSymbols$2)
771
- for (var prop of __getOwnPropSymbols$2(b)) {
772
- if (__propIsEnum$2.call(b, prop))
773
- __defNormalProp$4(a, prop, b[prop]);
849
+ if (__hasOwnProp$4.call(b, prop))
850
+ __defNormalProp$6(a, prop, b[prop]);
851
+ if (__getOwnPropSymbols$4)
852
+ for (var prop of __getOwnPropSymbols$4(b)) {
853
+ if (__propIsEnum$4.call(b, prop))
854
+ __defNormalProp$6(a, prop, b[prop]);
774
855
  }
775
856
  return a;
776
857
  };
777
- var __publicField$3 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
778
- var __async$2 = (__this, __arguments, generator) => {
858
+ var __objRest$2 = (source, exclude) => {
859
+ var target = {};
860
+ for (var prop in source)
861
+ if (__hasOwnProp$4.call(source, prop) && exclude.indexOf(prop) < 0)
862
+ target[prop] = source[prop];
863
+ if (source != null && __getOwnPropSymbols$4)
864
+ for (var prop of __getOwnPropSymbols$4(source)) {
865
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$4.call(source, prop))
866
+ target[prop] = source[prop];
867
+ }
868
+ return target;
869
+ };
870
+ var __async$4 = (__this, __arguments, generator) => {
779
871
  return new Promise((resolve, reject) => {
780
872
  var fulfilled = (value) => {
781
873
  try {
@@ -795,288 +887,820 @@ var __async$2 = (__this, __arguments, generator) => {
795
887
  step((generator = generator.apply(__this, __arguments)).next());
796
888
  });
797
889
  };
798
- class ResourcesControl {
799
- constructor({
800
- connector,
801
- cacheId
802
- }) {
803
- __publicField$3(this, "cache");
804
- __publicField$3(this, "connector");
805
- this.connector = connector;
806
- this.cache = new Cache({ namespace: cacheId });
807
- }
808
- // -------------------------------------------------------------------------
809
- // Resource Methods
810
- // -------------------------------------------------------------------------
811
- /**
812
- * Receive resource from NGW by id, keyname or search-object parameter.
813
- * @param resource - Resource id, keyname or search-object
814
- *
815
- * @remarks
816
- * Fetching resource would be cached to speed up next call
817
- */
818
- getOne(resource, requestOptions) {
819
- const opt = __spreadValues$2({}, requestOptions);
820
- if (typeof resource === "string") ; else if (typeof resource === "number") ; else if (isObject(resource)) {
821
- if (resource.id !== void 0) {
822
- resource.id;
823
- } else {
824
- if (resource.keyname) {
825
- resource.keyname;
826
- }
827
- if (resource.display_name) {
828
- resource.display_name;
829
- }
890
+ function lunkwillCheckResponse(lwResp) {
891
+ const ct = lwResp.headers.get("content-type");
892
+ return ct !== void 0 && ct !== null && ct.includes("application/vnd.lunkwill.request-summary+json");
893
+ }
894
+ function responseJson(response) {
895
+ return __async$4(this, null, function* () {
896
+ try {
897
+ return response.json();
898
+ } catch (e) {
899
+ throw new Error();
900
+ }
901
+ });
902
+ }
903
+ function lunkwillResponseUrl(lwResp) {
904
+ return __async$4(this, null, function* () {
905
+ const lwData = yield responseJson(lwResp);
906
+ let delay = lwData.delay_ms;
907
+ const retry = lwData.retry_ms !== void 0 ? lwData.retry_ms : 2e3;
908
+ const sum = `/api/lunkwill/${lwData.id}/summary`;
909
+ const res = `/api/lunkwill/${lwData.id}/response`;
910
+ const sleep = (msec) => new Promise((resolve) => setTimeout(resolve, msec));
911
+ let failed = false;
912
+ let ready = false;
913
+ while (!ready) {
914
+ yield sleep(failed ? retry : delay);
915
+ failed = false;
916
+ let lwResp2;
917
+ let lwData2;
918
+ try {
919
+ lwResp2 = yield fetch(sum, { credentials: "same-origin" });
920
+ lwData2 = yield lwResp2.json();
921
+ } catch (e) {
922
+ failed = true;
923
+ continue;
924
+ }
925
+ switch (lwData2.status) {
926
+ case void 0:
927
+ throw new LunkwillError(void 0, lwData2);
928
+ case "ready":
929
+ ready = true;
930
+ break;
931
+ case "cancelled":
932
+ throw new LunkwillRequestCancelled(lwData2);
933
+ case "failed":
934
+ throw new LunkwillRequestFailed(lwData2);
935
+ case "spooled":
936
+ case "processing":
937
+ case "buffering":
938
+ delay = lwData2.delay_ms;
939
+ break;
940
+ default:
941
+ throw new LunkwillError(void 0, lwData2);
830
942
  }
831
943
  }
832
- if (typeof resource === "string") {
833
- return this._fetchResourceBy({ keyname: resource }, opt);
834
- } else if (typeof resource === "number") {
835
- return this._fetchResourceById(resource, opt);
836
- } else if (isObject(resource)) {
837
- return this._fetchResourceBy(resource, opt);
944
+ return res;
945
+ });
946
+ }
947
+ function lunkwillFetch(lwRespUrl) {
948
+ return __async$4(this, null, function* () {
949
+ try {
950
+ return yield window.fetch(lwRespUrl, { credentials: "same-origin" });
951
+ } catch (e) {
952
+ throw new NetworksResponseError();
953
+ }
954
+ });
955
+ }
956
+ const mediaContentTypes = [
957
+ "application/pdf",
958
+ "image/png",
959
+ "image/jpeg",
960
+ "image/tiff",
961
+ "text/csv"
962
+ ];
963
+ const mediaContentTypesRegex = new RegExp(mediaContentTypes.join("|"));
964
+ function isMediaContentType(contentType) {
965
+ return mediaContentTypesRegex.test(contentType);
966
+ }
967
+ function encodeQueryParams(value) {
968
+ const result = [];
969
+ for (const [k, v] of Object.entries(value)) {
970
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
971
+ result.push(`${k}=${encodeURIComponent(v)}`);
972
+ } else if (Array.isArray(v)) {
973
+ result.push(`${k}=${v.map(encodeURIComponent).join(",")}`);
974
+ } else {
975
+ for (const [sk, sv] of Object.entries(v)) {
976
+ const ske = `${k}[${encodeURIComponent(sk)}]`;
977
+ if (typeof sv === "string" || typeof sv === "number" || typeof sv === "boolean") {
978
+ result.push(`${ske}=${encodeURIComponent(sv)}`);
979
+ } else if (Array.isArray(sv)) {
980
+ const sve = sv.map(encodeURIComponent);
981
+ result.push(`${ske}=${sve.join(",")}`);
982
+ }
983
+ }
838
984
  }
839
- return Promise.resolve(void 0);
840
985
  }
841
- getOneOrFail(resource, requestOptions) {
842
- return this.getOne(resource, requestOptions).then((res) => {
843
- if (res) {
844
- return res;
986
+ return result.join("&");
987
+ }
988
+ function generateUrl(path, query) {
989
+ let urlParams = "";
990
+ if (query !== void 0) {
991
+ urlParams = "?" + encodeQueryParams(query);
992
+ }
993
+ return path + urlParams;
994
+ }
995
+ function request(path, options, cacheEngine) {
996
+ return __async$4(this, null, function* () {
997
+ var _b;
998
+ const defaults = {
999
+ method: "GET",
1000
+ credentials: "same-origin",
1001
+ headers: {}
1002
+ };
1003
+ const _a = __spreadValues$4(__spreadValues$4({}, defaults), options), {
1004
+ withCredentials,
1005
+ responseType,
1006
+ cacheProps,
1007
+ cacheName,
1008
+ lunkwill,
1009
+ cache,
1010
+ query,
1011
+ json
1012
+ } = _a, opt = __objRest$2(_a, [
1013
+ "withCredentials",
1014
+ "responseType",
1015
+ "cacheProps",
1016
+ "cacheName",
1017
+ "lunkwill",
1018
+ "cache",
1019
+ "query",
1020
+ "json"
1021
+ ]);
1022
+ if (withCredentials) {
1023
+ opt.credentials = "include";
1024
+ }
1025
+ let useLunkwill = false;
1026
+ if (lunkwill !== void 0) {
1027
+ lunkwill.toHeaders(opt.headers || {});
1028
+ useLunkwill = true;
1029
+ }
1030
+ const lunkwillReturnUrl = !!opt.lunkwillReturnUrl;
1031
+ delete opt.lunkwillReturnUrl;
1032
+ if (json !== void 0) {
1033
+ opt.body = JSON.stringify(json);
1034
+ const headers = opt.headers || {};
1035
+ headers["Content-Type"] = "application/json";
1036
+ opt.headers = headers;
1037
+ }
1038
+ const url = generateUrl(path, query);
1039
+ const makeRequest = () => __async$4(this, null, function* () {
1040
+ let response;
1041
+ try {
1042
+ response = yield fetch(url, opt);
1043
+ } catch (e) {
1044
+ if (e.name === "AbortError") {
1045
+ throw e;
1046
+ }
1047
+ throw new NetworksResponseError();
1048
+ }
1049
+ if (useLunkwill && lunkwillCheckResponse(response)) {
1050
+ const lwRespUrl = yield lunkwillResponseUrl(response);
1051
+ if (lunkwillReturnUrl) {
1052
+ return lwRespUrl;
1053
+ }
1054
+ response = yield lunkwillFetch(lwRespUrl);
1055
+ }
1056
+ const respCType = response.headers.get("content-type");
1057
+ const respJSON = respCType && (respCType.includes("application/json") || respCType.includes("application/vnd.lunkwill.request-summary+json"));
1058
+ let body;
1059
+ try {
1060
+ const respMedia = respCType && isMediaContentType(respCType);
1061
+ if (responseType === "blob" || respMedia) {
1062
+ body = yield response.blob();
1063
+ } else if (respJSON) {
1064
+ body = yield response.json();
1065
+ } else {
1066
+ throw new InvalidResponseError();
1067
+ }
1068
+ } catch (e) {
1069
+ if (e.name === "AbortError" || e instanceof InvalidResponseError) {
1070
+ throw e;
1071
+ }
1072
+ throw new InvalidResponseError();
1073
+ }
1074
+ if (400 <= response.status && response.status <= 599) {
1075
+ throw new ServerResponseError(body);
1076
+ }
1077
+ return body;
1078
+ });
1079
+ if (cacheEngine && cache && ((_b = opt.method) == null ? void 0 : _b.toUpperCase()) === "GET") {
1080
+ const cacheOptions = cacheProps ? cacheProps : __spreadValues$4({}, objectRemoveEmpty({
1081
+ withCredentials,
1082
+ responseType
1083
+ }));
1084
+ return cacheEngine.add(cacheName || url, makeRequest, cacheOptions, false);
1085
+ }
1086
+ return makeRequest();
1087
+ });
1088
+ }
1089
+
1090
+ var __defProp$5 = Object.defineProperty;
1091
+ var __defProps$1 = Object.defineProperties;
1092
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
1093
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
1094
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1095
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
1096
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1097
+ var __spreadValues$3 = (a, b) => {
1098
+ for (var prop in b || (b = {}))
1099
+ if (__hasOwnProp$3.call(b, prop))
1100
+ __defNormalProp$5(a, prop, b[prop]);
1101
+ if (__getOwnPropSymbols$3)
1102
+ for (var prop of __getOwnPropSymbols$3(b)) {
1103
+ if (__propIsEnum$3.call(b, prop))
1104
+ __defNormalProp$5(a, prop, b[prop]);
1105
+ }
1106
+ return a;
1107
+ };
1108
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1109
+ var __objRest$1 = (source, exclude) => {
1110
+ var target = {};
1111
+ for (var prop in source)
1112
+ if (__hasOwnProp$3.call(source, prop) && exclude.indexOf(prop) < 0)
1113
+ target[prop] = source[prop];
1114
+ if (source != null && __getOwnPropSymbols$3)
1115
+ for (var prop of __getOwnPropSymbols$3(source)) {
1116
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$3.call(source, prop))
1117
+ target[prop] = source[prop];
1118
+ }
1119
+ return target;
1120
+ };
1121
+ var __async$3 = (__this, __arguments, generator) => {
1122
+ return new Promise((resolve, reject) => {
1123
+ var fulfilled = (value) => {
1124
+ try {
1125
+ step(generator.next(value));
1126
+ } catch (e) {
1127
+ reject(e);
1128
+ }
1129
+ };
1130
+ var rejected = (value) => {
1131
+ try {
1132
+ step(generator.throw(value));
1133
+ } catch (e) {
1134
+ reject(e);
1135
+ }
1136
+ };
1137
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1138
+ step((generator = generator.apply(__this, __arguments)).next());
1139
+ });
1140
+ };
1141
+ function routeURL(name, baseUrl, routeData, ...rest) {
1142
+ const [template, ...params] = routeData[name];
1143
+ const first = rest[0];
1144
+ let sub;
1145
+ if (first === void 0) {
1146
+ sub = [];
1147
+ } else if (typeof first === "object" && first !== null) {
1148
+ if (rest.length > 1) {
1149
+ throw new Error("Too many arguments for route(name, object)!");
1150
+ }
1151
+ sub = [];
1152
+ for (const [p, v] of Object.entries(first)) {
1153
+ sub[params.indexOf(p)] = String(v);
1154
+ }
1155
+ } else {
1156
+ sub = rest.map((v) => String(v));
1157
+ }
1158
+ return fixUrlStr(
1159
+ baseUrl + template.replace(/\{(\w+)\}/g, function(m, a) {
1160
+ const idx = parseInt(a);
1161
+ const value = sub[idx];
1162
+ if (value === void 0) {
1163
+ const msg = `Undefined parameter ${idx} in "${template}".`;
1164
+ throw new Error(msg);
1165
+ }
1166
+ return String(value);
1167
+ })
1168
+ );
1169
+ }
1170
+ function route(name, connector, ...rest) {
1171
+ const result = {
1172
+ url: (opt) => __async$3(this, null, function* () {
1173
+ var _a;
1174
+ const routeData = yield connector.connect();
1175
+ const template = routeURL(
1176
+ name,
1177
+ (_a = connector.options.baseUrl) != null ? _a : "",
1178
+ routeData,
1179
+ ...rest
1180
+ );
1181
+ return generateUrl(template, opt == null ? void 0 : opt.query);
1182
+ })
1183
+ };
1184
+ const methods = ["get", "post", "put", "delete", "patch"];
1185
+ for (const method of methods) {
1186
+ const methodResp = (requestOptions) => __async$3(this, null, function* () {
1187
+ var _b;
1188
+ const _a = requestOptions || {}, { headers: optHeaders } = _a, restOpt = __objRest$1(_a, ["headers"]);
1189
+ const routeData = yield connector.connect();
1190
+ const template = routeURL(
1191
+ name,
1192
+ (_b = connector.options.baseUrl) != null ? _b : "",
1193
+ routeData,
1194
+ ...rest
1195
+ );
1196
+ const headers = objectRemoveEmpty(__spreadValues$3(__spreadValues$3({}, connector.getAuthorizationHeaders()), optHeaders != null ? optHeaders : {}));
1197
+ return request(
1198
+ template,
1199
+ __spreadProps$1(__spreadValues$3({
1200
+ headers
1201
+ }, restOpt), {
1202
+ method
1203
+ }),
1204
+ connector.cache
1205
+ );
1206
+ });
1207
+ result[method] = methodResp;
1208
+ }
1209
+ return result;
1210
+ }
1211
+
1212
+ var __defProp$4 = Object.defineProperty;
1213
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1214
+ var __publicField$3 = (obj, key, value) => __defNormalProp$4(obj, key + "" , value);
1215
+ class NetworkError extends Error {
1216
+ constructor(url) {
1217
+ super();
1218
+ __publicField$3(this, "name", "NetworkError");
1219
+ Object.setPrototypeOf(this, NetworkError.prototype);
1220
+ this.message = `Unable to request ${url}.
1221
+ Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`;
1222
+ }
1223
+ }
1224
+
1225
+ function isObject(val) {
1226
+ return Object.prototype.toString.call(val) === "[object Object]";
1227
+ }
1228
+
1229
+ let loadData;
1230
+ {
1231
+ loadData = (url, callback, options = {}, error, onCancel) => {
1232
+ options.method = options.method || "GET";
1233
+ const xhr = new XMLHttpRequest();
1234
+ xhr.open(options.method || "GET", url, true);
1235
+ if (options.responseType === "blob") {
1236
+ xhr.responseType = options.responseType;
1237
+ }
1238
+ const getResponseText = () => {
1239
+ try {
1240
+ return JSON.parse(xhr.responseText);
1241
+ } catch (er) {
1242
+ return xhr.responseText;
1243
+ }
1244
+ };
1245
+ const processingResponse = (forError = false) => {
1246
+ const cb = forError ? error : callback;
1247
+ if (options.responseType === "blob") {
1248
+ cb(xhr.response);
1249
+ } else {
1250
+ if (xhr.responseText) {
1251
+ cb(getResponseText());
1252
+ } else {
1253
+ error({ message: "" });
1254
+ }
1255
+ }
1256
+ };
1257
+ xhr.onload = () => {
1258
+ if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1259
+ error(new NgwError(getResponseText()));
1260
+ }
1261
+ processingResponse();
1262
+ };
1263
+ xhr.onerror = (er) => {
1264
+ if (xhr.status === 0) {
1265
+ error(new NetworkError(url));
1266
+ } else {
1267
+ error(er);
1268
+ }
1269
+ };
1270
+ xhr.upload.onprogress = function(e) {
1271
+ if (e.lengthComputable) {
1272
+ const percentComplete = e.loaded / e.total * 100;
1273
+ if (options.onProgress) {
1274
+ options.onProgress(percentComplete, e);
1275
+ }
1276
+ }
1277
+ };
1278
+ const headers = options.headers;
1279
+ if (headers) {
1280
+ for (const h in headers) {
1281
+ const header = headers[h];
1282
+ if (typeof header === "string") {
1283
+ xhr.setRequestHeader(h, header);
1284
+ }
1285
+ }
1286
+ }
1287
+ if (options.withCredentials !== void 0) {
1288
+ xhr.withCredentials = options.withCredentials;
1289
+ }
1290
+ let data;
1291
+ if (options.file) {
1292
+ data = new FormData();
1293
+ data.append("file", options.file);
1294
+ if (options.data) {
1295
+ for (const d in options.data) {
1296
+ data.append(d, data[d]);
1297
+ }
1298
+ }
1299
+ } else {
1300
+ data = options.data ? typeof options.data === "string" ? options.data : JSON.stringify(options.data) : null;
1301
+ }
1302
+ if (onCancel) {
1303
+ onCancel(() => {
1304
+ xhr.abort();
1305
+ });
1306
+ }
1307
+ xhr.send(data);
1308
+ };
1309
+ }
1310
+
1311
+ const templateRe = /\{ *([\w_-]+) *\}/g;
1312
+ function template(str, data) {
1313
+ return str.replace(templateRe, (s, key) => {
1314
+ let value = data[key];
1315
+ if (value === void 0) {
1316
+ throw new Error("No value provided for letiable " + s);
1317
+ } else if (typeof value === "function") {
1318
+ value = value(data);
1319
+ }
1320
+ return value;
1321
+ });
1322
+ }
1323
+
1324
+ var __defProp$3 = Object.defineProperty;
1325
+ var __defProps = Object.defineProperties;
1326
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1327
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
1328
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
1329
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
1330
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1331
+ var __spreadValues$2 = (a, b) => {
1332
+ for (var prop in b || (b = {}))
1333
+ if (__hasOwnProp$2.call(b, prop))
1334
+ __defNormalProp$3(a, prop, b[prop]);
1335
+ if (__getOwnPropSymbols$2)
1336
+ for (var prop of __getOwnPropSymbols$2(b)) {
1337
+ if (__propIsEnum$2.call(b, prop))
1338
+ __defNormalProp$3(a, prop, b[prop]);
1339
+ }
1340
+ return a;
1341
+ };
1342
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1343
+ var __objRest = (source, exclude) => {
1344
+ var target = {};
1345
+ for (var prop in source)
1346
+ if (__hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0)
1347
+ target[prop] = source[prop];
1348
+ if (source != null && __getOwnPropSymbols$2)
1349
+ for (var prop of __getOwnPropSymbols$2(source)) {
1350
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop))
1351
+ target[prop] = source[prop];
1352
+ }
1353
+ return target;
1354
+ };
1355
+ var __publicField$2 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
1356
+ var __async$2 = (__this, __arguments, generator) => {
1357
+ return new Promise((resolve, reject) => {
1358
+ var fulfilled = (value) => {
1359
+ try {
1360
+ step(generator.next(value));
1361
+ } catch (e) {
1362
+ reject(e);
1363
+ }
1364
+ };
1365
+ var rejected = (value) => {
1366
+ try {
1367
+ step(generator.throw(value));
1368
+ } catch (e) {
1369
+ reject(e);
1370
+ }
1371
+ };
1372
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1373
+ step((generator = generator.apply(__this, __arguments)).next());
1374
+ });
1375
+ };
1376
+ let ID = 0;
1377
+ let REQUEST_ID = 0;
1378
+ class NgwConnector {
1379
+ constructor(options) {
1380
+ this.options = options;
1381
+ __publicField$2(this, "id", ID++);
1382
+ __publicField$2(this, "emitter", new EventEmitter());
1383
+ __publicField$2(this, "user");
1384
+ __publicField$2(this, "cache");
1385
+ __publicField$2(this, "withCredentials");
1386
+ __publicField$2(this, "client", `NextGIS-NGW-Connector/${pkg.version}`);
1387
+ __publicField$2(this, "routeStr", "/api/component/pyramid/route");
1388
+ __publicField$2(this, "activeRequests", {});
1389
+ __publicField$2(this, "requestTransform");
1390
+ const exist = findConnector(options);
1391
+ this.cache = new Cache({ namespace: options.cacheId });
1392
+ if (exist) {
1393
+ return exist;
1394
+ } else {
1395
+ const { route: route2, requestTransform, withCredentials } = this.options;
1396
+ if (route2) {
1397
+ this.routeStr = route2;
1398
+ }
1399
+ if (requestTransform) {
1400
+ this.requestTransform = requestTransform;
1401
+ }
1402
+ if (withCredentials !== void 0) {
1403
+ this.withCredentials = withCredentials;
1404
+ }
1405
+ addConnector(this);
1406
+ }
1407
+ }
1408
+ static create(options) {
1409
+ return new this(options);
1410
+ }
1411
+ /**
1412
+ * Clear the cache.
1413
+ */
1414
+ clearCache() {
1415
+ this.cache.clean();
1416
+ }
1417
+ setRequestTransform(requestTransform) {
1418
+ this.requestTransform = requestTransform;
1419
+ }
1420
+ /**
1421
+ * Fast way to specify the connection address to NextGIS Web.
1422
+ * The current connection will be severed.
1423
+ * @param baseUrl - NGW url
1424
+ */
1425
+ setNgw(baseUrl) {
1426
+ this.logout();
1427
+ this.options.baseUrl = baseUrl;
1428
+ addConnector(this);
1429
+ }
1430
+ /**
1431
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
1432
+ * @remarks
1433
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1434
+ * Can be used to check connection.
1435
+ * @example
1436
+ * ```javascript
1437
+ * const connector = new NgwConnector({ baseUrl: 'https://demo.nextgis.com' });
1438
+ * connector.connect()
1439
+ * .then(() => console.log('Ok'))
1440
+ * .catch((er) => console.log('Connection problem', er));
1441
+ * ```
1442
+ */
1443
+ connect() {
1444
+ return __async$2(this, null, function* () {
1445
+ const auth = this.options.auth;
1446
+ if (auth) {
1447
+ const { login, password } = auth;
1448
+ if (login && password) {
1449
+ yield this._login({ login, password });
1450
+ }
1451
+ }
1452
+ const routeUrl = `${this.routeStr}?client=${this.client}`;
1453
+ return yield this.makeQuery(
1454
+ routeUrl,
1455
+ {},
1456
+ {
1457
+ cacheName: "route",
1458
+ cache: true,
1459
+ cacheProps: {
1460
+ id: this.id,
1461
+ auth,
1462
+ baseUrl: this.options.baseUrl
1463
+ }
1464
+ }
1465
+ );
1466
+ });
1467
+ }
1468
+ /**
1469
+ * Quick way to change NextGIS Web user.
1470
+ * @param credentials - New user credentials
1471
+ */
1472
+ login(credentials, options) {
1473
+ this.logout();
1474
+ addConnector(this);
1475
+ return this._login(credentials, options);
1476
+ }
1477
+ /**
1478
+ * Disconnecting a user. Aborting all current requests
1479
+ */
1480
+ logout() {
1481
+ this.abort();
1482
+ removeConnector(this);
1483
+ this.options.auth = void 0;
1484
+ this.user = void 0;
1485
+ this.clearCache();
1486
+ this.emitter.emit("logout");
1487
+ }
1488
+ getUserInfo(credentials, options) {
1489
+ return __async$2(this, null, function* () {
1490
+ if (this.user && this.user.id) {
1491
+ return this.user;
845
1492
  }
846
- throw new ResourceNotFoundError();
1493
+ if (credentials) {
1494
+ this.options.auth = credentials;
1495
+ }
1496
+ const options_ = __spreadValues$2({
1497
+ headers: this.getAuthorizationHeaders(credentials),
1498
+ cache: true
1499
+ }, options);
1500
+ return this.makeQuery(
1501
+ "/api/component/auth/current_user",
1502
+ {},
1503
+ options_
1504
+ );
847
1505
  });
848
1506
  }
849
1507
  /**
850
- * A fast way to retrieve resource ID for any resource definition.
851
- * @param resource - Any available resource definition
852
- *
853
- * @remarks
854
- * There are situations when exactly the resource id is needed
855
- * (for example, to compose the correct request to the api)
856
- * then this method will come in handy to facilitate the extraction of the identifier
857
- * if the resource is specified through a keyname or other parameters.
1508
+ * Obtaining the required Headers for authentication of requests in the NGW.
858
1509
  */
859
- getId(resource, requestOptions) {
860
- if (typeof resource === "number") {
861
- return Promise.resolve(resource);
862
- } else if (typeof resource === "string" || isObject(resource)) {
863
- return this.getOne(resource, requestOptions).then((res) => {
864
- if (res) {
865
- return res.resource.id;
866
- }
867
- });
1510
+ getAuthorizationHeaders(credentials) {
1511
+ const client = this.makeClientId(credentials);
1512
+ if (client) {
1513
+ return {
1514
+ Authorization: `Basic ${client}`
1515
+ };
868
1516
  }
869
- return Promise.resolve(void 0);
870
- }
871
- /**
872
- * A fast way to retrieve resource ID for any resource definition.
873
- * @param resource - Any available resource definition
874
- *
875
- * @remarks
876
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
877
- * To not make one more checks if the resource is definitely exists
878
- */
879
- getIdOrFail(resource, requestOptions) {
880
- return this.getId(resource, requestOptions).then((resp) => {
881
- if (resp === void 0) {
882
- throw new Error();
883
- }
884
- return resp;
885
- });
1517
+ return {};
886
1518
  }
887
- getMany(resource, requestOptions) {
888
- return this._resourceCacheFilter(resource).then((items) => {
889
- if (!items.length) {
890
- const query = {};
891
- if (resource.keyname) {
892
- query.keyname = resource.keyname;
893
- } else {
894
- Object.assign(query, resourceToQuery(resource));
895
- }
896
- return this.connector.get("resource.search", requestOptions, __spreadValues$2({
897
- serialization: "full"
898
- }, query)).then((resources) => {
899
- if ((requestOptions == null ? void 0 : requestOptions.cache) && resources) {
900
- for (const x of resources) {
901
- this.cache.add("resource.item", Promise.resolve(x), {
902
- id: x.resource.id
903
- });
904
- }
905
- }
906
- return resources;
907
- });
1519
+ makeClientId(credentials) {
1520
+ credentials = credentials || this.options.auth;
1521
+ if (credentials) {
1522
+ const { login, password } = credentials;
1523
+ const encodedStr = [login, password].map(encodeURIComponent).join(":");
1524
+ {
1525
+ return window.btoa(encodedStr);
908
1526
  }
909
- return items;
910
- });
1527
+ }
911
1528
  }
912
- getParent(resource, requestOptions) {
913
- return this.getOne(resource, requestOptions).then((child) => {
914
- if (child) {
915
- return this.getOne(child.resource.parent.id, requestOptions);
916
- }
917
- return Promise.resolve(void 0);
918
- });
1529
+ /** Stop all api requests */
1530
+ abort() {
1531
+ for (const abortController of Object.values(this.activeRequests)) {
1532
+ abortController.abort();
1533
+ }
1534
+ this.activeRequests = {};
919
1535
  }
920
- getChildrenOf(resource, requestOptions) {
921
- return this.getIdOrFail(resource).then(
922
- (parent) => this._getChildrenOf(parent, requestOptions)
923
- );
1536
+ getActiveApiRequests() {
1537
+ return __spreadValues$2({}, this.activeRequests);
924
1538
  }
925
- update(resource, data) {
926
- return this.getId(resource).then((id) => {
927
- if (id !== void 0) {
928
- return this.connector.put("resource.item", { data }, { id });
929
- }
930
- });
1539
+ route(name, ...rest) {
1540
+ return route(name, this, ...rest);
931
1541
  }
932
1542
  /**
933
- * Fast way to delete resource from NGW and clean cache.
934
- * @param resource - Resource definition
1543
+ * Send request to NGW.
1544
+ * @param url - URL address to NGW
1545
+ * @param params - Query params
1546
+ * @param options - Request options
935
1547
  */
936
- delete(resource) {
937
- return this.getId(resource).then((id) => {
938
- if (id !== void 0) {
939
- return this.connector.delete("resource.item", null, { id }).then(() => {
940
- this._cleanResourceItemCache(id);
941
- return void 0;
942
- });
1548
+ makeQuery(_0, _1) {
1549
+ return __async$2(this, arguments, function* (url, params, options = {}) {
1550
+ var _b;
1551
+ url = (this.options.baseUrl ? this.options.baseUrl : "") + url;
1552
+ if (!url) {
1553
+ throw new Error("Empty `url` not allowed");
943
1554
  }
944
- });
945
- }
946
- _getChildrenOf(parent, requestOptions, _items = []) {
947
- return this.connector.get("resource.collection", requestOptions, {
948
- parent
949
- }).then((items) => {
950
- const recursivePromises = [];
951
- for (const item of items) {
952
- if (requestOptions == null ? void 0 : requestOptions.cache) {
953
- this.cache.add("resource.item", Promise.resolve(item), {
954
- id: item.resource.id
955
- });
956
- }
957
- _items.push(item);
958
- if ((requestOptions == null ? void 0 : requestOptions.recursive) && item.resource.children) {
959
- recursivePromises.push(
960
- this._getChildrenOf(item.resource.id, requestOptions, _items)
961
- );
1555
+ if (params) {
1556
+ const _a = params, restParams = __objRest(_a, ["paramList"]);
1557
+ url = template(url, restParams);
1558
+ }
1559
+ url = encodeURI(fixUrlStr(url));
1560
+ options = __spreadValues$2({ withCredentials: this.withCredentials }, options);
1561
+ const {
1562
+ cache,
1563
+ signal: externalSignal,
1564
+ method = "GET",
1565
+ headers,
1566
+ cacheName,
1567
+ cacheProps,
1568
+ responseType,
1569
+ withCredentials
1570
+ } = options;
1571
+ const internalAbortController = new AbortController();
1572
+ const internalSignal = internalAbortController.signal;
1573
+ if (externalSignal) {
1574
+ if (externalSignal.aborted) {
1575
+ throw new AbortError();
962
1576
  }
1577
+ externalSignal.addEventListener("abort", () => {
1578
+ internalAbortController.abort();
1579
+ });
963
1580
  }
964
- if (recursivePromises.length) {
965
- return Promise.all(recursivePromises).then(() => {
966
- return _items;
1581
+ options.signal = internalSignal;
1582
+ const createPromise = () => __async$2(this, null, function* () {
1583
+ const id = REQUEST_ID++;
1584
+ this.activeRequests[id] = internalAbortController;
1585
+ try {
1586
+ return this._loadData(url, options);
1587
+ } finally {
1588
+ this._cleanActiveRequest(id);
1589
+ }
1590
+ });
1591
+ if (cache && method === "GET") {
1592
+ const cacheOptions = cacheProps ? cacheProps : __spreadProps(__spreadValues$2({}, objectRemoveEmpty({
1593
+ headers,
1594
+ withCredentials,
1595
+ responseType,
1596
+ baseUrl: this.options.baseUrl,
1597
+ userId: (_b = this.user) == null ? void 0 : _b.id
1598
+ })), {
1599
+ params
967
1600
  });
1601
+ return this.cache.add(
1602
+ cacheName || url,
1603
+ createPromise,
1604
+ cacheOptions,
1605
+ false
1606
+ );
968
1607
  }
969
- return _items;
1608
+ return createPromise();
970
1609
  });
971
1610
  }
972
- _cleanResourceItemCache(id) {
973
- return __async$2(this, null, function* () {
1611
+ _loadData(url, options) {
1612
+ options.responseType = options.responseType || "json";
1613
+ return new Promise((resolve, reject) => {
974
1614
  var _a;
975
- const all = this.cache.all();
976
- const toDelete = [];
977
- for (const c of all) {
978
- const cid = (_a = c.props) == null ? void 0 : _a.id;
979
- if (["resource.item", "resource"].includes(c.key) && cid !== void 0) {
980
- if (typeof cid === "number") {
981
- if (cid === id) {
982
- toDelete.push(c);
983
- }
984
- } else {
985
- const rid = yield this.getId(cid);
986
- if (rid === id) {
987
- toDelete.push(c);
988
- }
989
- }
990
- }
1615
+ if (this.user) {
1616
+ options = options || {};
1617
+ options.headers = __spreadValues$2(__spreadValues$2({}, this.getAuthorizationHeaders()), options.headers);
991
1618
  }
992
- for (const d of toDelete) {
993
- this.cache.delete(d);
1619
+ if (this.requestTransform) {
1620
+ const [transUrl, transOptions] = this.requestTransform(url, options);
1621
+ url = transUrl;
1622
+ options = transOptions;
1623
+ }
1624
+ let runOnAbort = void 0;
1625
+ loadData(url, resolve, options, reject, (handler) => {
1626
+ runOnAbort = handler;
1627
+ });
1628
+ (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
1629
+ if (runOnAbort !== void 0) {
1630
+ runOnAbort();
1631
+ }
1632
+ reject(new AbortError());
1633
+ });
1634
+ }).catch((httpError) => {
1635
+ if (httpError.name !== "AbortError") {
1636
+ {
1637
+ console.warn("DEV WARN", httpError);
1638
+ }
1639
+ const er = this._handleHttpError(httpError);
1640
+ if (er) {
1641
+ throw er;
1642
+ }
994
1643
  }
1644
+ throw httpError;
995
1645
  });
996
1646
  }
997
- _fetchResourceById(id, requestOptions) {
998
- return this.connector.get("resource.item", requestOptions, { id });
999
- }
1000
- _fetchResourceBy(resource, requestOptions) {
1001
- return this.getMany(resource, requestOptions).then((resources) => {
1002
- return resources[0];
1647
+ _login(credentials, options) {
1648
+ return __async$2(this, null, function* () {
1649
+ try {
1650
+ const data = yield this.getUserInfo(credentials, options);
1651
+ this.user = data;
1652
+ this.emitter.emit("login", data);
1653
+ return data;
1654
+ } catch (er) {
1655
+ this.emitter.emit("login:error", er);
1656
+ throw er;
1657
+ }
1003
1658
  });
1004
1659
  }
1005
- _resourceCacheFilter(resource) {
1006
- return Promise.all(this.cache.matchAll("resource.item")).then(
1007
- (resources) => {
1008
- const items = [];
1009
- resources.filter((x) => {
1010
- if (x) {
1011
- if (resource.keyname && x.resource.keyname) {
1012
- return resource.keyname === x.resource.keyname;
1013
- }
1014
- if (defined(resource.id) && defined(x.resource.id)) {
1015
- return resource.id === x.resource.id;
1016
- }
1017
- return resourceCompare(resource, x.resource);
1018
- }
1019
- });
1020
- return items;
1021
- }
1022
- );
1660
+ _cleanActiveRequest(requestId) {
1661
+ delete this.activeRequests[requestId];
1023
1662
  }
1024
- }
1025
-
1026
- const CONNECTORS = [];
1027
- function addConnector(connector) {
1028
- CONNECTORS.push(connector);
1029
- }
1030
- function findConnector(options) {
1031
- return CONNECTORS.find((x) => {
1032
- if (x.options.baseUrl === options.baseUrl) {
1033
- if (options.auth) {
1034
- if (x.options.auth) {
1035
- return objectDeepEqual(x.options.auth, options.auth);
1663
+ _handleHttpError(er) {
1664
+ if (er) {
1665
+ if (er instanceof NgwError) {
1666
+ if (er.exception === "nextgisweb.resource.exception.ResourceNotFound") {
1667
+ throw new ResourceNotFoundError(er);
1668
+ } else if (er.exception === "nextgisweb.core.exception.InsufficientPermissions") {
1669
+ throw new InsufficientPermissionsError(er);
1036
1670
  }
1037
- } else {
1038
- return true;
1039
1671
  }
1040
1672
  }
1041
- });
1042
- }
1043
- function removeConnector(connector) {
1044
- const index = CONNECTORS.indexOf(connector);
1045
- if (index !== -1) {
1046
- CONNECTORS.splice(index, 1);
1047
- }
1048
- }
1049
-
1050
- class AbortError extends Error {
1051
- constructor(message = "AbortError") {
1052
- super(message);
1053
- this.name = "AbortError";
1673
+ return er;
1054
1674
  }
1055
1675
  }
1676
+ __publicField$2(NgwConnector, "errors", {
1677
+ NgwError,
1678
+ ResourceNotFoundError
1679
+ });
1056
1680
 
1057
- var __defProp$3 = Object.defineProperty;
1058
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1059
- var __publicField$2 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
1060
- class InsufficientPermissionsError extends NgwError {
1061
- constructor(obj) {
1062
- super(obj);
1063
- __publicField$2(this, "name", "InsufficientPermissionsError");
1064
- __publicField$2(this, "exception", "nextgisweb.core.exception.InsufficientPermissions");
1065
- Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1066
- }
1681
+ function resourceCompare(res1, res2) {
1682
+ return objectDeepEqual(res1, res2);
1067
1683
  }
1068
1684
 
1069
- const templateRe = /\{ *([\w_-]+) *\}/g;
1070
- function template(str, data) {
1071
- return str.replace(templateRe, (s, key) => {
1072
- let value = data[key];
1073
- if (value === void 0) {
1074
- throw new Error("No value provided for letiable " + s);
1075
- } else if (typeof value === "function") {
1076
- value = value(data);
1685
+ const exclude = ["description"];
1686
+ function resourceToQuery(resource, prefix = "") {
1687
+ prefix = prefix ? prefix + "__" : "";
1688
+ const query = {};
1689
+ for (const [key, value] of Object.entries(resource)) {
1690
+ if (exclude.indexOf(key) === -1) {
1691
+ if (isObject(value)) {
1692
+ if (key === "owner_user") {
1693
+ const children = resourceToQuery(value, key);
1694
+ Object.assign(query, children);
1695
+ } else if (key === "parent" && "id" in value) {
1696
+ query.parent_id = value.id;
1697
+ }
1698
+ } else if (defined(value)) {
1699
+ query[prefix + key] = value;
1700
+ }
1077
1701
  }
1078
- return value;
1079
- });
1702
+ }
1703
+ return query;
1080
1704
  }
1081
1705
 
1082
1706
  var __defProp$2 = Object.defineProperty;
@@ -1095,6 +1719,7 @@ var __spreadValues$1 = (a, b) => {
1095
1719
  }
1096
1720
  return a;
1097
1721
  };
1722
+ var __publicField$1 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1098
1723
  var __async$1 = (__this, __arguments, generator) => {
1099
1724
  return new Promise((resolve, reject) => {
1100
1725
  var fulfilled = (value) => {
@@ -1115,184 +1740,250 @@ var __async$1 = (__this, __arguments, generator) => {
1115
1740
  step((generator = generator.apply(__this, __arguments)).next());
1116
1741
  });
1117
1742
  };
1118
- function apiRequest(opt) {
1119
- return __async$1(this, null, function* () {
1120
- const { params, name, connector, requestOptions } = opt;
1121
- const apiItems = yield connector.connect();
1122
- let apiItem = apiItems && apiItems[name];
1123
- if (apiItem) {
1124
- apiItem = [...apiItem];
1125
- let url = apiItem.shift();
1126
- if (apiItem.length) {
1127
- const replaceParams = {};
1128
- for (let fry = 0; fry < apiItem.length; fry++) {
1129
- const arg = apiItem[fry];
1130
- replaceParams[fry] = `{${arg}}`;
1131
- if (params[arg] === void 0) {
1132
- throw new Error(`\`${arg}\` URL API argument is not specified`);
1133
- }
1134
- }
1135
- if (url) {
1136
- url = template(url, replaceParams);
1137
- }
1138
- }
1139
- if (params) {
1140
- const paramArray = [];
1141
- const paramList = params.paramList;
1142
- if (Array.isArray(paramList)) {
1143
- paramList.forEach(([key, value]) => {
1144
- paramArray.push(`${key}=${value}`);
1145
- });
1146
- }
1147
- for (const p in params) {
1148
- if (apiItem.indexOf(p) === -1) {
1149
- paramArray.push(`${p}=${params[p]}`);
1150
- }
1743
+ class ResourcesControl {
1744
+ constructor({
1745
+ connector,
1746
+ cacheId
1747
+ }) {
1748
+ __publicField$1(this, "cache");
1749
+ __publicField$1(this, "connector");
1750
+ this.connector = connector;
1751
+ this.cache = new Cache({ namespace: cacheId });
1752
+ }
1753
+ // -------------------------------------------------------------------------
1754
+ // Resource Methods
1755
+ // -------------------------------------------------------------------------
1756
+ /**
1757
+ * Receive resource from NGW by id, keyname or search-object parameter.
1758
+ * @param resource - Resource id, keyname or search-object
1759
+ *
1760
+ * @remarks
1761
+ * Fetching resource would be cached to speed up next call
1762
+ */
1763
+ getOne(resource, requestOptions) {
1764
+ const opt = __spreadValues$1({}, requestOptions);
1765
+ if (typeof resource === "string") ; else if (typeof resource === "number") ; else if (isObject(resource)) {
1766
+ if (resource.id !== void 0) {
1767
+ resource.id;
1768
+ } else {
1769
+ if (resource.keyname) {
1770
+ resource.keyname;
1151
1771
  }
1152
- if (paramArray.length) {
1153
- url = `${url}?${paramArray.join("&")}`;
1772
+ if (resource.display_name) {
1773
+ resource.display_name;
1154
1774
  }
1155
1775
  }
1156
- if (url) {
1157
- return connector.makeQuery(url, params, __spreadValues$1({
1158
- cacheName: name
1159
- }, requestOptions));
1160
- } else {
1161
- throw new Error("Request URL is not set");
1162
- }
1163
- } else {
1164
- return void 0;
1165
1776
  }
1166
- });
1167
- }
1168
-
1169
- var __defProp$1 = Object.defineProperty;
1170
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1171
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, key + "" , value);
1172
- class NetworkError extends Error {
1173
- constructor(url) {
1174
- super();
1175
- __publicField$1(this, "name", "NetworkError");
1176
- Object.setPrototypeOf(this, NetworkError.prototype);
1177
- this.message = `Unable to request ${url}.
1178
- Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`;
1179
- }
1180
- }
1181
-
1182
- let loadData;
1183
- {
1184
- loadData = (url, callback, options = {}, error, onCancel) => {
1185
- options.method = options.method || "GET";
1186
- const xhr = new XMLHttpRequest();
1187
- xhr.open(options.method || "GET", url, true);
1188
- if (options.responseType === "blob") {
1189
- xhr.responseType = options.responseType;
1777
+ if (typeof resource === "string") {
1778
+ return this._fetchResourceBy({ keyname: resource }, opt);
1779
+ } else if (typeof resource === "number") {
1780
+ return this._fetchResourceById(resource, opt);
1781
+ } else if (isObject(resource)) {
1782
+ return this._fetchResourceBy(resource, opt);
1190
1783
  }
1191
- const getResponseText = () => {
1192
- try {
1193
- return JSON.parse(xhr.responseText);
1194
- } catch (er) {
1195
- return xhr.responseText;
1784
+ return Promise.resolve(void 0);
1785
+ }
1786
+ getOneOrFail(resource, requestOptions) {
1787
+ return this.getOne(resource, requestOptions).then((res) => {
1788
+ if (res) {
1789
+ return res;
1196
1790
  }
1197
- };
1198
- const processingResponse = (forError = false) => {
1199
- const cb = forError ? error : callback;
1200
- if (options.responseType === "blob") {
1201
- cb(xhr.response);
1202
- } else {
1203
- if (xhr.responseText) {
1204
- cb(getResponseText());
1791
+ throw new ResourceNotFoundError();
1792
+ });
1793
+ }
1794
+ /**
1795
+ * A fast way to retrieve resource ID for any resource definition.
1796
+ * @param resource - Any available resource definition
1797
+ *
1798
+ * @remarks
1799
+ * There are situations when exactly the resource id is needed
1800
+ * (for example, to compose the correct request to the api)
1801
+ * then this method will come in handy to facilitate the extraction of the identifier
1802
+ * if the resource is specified through a keyname or other parameters.
1803
+ */
1804
+ getId(resource, requestOptions) {
1805
+ if (typeof resource === "number") {
1806
+ return Promise.resolve(resource);
1807
+ } else if (typeof resource === "string" || isObject(resource)) {
1808
+ return this.getOne(resource, requestOptions).then((res) => {
1809
+ if (res) {
1810
+ return res.resource.id;
1811
+ }
1812
+ });
1813
+ }
1814
+ return Promise.resolve(void 0);
1815
+ }
1816
+ /**
1817
+ * A fast way to retrieve resource ID for any resource definition.
1818
+ * @param resource - Any available resource definition
1819
+ *
1820
+ * @remarks
1821
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1822
+ * To not make one more checks if the resource is definitely exists
1823
+ */
1824
+ getIdOrFail(resource, requestOptions) {
1825
+ return this.getId(resource, requestOptions).then((resp) => {
1826
+ if (resp === void 0) {
1827
+ throw new Error();
1828
+ }
1829
+ return resp;
1830
+ });
1831
+ }
1832
+ getMany(resource, requestOptions) {
1833
+ return this._resourceCacheFilter(resource).then((items) => {
1834
+ if (!items.length) {
1835
+ const query = {};
1836
+ if (resource.keyname) {
1837
+ query.keyname = resource.keyname;
1205
1838
  } else {
1206
- error({ message: "" });
1839
+ Object.assign(query, resourceToQuery(resource));
1207
1840
  }
1841
+ return this.connector.get("resource.search", requestOptions, __spreadValues$1({
1842
+ serialization: "full"
1843
+ }, query)).then((resources) => {
1844
+ if ((requestOptions == null ? void 0 : requestOptions.cache) && resources) {
1845
+ for (const x of resources) {
1846
+ this.cache.add("resource.item", Promise.resolve(x), {
1847
+ id: x.resource.id
1848
+ });
1849
+ }
1850
+ }
1851
+ return resources;
1852
+ });
1208
1853
  }
1209
- };
1210
- xhr.onload = () => {
1211
- if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1212
- error(new NgwError(getResponseText()));
1854
+ return items;
1855
+ });
1856
+ }
1857
+ getParent(resource, requestOptions) {
1858
+ return this.getOne(resource, requestOptions).then((child) => {
1859
+ if (child) {
1860
+ return this.getOne(child.resource.parent.id, requestOptions);
1213
1861
  }
1214
- processingResponse();
1215
- };
1216
- xhr.onerror = (er) => {
1217
- if (xhr.status === 0) {
1218
- error(new NetworkError(url));
1219
- } else {
1220
- error(er);
1862
+ return Promise.resolve(void 0);
1863
+ });
1864
+ }
1865
+ getChildrenOf(resource, requestOptions) {
1866
+ return this.getIdOrFail(resource).then(
1867
+ (parent) => this._getChildrenOf(parent, requestOptions)
1868
+ );
1869
+ }
1870
+ update(resource, data) {
1871
+ return this.getId(resource).then((id) => {
1872
+ if (id !== void 0) {
1873
+ return this.connector.put("resource.item", { data }, { id });
1221
1874
  }
1222
- };
1223
- xhr.upload.onprogress = function(e) {
1224
- if (e.lengthComputable) {
1225
- const percentComplete = e.loaded / e.total * 100;
1226
- if (options.onProgress) {
1227
- options.onProgress(percentComplete, e);
1228
- }
1875
+ });
1876
+ }
1877
+ /**
1878
+ * Fast way to delete resource from NGW and clean cache.
1879
+ * @param resource - Resource definition
1880
+ */
1881
+ delete(resource) {
1882
+ return this.getId(resource).then((id) => {
1883
+ if (id !== void 0) {
1884
+ return this.connector.delete("resource.item", null, { id }).then(() => {
1885
+ this._cleanResourceItemCache(id);
1886
+ return void 0;
1887
+ });
1229
1888
  }
1230
- };
1231
- const headers = options.headers;
1232
- if (headers) {
1233
- for (const h in headers) {
1234
- const header = headers[h];
1235
- if (typeof header === "string") {
1236
- xhr.setRequestHeader(h, header);
1889
+ });
1890
+ }
1891
+ _getChildrenOf(parent, requestOptions, _items = []) {
1892
+ return this.connector.get("resource.collection", requestOptions, {
1893
+ parent
1894
+ }).then((items) => {
1895
+ const recursivePromises = [];
1896
+ for (const item of items) {
1897
+ if (requestOptions == null ? void 0 : requestOptions.cache) {
1898
+ this.cache.add("resource.item", Promise.resolve(item), {
1899
+ id: item.resource.id
1900
+ });
1901
+ }
1902
+ _items.push(item);
1903
+ if ((requestOptions == null ? void 0 : requestOptions.recursive) && item.resource.children) {
1904
+ recursivePromises.push(
1905
+ this._getChildrenOf(item.resource.id, requestOptions, _items)
1906
+ );
1237
1907
  }
1238
1908
  }
1239
- }
1240
- if (options.withCredentials !== void 0) {
1241
- xhr.withCredentials = options.withCredentials;
1242
- }
1243
- let data;
1244
- if (options.file) {
1245
- data = new FormData();
1246
- data.append("file", options.file);
1247
- if (options.data) {
1248
- for (const d in options.data) {
1249
- data.append(d, data[d]);
1909
+ if (recursivePromises.length) {
1910
+ return Promise.all(recursivePromises).then(() => {
1911
+ return _items;
1912
+ });
1913
+ }
1914
+ return _items;
1915
+ });
1916
+ }
1917
+ _cleanResourceItemCache(id) {
1918
+ return __async$1(this, null, function* () {
1919
+ var _a;
1920
+ const all = this.cache.all();
1921
+ const toDelete = [];
1922
+ for (const c of all) {
1923
+ const cid = (_a = c.props) == null ? void 0 : _a.id;
1924
+ if (["resource.item", "resource"].includes(c.key) && cid !== void 0) {
1925
+ if (typeof cid === "number") {
1926
+ if (cid === id) {
1927
+ toDelete.push(c);
1928
+ }
1929
+ } else {
1930
+ const rid = yield this.getId(cid);
1931
+ if (rid === id) {
1932
+ toDelete.push(c);
1933
+ }
1934
+ }
1250
1935
  }
1251
1936
  }
1252
- } else {
1253
- data = options.data ? typeof options.data === "string" ? options.data : JSON.stringify(options.data) : null;
1254
- }
1255
- if (onCancel) {
1256
- onCancel(() => {
1257
- xhr.abort();
1258
- });
1259
- }
1260
- xhr.send(data);
1261
- };
1937
+ for (const d of toDelete) {
1938
+ this.cache.delete(d);
1939
+ }
1940
+ });
1941
+ }
1942
+ _fetchResourceById(id, requestOptions) {
1943
+ return this.connector.get("resource.item", requestOptions, { id });
1944
+ }
1945
+ _fetchResourceBy(resource, requestOptions) {
1946
+ return this.getMany(resource, requestOptions).then((resources) => {
1947
+ return resources[0];
1948
+ });
1949
+ }
1950
+ _resourceCacheFilter(resource) {
1951
+ return Promise.all(this.cache.matchAll("resource.item")).then(
1952
+ (resources) => {
1953
+ const items = [];
1954
+ resources.filter((x) => {
1955
+ if (x) {
1956
+ if (resource.keyname && x.resource.keyname) {
1957
+ return resource.keyname === x.resource.keyname;
1958
+ }
1959
+ if (defined(resource.id) && defined(x.resource.id)) {
1960
+ return resource.id === x.resource.id;
1961
+ }
1962
+ return resourceCompare(resource, x.resource);
1963
+ }
1964
+ });
1965
+ return items;
1966
+ }
1967
+ );
1968
+ }
1262
1969
  }
1263
1970
 
1264
- var __defProp = Object.defineProperty;
1265
- var __defProps = Object.defineProperties;
1266
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1971
+ var __defProp$1 = Object.defineProperty;
1267
1972
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1268
1973
  var __hasOwnProp = Object.prototype.hasOwnProperty;
1269
1974
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
1270
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1975
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1271
1976
  var __spreadValues = (a, b) => {
1272
1977
  for (var prop in b || (b = {}))
1273
1978
  if (__hasOwnProp.call(b, prop))
1274
- __defNormalProp(a, prop, b[prop]);
1979
+ __defNormalProp$1(a, prop, b[prop]);
1275
1980
  if (__getOwnPropSymbols)
1276
1981
  for (var prop of __getOwnPropSymbols(b)) {
1277
1982
  if (__propIsEnum.call(b, prop))
1278
- __defNormalProp(a, prop, b[prop]);
1983
+ __defNormalProp$1(a, prop, b[prop]);
1279
1984
  }
1280
1985
  return a;
1281
1986
  };
1282
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1283
- var __objRest = (source, exclude) => {
1284
- var target = {};
1285
- for (var prop in source)
1286
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
1287
- target[prop] = source[prop];
1288
- if (source != null && __getOwnPropSymbols)
1289
- for (var prop of __getOwnPropSymbols(source)) {
1290
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
1291
- target[prop] = source[prop];
1292
- }
1293
- return target;
1294
- };
1295
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1296
1987
  var __async = (__this, __arguments, generator) => {
1297
1988
  return new Promise((resolve, reject) => {
1298
1989
  var fulfilled = (value) => {
@@ -1311,174 +2002,77 @@ var __async = (__this, __arguments, generator) => {
1311
2002
  };
1312
2003
  var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1313
2004
  step((generator = generator.apply(__this, __arguments)).next());
1314
- });
1315
- };
1316
- let ID = 0;
1317
- let REQUEST_ID = 0;
1318
- class NgwConnector {
1319
- constructor(options) {
1320
- this.options = options;
1321
- __publicField(this, "id", ID++);
1322
- __publicField(this, "emitter", new EventEmitter());
1323
- __publicField(this, "user");
1324
- __publicField(this, "resources");
1325
- __publicField(this, "cache");
1326
- __publicField(this, "withCredentials");
1327
- __publicField(this, "client", `NextGIS-NGW-Connector/${pkg.version}`);
1328
- __publicField(this, "routeStr", "/api/component/pyramid/route");
1329
- __publicField(this, "activeRequests", {});
1330
- __publicField(this, "requestTransform");
1331
- const exist = findConnector(options);
1332
- this.cache = new Cache({ namespace: options.cacheId });
1333
- if (exist) {
1334
- return exist;
1335
- } else {
1336
- const { route, requestTransform, withCredentials } = this.options;
1337
- if (route) {
1338
- this.routeStr = route;
1339
- }
1340
- if (requestTransform) {
1341
- this.requestTransform = requestTransform;
1342
- }
1343
- if (withCredentials !== void 0) {
1344
- this.withCredentials = withCredentials;
1345
- }
1346
- this.resources = new ResourcesControl({
1347
- connector: this,
1348
- cacheId: options.cacheId
1349
- });
1350
- addConnector(this);
1351
- }
1352
- }
1353
- static create(options) {
1354
- return new this(options);
1355
- }
1356
- /**
1357
- * Clear the cache.
1358
- */
1359
- clearCache() {
1360
- this.cache.clean();
1361
- this.resources.cache.clean();
1362
- }
1363
- setRequestTransform(requestTransform) {
1364
- this.requestTransform = requestTransform;
1365
- }
1366
- /**
1367
- * Fast way to specify the connection address to NextGIS Web.
1368
- * The current connection will be severed.
1369
- * @param baseUrl - NGW url
1370
- */
1371
- setNgw(baseUrl) {
1372
- this.logout();
1373
- this.options.baseUrl = baseUrl;
1374
- addConnector(this);
1375
- }
1376
- /**
1377
- * Establishing a connection with NextGIS Web to fulfill all other requests.
1378
- * @remarks
1379
- * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1380
- * Can be used to check connection.
1381
- * @example
1382
- * ```javascript
1383
- * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1384
- * connector.connect()
1385
- * .then(() => console.log('Ok'))
1386
- * .catch((er) => console.log('Connection problem', er));
1387
- * ```
1388
- */
1389
- connect() {
1390
- return __async(this, null, function* () {
1391
- const auth = this.options.auth;
1392
- if (auth) {
1393
- const { login, password } = auth;
1394
- if (login && password) {
1395
- yield this._login({ login, password });
2005
+ });
2006
+ };
2007
+ function apiRequest(opt) {
2008
+ return __async(this, null, function* () {
2009
+ const { params, name, connector, requestOptions } = opt;
2010
+ const apiItems = yield connector.connect();
2011
+ let apiItem = apiItems && apiItems[name];
2012
+ if (apiItem) {
2013
+ apiItem = [...apiItem];
2014
+ let url = apiItem.shift();
2015
+ if (apiItem.length) {
2016
+ const replaceParams = {};
2017
+ for (let fry = 0; fry < apiItem.length; fry++) {
2018
+ const arg = apiItem[fry];
2019
+ replaceParams[fry] = `{${arg}}`;
2020
+ if (params[arg] === void 0) {
2021
+ throw new Error(`\`${arg}\` URL API argument is not specified`);
2022
+ }
2023
+ }
2024
+ if (url) {
2025
+ url = template(url, replaceParams);
1396
2026
  }
1397
2027
  }
1398
- const routeUrl = `${this.routeStr}?client=${this.client}`;
1399
- return yield this.makeQuery(
1400
- routeUrl,
1401
- {},
1402
- {
1403
- cacheName: "route",
1404
- cache: true,
1405
- cacheProps: {
1406
- id: this.id,
1407
- auth,
1408
- baseUrl: this.options.baseUrl
2028
+ if (params) {
2029
+ const paramArray = [];
2030
+ const paramList = params.paramList;
2031
+ if (Array.isArray(paramList)) {
2032
+ paramList.forEach(([key, value]) => {
2033
+ paramArray.push(`${key}=${value}`);
2034
+ });
2035
+ }
2036
+ for (const p in params) {
2037
+ if (apiItem.indexOf(p) === -1) {
2038
+ paramArray.push(`${p}=${params[p]}`);
1409
2039
  }
1410
2040
  }
1411
- );
1412
- });
1413
- }
1414
- /**
1415
- * Quick way to change NextGIS Web user.
1416
- * @param credentials - New user credentials
1417
- */
1418
- login(credentials, options) {
1419
- this.logout();
1420
- addConnector(this);
1421
- return this._login(credentials, options);
1422
- }
1423
- /**
1424
- * Disconnecting a user. Aborting all current requests
1425
- */
1426
- logout() {
1427
- this.abort();
1428
- removeConnector(this);
1429
- this.options.auth = void 0;
1430
- this.user = void 0;
1431
- this.clearCache();
1432
- this.emitter.emit("logout");
1433
- }
1434
- getUserInfo(credentials, options) {
1435
- return __async(this, null, function* () {
1436
- if (this.user && this.user.id) {
1437
- return this.user;
2041
+ if (paramArray.length) {
2042
+ url = `${url}?${paramArray.join("&")}`;
2043
+ }
1438
2044
  }
1439
- if (credentials) {
1440
- this.options.auth = credentials;
2045
+ if (url) {
2046
+ return connector.makeQuery(url, params, __spreadValues({
2047
+ cacheName: name
2048
+ }, requestOptions));
2049
+ } else {
2050
+ throw new Error("Request URL is not set");
1441
2051
  }
1442
- const options_ = __spreadValues({
1443
- headers: this.getAuthorizationHeaders(credentials)
1444
- }, options);
1445
- return this.makeQuery(
1446
- "/api/component/auth/current_user",
1447
- {},
1448
- options_
1449
- );
2052
+ } else {
2053
+ return void 0;
2054
+ }
2055
+ });
2056
+ }
2057
+
2058
+ var __defProp = Object.defineProperty;
2059
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2060
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
2061
+ class NgwConnectorExtended extends NgwConnector {
2062
+ constructor(options) {
2063
+ super(options);
2064
+ __publicField(this, "resources");
2065
+ this.resources = new ResourcesControl({
2066
+ connector: this,
2067
+ cacheId: options.cacheId
1450
2068
  });
1451
2069
  }
1452
2070
  /**
1453
- * Obtaining the required Headers for authentication of requests in the NGW.
2071
+ * Clear the cache.
1454
2072
  */
1455
- getAuthorizationHeaders(credentials) {
1456
- const client = this.makeClientId(credentials);
1457
- if (client) {
1458
- return {
1459
- Authorization: `Basic ${client}`
1460
- };
1461
- }
1462
- }
1463
- makeClientId(credentials) {
1464
- credentials = credentials || this.options.auth;
1465
- if (credentials) {
1466
- const { login, password } = credentials;
1467
- const encodedStr = [login, password].map(encodeURIComponent).join(":");
1468
- {
1469
- return window.btoa(encodedStr);
1470
- }
1471
- }
1472
- }
1473
- /** Stop all api requests */
1474
- abort() {
1475
- for (const abortController of Object.values(this.activeRequests)) {
1476
- abortController.abort();
1477
- }
1478
- this.activeRequests = {};
1479
- }
1480
- getActiveApiRequests() {
1481
- return __spreadValues({}, this.activeRequests);
2073
+ clearCache() {
2074
+ super.clearCache();
2075
+ this.resources.cache.clean();
1482
2076
  }
1483
2077
  /**
1484
2078
  * Send request to NGW api router.
@@ -1597,75 +2191,6 @@ class NgwConnector {
1597
2191
  options
1598
2192
  );
1599
2193
  }
1600
- /**
1601
- * Send request to NGW.
1602
- * @param url - URL address to NGW
1603
- * @param params - Query params
1604
- * @param options - Request options
1605
- */
1606
- makeQuery(_0, _1) {
1607
- return __async(this, arguments, function* (url, params, options = {}) {
1608
- var _b;
1609
- url = (this.options.baseUrl ? this.options.baseUrl : "") + url;
1610
- if (!url) {
1611
- throw new Error("Empty `url` not allowed");
1612
- }
1613
- if (params) {
1614
- const _a = params, restParams = __objRest(_a, ["paramList"]);
1615
- url = template(url, restParams);
1616
- }
1617
- url = encodeURI(fixUrlStr(url));
1618
- options = __spreadValues({ withCredentials: this.withCredentials }, options);
1619
- const {
1620
- cache,
1621
- signal: externalSignal,
1622
- method = "GET",
1623
- headers,
1624
- cacheName,
1625
- cacheProps,
1626
- responseType,
1627
- withCredentials
1628
- } = options;
1629
- const internalAbortController = new AbortController();
1630
- const internalSignal = internalAbortController.signal;
1631
- if (externalSignal) {
1632
- if (externalSignal.aborted) {
1633
- throw new AbortError();
1634
- }
1635
- externalSignal.addEventListener("abort", () => {
1636
- internalAbortController.abort();
1637
- });
1638
- }
1639
- options.signal = internalSignal;
1640
- const createPromise = () => __async(this, null, function* () {
1641
- const id = REQUEST_ID++;
1642
- this.activeRequests[id] = internalAbortController;
1643
- try {
1644
- return this._loadData(url, options);
1645
- } finally {
1646
- this._cleanActiveRequest(id);
1647
- }
1648
- });
1649
- if (cache && method === "GET") {
1650
- const cacheOptions = cacheProps ? cacheProps : __spreadProps(__spreadValues({}, objectRemoveEmpty({
1651
- headers,
1652
- withCredentials,
1653
- responseType,
1654
- baseUrl: this.options.baseUrl,
1655
- userId: (_b = this.user) == null ? void 0 : _b.id
1656
- })), {
1657
- params
1658
- });
1659
- return this.cache.add(
1660
- cacheName || url,
1661
- createPromise,
1662
- cacheOptions,
1663
- false
1664
- );
1665
- }
1666
- return createPromise();
1667
- });
1668
- }
1669
2194
  // -------------------------------------------------------------------------
1670
2195
  // Resource Methods
1671
2196
  // -------------------------------------------------------------------------
@@ -1741,78 +2266,7 @@ class NgwConnector {
1741
2266
  deleteResource(resource) {
1742
2267
  return this.resources.delete(resource);
1743
2268
  }
1744
- /**
1745
- * @internal
1746
- */
1747
- _loadData(url, options) {
1748
- options.responseType = options.responseType || "json";
1749
- return new Promise((resolve, reject) => {
1750
- var _a;
1751
- if (this.user) {
1752
- options = options || {};
1753
- options.headers = __spreadValues(__spreadValues({}, this.getAuthorizationHeaders()), options.headers);
1754
- }
1755
- if (this.requestTransform) {
1756
- const [transUrl, transOptions] = this.requestTransform(url, options);
1757
- url = transUrl;
1758
- options = transOptions;
1759
- }
1760
- let runOnAbort = void 0;
1761
- loadData(url, resolve, options, reject, (handler) => {
1762
- runOnAbort = handler;
1763
- });
1764
- (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
1765
- if (runOnAbort !== void 0) {
1766
- runOnAbort();
1767
- }
1768
- reject(new AbortError());
1769
- });
1770
- }).catch((httpError) => {
1771
- if (httpError.name !== "AbortError") {
1772
- {
1773
- console.warn("DEV WARN", httpError);
1774
- }
1775
- const er = this._handleHttpError(httpError);
1776
- if (er) {
1777
- throw er;
1778
- }
1779
- }
1780
- throw httpError;
1781
- });
1782
- }
1783
- _login(credentials, options) {
1784
- return __async(this, null, function* () {
1785
- try {
1786
- const data = yield this.getUserInfo(credentials, options);
1787
- this.user = data;
1788
- this.emitter.emit("login", data);
1789
- return data;
1790
- } catch (er) {
1791
- this.emitter.emit("login:error", er);
1792
- throw er;
1793
- }
1794
- });
1795
- }
1796
- _cleanActiveRequest(requestId) {
1797
- delete this.activeRequests[requestId];
1798
- }
1799
- _handleHttpError(er) {
1800
- if (er) {
1801
- if (er instanceof NgwError) {
1802
- if (er.exception === "nextgisweb.resource.exception.ResourceNotFound") {
1803
- throw new ResourceNotFoundError(er);
1804
- } else if (er.exception === "nextgisweb.core.exception.InsufficientPermissions") {
1805
- throw new InsufficientPermissionsError(er);
1806
- }
1807
- }
1808
- }
1809
- return er;
1810
- }
1811
2269
  }
1812
- __publicField(NgwConnector, "errors", {
1813
- NgwError,
1814
- ResourceNotFoundError
1815
- });
1816
2270
 
1817
- export { NgwConnector as default };
2271
+ export { NgwConnectorExtended as default };
1818
2272
  //# sourceMappingURL=ngw-connector.esm-browser.js.map