@nextgis/geocoder 3.0.0-alpha.0 → 3.0.0-alpha.12

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,4 @@
1
- /** Bundle of @nextgis/geocoder; version: 3.0.0-alpha.0; author: NextGIS */
1
+ /** Bundle of @nextgis/geocoder; version: 3.0.0-alpha.9; author: NextGIS */
2
2
  function defined(val) {
3
3
  return val !== void 0 && val !== null;
4
4
  }
@@ -104,28 +104,28 @@ class BaseGeocoder {
104
104
  }
105
105
  }
106
106
 
107
- var __defProp$d = Object.defineProperty;
108
- var __defProps$3 = Object.defineProperties;
109
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
110
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
111
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
112
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
107
+ var __defProp$i = Object.defineProperty;
108
+ var __defProps$5 = Object.defineProperties;
109
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
110
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
111
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
112
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
113
113
  var __knownSymbol$2 = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
114
- var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
115
- var __spreadValues$6 = (a, b) => {
114
+ var __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
115
+ var __spreadValues$8 = (a, b) => {
116
116
  for (var prop in b || (b = {}))
117
- if (__hasOwnProp$6.call(b, prop))
118
- __defNormalProp$d(a, prop, b[prop]);
119
- if (__getOwnPropSymbols$6)
120
- for (var prop of __getOwnPropSymbols$6(b)) {
121
- if (__propIsEnum$6.call(b, prop))
122
- __defNormalProp$d(a, prop, b[prop]);
117
+ if (__hasOwnProp$8.call(b, prop))
118
+ __defNormalProp$i(a, prop, b[prop]);
119
+ if (__getOwnPropSymbols$8)
120
+ for (var prop of __getOwnPropSymbols$8(b)) {
121
+ if (__propIsEnum$8.call(b, prop))
122
+ __defNormalProp$i(a, prop, b[prop]);
123
123
  }
124
124
  return a;
125
125
  };
126
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
127
- var __publicField$a = (obj, key, value) => __defNormalProp$d(obj, key + "" , value);
128
- var __async$5 = (__this, __arguments, generator) => {
126
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
127
+ var __publicField$d = (obj, key, value) => __defNormalProp$i(obj, key + "" , value);
128
+ var __async$7 = (__this, __arguments, generator) => {
129
129
  return new Promise((resolve, reject) => {
130
130
  var fulfilled = (value) => {
131
131
  try {
@@ -165,7 +165,7 @@ let ID$1 = 0;
165
165
  class Geocoder extends BaseGeocoder {
166
166
  constructor(options) {
167
167
  super(options);
168
- __publicField$a(this, "providers", []);
168
+ __publicField$d(this, "providers", []);
169
169
  if (options && options.providers) {
170
170
  this.providers = options.providers;
171
171
  }
@@ -189,7 +189,7 @@ class Geocoder extends BaseGeocoder {
189
189
  for (var iter = __forAwait(results), more, temp, error; more = !(temp = yield new __await$2(iter.next())).done; more = false) {
190
190
  const r = temp.value;
191
191
  allProvidersFailed = false;
192
- yield __spreadProps$3(__spreadValues$6({}, r), { provider, _id: ID$1++ });
192
+ yield __spreadProps$5(__spreadValues$8({}, r), { provider, _id: ID$1++ });
193
193
  }
194
194
  } catch (temp) {
195
195
  error = [temp];
@@ -203,7 +203,7 @@ class Geocoder extends BaseGeocoder {
203
203
  }
204
204
  } catch (err) {
205
205
  const er = err;
206
- if (er.name !== "CancelError") {
206
+ if (er.name !== "AbortError") {
207
207
  errors.push(er);
208
208
  }
209
209
  }
@@ -232,7 +232,7 @@ class Geocoder extends BaseGeocoder {
232
232
  try {
233
233
  for (var iter = __forAwait(results), more, temp, error; more = !(temp = yield new __await$2(iter.next())).done; more = false) {
234
234
  const r = temp.value;
235
- yield __spreadProps$3(__spreadValues$6({}, r), { provider, _id: ID$1++ });
235
+ yield __spreadProps$5(__spreadValues$8({}, r), { provider, _id: ID$1++ });
236
236
  }
237
237
  } catch (temp) {
238
238
  error = [temp];
@@ -256,7 +256,7 @@ class Geocoder extends BaseGeocoder {
256
256
  * @returns A promise that resolves to the first reverse geocoding result, or undefined if no results are found.
257
257
  */
258
258
  reverseGeocodeFirstResult(coordinates) {
259
- return __async$5(this, null, function* () {
259
+ return __async$7(this, null, function* () {
260
260
  for (const provider of this.providers) {
261
261
  if (typeof provider.reverse === "function") {
262
262
  try {
@@ -285,9 +285,9 @@ class Geocoder extends BaseGeocoder {
285
285
  }
286
286
  }
287
287
 
288
- var __defProp$c = Object.defineProperty;
289
- var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
290
- var __publicField$9 = (obj, key, value) => __defNormalProp$c(obj, typeof key !== "symbol" ? key + "" : key, value);
288
+ var __defProp$h = Object.defineProperty;
289
+ var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
290
+ var __publicField$c = (obj, key, value) => __defNormalProp$h(obj, typeof key !== "symbol" ? key + "" : key, value);
291
291
  class BaseProvider extends BaseGeocoder {
292
292
  constructor() {
293
293
  super(...arguments);
@@ -295,12 +295,12 @@ class BaseProvider extends BaseGeocoder {
295
295
  * URL endpoint for the search service.
296
296
  * This is where queries will be sent to obtain search results.
297
297
  */
298
- __publicField$9(this, "searchUrl");
298
+ __publicField$c(this, "searchUrl");
299
299
  /**
300
300
  * Label to represent the provider.
301
301
  * Useful for user interfaces to display the source of search results.
302
302
  */
303
- __publicField$9(this, "label");
303
+ __publicField$c(this, "label");
304
304
  }
305
305
  }
306
306
 
@@ -334,7 +334,7 @@ EventEmitter.init = function() {
334
334
  this.domain = null;
335
335
  if (EventEmitter.usingDomains) {
336
336
  // if there is an active domain, then attach to it.
337
- if (domain.active ) ;
337
+ if (domain.active) ;
338
338
  }
339
339
 
340
340
  if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
@@ -776,12 +776,12 @@ function unwrapListeners(arr) {
776
776
  return ret;
777
777
  }
778
778
 
779
- var __defProp$b = Object.defineProperty;
780
- var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
781
- var __publicField$8 = (obj, key, value) => __defNormalProp$b(obj, typeof key !== "symbol" ? key + "" : key, value);
779
+ var __defProp$g = Object.defineProperty;
780
+ var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
781
+ var __publicField$b = (obj, key, value) => __defNormalProp$g(obj, typeof key !== "symbol" ? key + "" : key, value);
782
782
  const _Cache = class _Cache {
783
783
  constructor(options = {}) {
784
- __publicField$8(this, "cache", []);
784
+ __publicField$b(this, "cache", []);
785
785
  var _a;
786
786
  const namespace = (_a = options.namespace) != null ? _a : "default";
787
787
  if (_Cache.instance[namespace]) {
@@ -817,10 +817,23 @@ const _Cache = class _Cache {
817
817
  * });
818
818
  * ```
819
819
  */
820
- addFull(key, valueToSet, props) {
821
- return this.add(key, valueToSet, props, true);
822
- }
823
- add(key, valueToSet, props, onlyFull) {
820
+ addFull(key, valueToSet, propsOrOptions, expirationTime) {
821
+ if (typeof propsOrOptions === "object" && "valueToSet" in propsOrOptions) {
822
+ propsOrOptions.onlyFull = true;
823
+ }
824
+ return this.add(key, valueToSet, propsOrOptions, true, expirationTime);
825
+ }
826
+ add(key, valueToSet, propsOrOptions, onlyFull, expirationTime) {
827
+ let opt;
828
+ let props;
829
+ if (typeof propsOrOptions === "object" && "valueToSet" in propsOrOptions) {
830
+ opt = propsOrOptions;
831
+ onlyFull = opt.onlyFull;
832
+ expirationTime = opt.expirationTime;
833
+ props = opt.props;
834
+ } else {
835
+ props = propsOrOptions;
836
+ }
824
837
  const exist = this._find(key, props);
825
838
  if (!exist) {
826
839
  let value;
@@ -830,10 +843,12 @@ const _Cache = class _Cache {
830
843
  value = valueToSet;
831
844
  }
832
845
  const nonEmptyProps = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
846
+ expirationTime = expirationTime ? Date.now() + expirationTime : void 0;
833
847
  const cacheItem = {
834
848
  key,
835
849
  value,
836
- props: nonEmptyProps
850
+ props: nonEmptyProps,
851
+ expirationTime
837
852
  };
838
853
  if (onlyFull && !full(value)) {
839
854
  return value;
@@ -860,9 +875,19 @@ const _Cache = class _Cache {
860
875
  }
861
876
  match(key, props) {
862
877
  const cacheRecord = this._find(key, props);
878
+ if (cacheRecord && cacheRecord.expirationTime && Date.now() > cacheRecord.expirationTime) {
879
+ this.delete(cacheRecord);
880
+ return void 0;
881
+ }
863
882
  return cacheRecord == null ? void 0 : cacheRecord.value;
864
883
  }
865
884
  matchAll(key, props) {
885
+ const now = Date.now();
886
+ this.cache.forEach((item) => {
887
+ if (item.expirationTime && now > item.expirationTime) {
888
+ this.delete(item);
889
+ }
890
+ });
866
891
  if (key) {
867
892
  return this.cache.filter((x) => this._filter(x, key, props)).map((x) => x.value);
868
893
  }
@@ -887,31 +912,159 @@ const _Cache = class _Cache {
887
912
  return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
888
913
  }
889
914
  };
890
- __publicField$8(_Cache, "instance", {});
915
+ __publicField$b(_Cache, "instance", {});
891
916
  let Cache = _Cache;
892
917
 
893
- var __defProp$a = Object.defineProperty;
894
- var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
895
- var __publicField$7 = (obj, key, value) => __defNormalProp$a(obj, typeof key !== "symbol" ? key + "" : key, value);
918
+ var pkg = {
919
+ name: "@nextgis/ngw-connector",
920
+ version: "3.0.0-alpha.8",
921
+ _priority: 12,
922
+ description: "A lightweight HTTP client optimized for use with NextGIS Web API",
923
+ main: "index.js",
924
+ module: "lib/ngw-connector.esm-bundler.js",
925
+ unpkg: "lib/ngw-connector.global.prod.js",
926
+ jsdelivr: "lib/ngw-connector.global.prod.js",
927
+ types: "lib/index.d.ts",
928
+ dependencies: {
929
+ "@nextgis/cache": "^3.0.0-alpha.7",
930
+ "@nextgis/cancelable-promise": "^3.0.0-alpha.5",
931
+ "@nextgis/utils": "^3.0.0-alpha.5",
932
+ "@types/events": "^3.0.0",
933
+ events: "*",
934
+ "form-data": "^4.0.0"
935
+ },
936
+ devDependencies: {
937
+ "@nextgis/build-tools": "^3.0.0-alpha.5"
938
+ },
939
+ scripts: {
940
+ clean: "rimraf ./lib",
941
+ dev: "node ../build-tools/lib/build.js",
942
+ prod: "npm run dev -- --release",
943
+ lint: "eslint ./src/**/*.ts --fix --c ../../.eslintrc",
944
+ watch: "npm run dev -- --watch",
945
+ "gen:types": "node ./scripts/generator"
946
+ },
947
+ buildOptions: {
948
+ name: "NgwConnector",
949
+ formats: [
950
+ "esm-bundler",
951
+ "esm-browser",
952
+ "cjs",
953
+ "global"
954
+ ]
955
+ },
956
+ keywords: [
957
+ "NextGIS",
958
+ "MAP"
959
+ ],
960
+ author: "NextGIS",
961
+ files: [
962
+ "index.js",
963
+ "lib"
964
+ ],
965
+ license: "MIT",
966
+ homepage: "https://github.com/nextgis/nextgis_frontend/tree/master/packages/ngw-connector#readme",
967
+ repository: {
968
+ type: "git",
969
+ url: "git://github.com/nextgis/nextgis_frontend.git"
970
+ },
971
+ engines: {
972
+ node: ">=18.20.4"
973
+ },
974
+ gitHead: "edc68033f914f6c95c4125b9738bba6d36e990b4"
975
+ };
976
+
977
+ const CONNECTORS = [];
978
+ function addConnector(connector) {
979
+ CONNECTORS.push(connector);
980
+ }
981
+ function findConnector(options) {
982
+ return CONNECTORS.find((x) => {
983
+ if (x.options.baseUrl === options.baseUrl) {
984
+ if (options.auth) {
985
+ if (x.options.auth) {
986
+ return objectDeepEqual(x.options.auth, options.auth);
987
+ }
988
+ } else {
989
+ return true;
990
+ }
991
+ }
992
+ });
993
+ }
994
+ function removeConnector(connector) {
995
+ const index = CONNECTORS.indexOf(connector);
996
+ if (index !== -1) {
997
+ CONNECTORS.splice(index, 1);
998
+ }
999
+ }
1000
+
1001
+ class AbortError extends Error {
1002
+ constructor(message = "AbortError") {
1003
+ super(message);
1004
+ this.name = "AbortError";
1005
+ }
1006
+ }
1007
+
1008
+ var __defProp$f = Object.defineProperty;
1009
+ var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1010
+ var __publicField$a = (obj, key, value) => __defNormalProp$f(obj, typeof key !== "symbol" ? key + "" : key, value);
896
1011
  class NgwError extends Error {
897
1012
  constructor(er) {
898
1013
  super();
899
- __publicField$7(this, "name", "NgwError");
900
- __publicField$7(this, "title");
901
- __publicField$7(this, "message");
902
- __publicField$7(this, "detail");
903
- __publicField$7(this, "exception");
904
- __publicField$7(this, "status_code");
905
- __publicField$7(this, "data");
906
- __publicField$7(this, "guru_meditation");
1014
+ __publicField$a(this, "name", "NgwError");
1015
+ __publicField$a(this, "title");
1016
+ __publicField$a(this, "message");
1017
+ __publicField$a(this, "detail");
1018
+ __publicField$a(this, "exception");
1019
+ __publicField$a(this, "status_code");
1020
+ __publicField$a(this, "data");
1021
+ __publicField$a(this, "guru_meditation");
907
1022
  Object.assign(this, er);
908
1023
  Object.setPrototypeOf(this, NgwError.prototype);
909
1024
  }
910
1025
  }
911
1026
 
912
- var __defProp$9 = Object.defineProperty;
913
- var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
914
- var __publicField$6 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
1027
+ var __defProp$e = Object.defineProperty;
1028
+ var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1029
+ var __publicField$9 = (obj, key, value) => __defNormalProp$e(obj, typeof key !== "symbol" ? key + "" : key, value);
1030
+ class InsufficientPermissionsError extends NgwError {
1031
+ constructor(obj) {
1032
+ super(obj);
1033
+ __publicField$9(this, "name", "InsufficientPermissionsError");
1034
+ __publicField$9(this, "exception", "nextgisweb.core.exception.InsufficientPermissions");
1035
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1036
+ }
1037
+ }
1038
+
1039
+ var __defProp$d = Object.defineProperty;
1040
+ var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1041
+ var __publicField$8 = (obj, key, value) => __defNormalProp$d(obj, key + "" , value);
1042
+ class NetworkError extends Error {
1043
+ constructor(url) {
1044
+ super();
1045
+ __publicField$8(this, "name", "NetworkError");
1046
+ Object.setPrototypeOf(this, NetworkError.prototype);
1047
+ this.message = `Unable to request ${url}.
1048
+ Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`;
1049
+ }
1050
+ }
1051
+
1052
+ var __defProp$c = Object.defineProperty;
1053
+ var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1054
+ var __publicField$7 = (obj, key, value) => __defNormalProp$c(obj, typeof key !== "symbol" ? key + "" : key, value);
1055
+ let NetworksResponseError$1 = class NetworksResponseError extends NgwError {
1056
+ constructor(obj) {
1057
+ super(obj);
1058
+ __publicField$7(this, "message", "There is no response from the server or problem connecting to server.");
1059
+ __publicField$7(this, "title", "Network error");
1060
+ __publicField$7(this, "detail", "Check network connectivity and try again later.");
1061
+ Object.setPrototypeOf(this, NetworksResponseError.prototype);
1062
+ }
1063
+ };
1064
+
1065
+ var __defProp$b = Object.defineProperty;
1066
+ var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1067
+ var __publicField$6 = (obj, key, value) => __defNormalProp$b(obj, typeof key !== "symbol" ? key + "" : key, value);
915
1068
  class ResourceNotFoundError extends NgwError {
916
1069
  constructor(obj) {
917
1070
  super(obj);
@@ -921,53 +1074,143 @@ class ResourceNotFoundError extends NgwError {
921
1074
  }
922
1075
  }
923
1076
 
924
- function isObject(val) {
925
- return Object.prototype.toString.call(val) === "[object Object]";
1077
+ function isError(error) {
1078
+ if (isObject$1(error)) {
1079
+ return error.status_code && error.exception && error.title;
1080
+ }
1081
+ return false;
926
1082
  }
927
1083
 
928
- function resourceCompare(res1, res2) {
929
- return objectDeepEqual(res1, res2);
1084
+ function extractError(error) {
1085
+ if (isObject$1(error)) {
1086
+ if (error.name && error.message && error.title) {
1087
+ return {
1088
+ title: error.title,
1089
+ message: error.message,
1090
+ detail: error.detail || null,
1091
+ data: error.data && error.data.data ? error.data.data : null
1092
+ };
1093
+ } else if (error.exception) {
1094
+ if (error.status === void 0 || error.status === 0 || error.data === void 0) {
1095
+ return new NetworksResponseError$1({
1096
+ title: error.title,
1097
+ status_code: error.status_code,
1098
+ exception: error.exception
1099
+ });
1100
+ }
1101
+ }
1102
+ return {
1103
+ title: typeof error.title === "string" ? error.title : "Unexpected error",
1104
+ message: typeof error.message === "string" ? error.message : "Something went wrong."
1105
+ };
1106
+ }
930
1107
  }
931
1108
 
932
- const exclude = ["description"];
933
- function resourceToQuery(resource, prefix = "") {
934
- prefix = prefix ? prefix + "__" : "";
935
- const query = {};
936
- for (const [key, value] of Object.entries(resource)) {
937
- if (exclude.indexOf(key) === -1) {
938
- if (isObject(value)) {
939
- if (key === "owner_user") {
940
- const children = resourceToQuery(value, key);
941
- Object.assign(query, children);
942
- } else if (key === "parent" && "id" in value) {
943
- query.parent_id = value.id;
944
- }
945
- } else if (defined(value)) {
946
- query[prefix + key] = value;
947
- }
1109
+ var errors = /*#__PURE__*/Object.freeze({
1110
+ __proto__: null,
1111
+ AbortError: AbortError,
1112
+ InsufficientPermissionsError: InsufficientPermissionsError,
1113
+ NetworkError: NetworkError,
1114
+ NetworksResponseError: NetworksResponseError$1,
1115
+ NgwError: NgwError,
1116
+ ResourceNotFoundError: ResourceNotFoundError,
1117
+ extractError: extractError,
1118
+ isError: isError
1119
+ });
1120
+
1121
+ var __defProp$a = Object.defineProperty;
1122
+ var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1123
+ var __publicField$5 = (obj, key, value) => __defNormalProp$a(obj, typeof key !== "symbol" ? key + "" : key, value);
1124
+ class BaseAPIError extends Error {
1125
+ constructor(message) {
1126
+ super(message || "Something went wrong.");
1127
+ __publicField$5(this, "title");
1128
+ this.name = "BaseAPIError";
1129
+ this.title = "Unknown API error";
1130
+ if (Error.captureStackTrace) {
1131
+ Error.captureStackTrace(this, BaseAPIError);
948
1132
  }
949
1133
  }
950
- return query;
1134
+ }
1135
+ class NetworksResponseError extends BaseAPIError {
1136
+ // prettier-ignore
1137
+ constructor(message) {
1138
+ super(message || "There is no response from the server or problem connecting to server.");
1139
+ __publicField$5(this, "detail");
1140
+ this.title = "Network error";
1141
+ this.detail = "Check network connectivity and try again later.";
1142
+ }
1143
+ }
1144
+ class InvalidResponseError extends BaseAPIError {
1145
+ constructor(message) {
1146
+ super(message || "Something went wrong.");
1147
+ this.title = "Unexpected server response";
1148
+ }
1149
+ }
1150
+ class ServerResponseError extends BaseAPIError {
1151
+ constructor(data) {
1152
+ super(data.message);
1153
+ __publicField$5(this, "detail");
1154
+ __publicField$5(this, "data");
1155
+ this.title = data.title || this.title;
1156
+ this.detail = data.detail || null;
1157
+ this.data = data;
1158
+ }
1159
+ }
1160
+ class LunkwillError extends Error {
1161
+ // prettier-ignore
1162
+ constructor(message, data = {}) {
1163
+ super(message || "Unexpected error while processing long-running request.");
1164
+ __publicField$5(this, "title");
1165
+ __publicField$5(this, "data");
1166
+ this.name = "LunkwillError";
1167
+ this.title = "Long-running request error";
1168
+ this.data = data;
1169
+ if (Error.captureStackTrace) {
1170
+ Error.captureStackTrace(this, LunkwillError);
1171
+ }
1172
+ }
1173
+ }
1174
+ class LunkwillRequestCancelled extends LunkwillError {
1175
+ constructor(data) {
1176
+ super("Long-running request was cancelled.", data);
1177
+ }
1178
+ }
1179
+ class LunkwillRequestFailed extends LunkwillError {
1180
+ constructor(data) {
1181
+ super(void 0, data);
1182
+ }
951
1183
  }
952
1184
 
953
- var __defProp$8 = Object.defineProperty;
954
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
955
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
956
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
957
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
958
- var __spreadValues$5 = (a, b) => {
1185
+ var __defProp$9 = Object.defineProperty;
1186
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
1187
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
1188
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
1189
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1190
+ var __spreadValues$7 = (a, b) => {
959
1191
  for (var prop in b || (b = {}))
960
- if (__hasOwnProp$5.call(b, prop))
961
- __defNormalProp$8(a, prop, b[prop]);
962
- if (__getOwnPropSymbols$5)
963
- for (var prop of __getOwnPropSymbols$5(b)) {
964
- if (__propIsEnum$5.call(b, prop))
965
- __defNormalProp$8(a, prop, b[prop]);
1192
+ if (__hasOwnProp$7.call(b, prop))
1193
+ __defNormalProp$9(a, prop, b[prop]);
1194
+ if (__getOwnPropSymbols$7)
1195
+ for (var prop of __getOwnPropSymbols$7(b)) {
1196
+ if (__propIsEnum$7.call(b, prop))
1197
+ __defNormalProp$9(a, prop, b[prop]);
966
1198
  }
967
1199
  return a;
968
1200
  };
969
- var __publicField$5 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
970
- var __async$4 = (__this, __arguments, generator) => {
1201
+ var __objRest$2 = (source, exclude) => {
1202
+ var target = {};
1203
+ for (var prop in source)
1204
+ if (__hasOwnProp$7.call(source, prop) && exclude.indexOf(prop) < 0)
1205
+ target[prop] = source[prop];
1206
+ if (source != null && __getOwnPropSymbols$7)
1207
+ for (var prop of __getOwnPropSymbols$7(source)) {
1208
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$7.call(source, prop))
1209
+ target[prop] = source[prop];
1210
+ }
1211
+ return target;
1212
+ };
1213
+ var __async$6 = (__this, __arguments, generator) => {
971
1214
  return new Promise((resolve, reject) => {
972
1215
  var fulfilled = (value) => {
973
1216
  try {
@@ -987,94 +1230,935 @@ var __async$4 = (__this, __arguments, generator) => {
987
1230
  step((generator = generator.apply(__this, __arguments)).next());
988
1231
  });
989
1232
  };
990
- class ResourcesControl {
991
- constructor({
992
- connector,
993
- cacheId
994
- }) {
995
- __publicField$5(this, "cache");
996
- __publicField$5(this, "connector");
997
- this.connector = connector;
998
- this.cache = new Cache({ namespace: cacheId });
999
- }
1000
- // -------------------------------------------------------------------------
1001
- // Resource Methods
1002
- // -------------------------------------------------------------------------
1003
- /**
1004
- * Receive resource from NGW by id, keyname or search-object parameter.
1005
- * @param resource - Resource id, keyname or search-object
1006
- *
1007
- * @remarks
1008
- * Fetching resource would be cached to speed up next call
1009
- */
1010
- getOne(resource, requestOptions) {
1011
- const opt = __spreadValues$5({}, requestOptions);
1012
- if (typeof resource === "string") ; else if (typeof resource === "number") ; else if (isObject(resource)) {
1013
- if (resource.id !== void 0) {
1014
- resource.id;
1015
- } else {
1016
- if (resource.keyname) {
1017
- resource.keyname;
1018
- }
1019
- if (resource.display_name) {
1020
- resource.display_name;
1021
- }
1233
+ function lunkwillCheckResponse(lwResp) {
1234
+ const ct = lwResp.headers.get("content-type");
1235
+ return ct !== void 0 && ct !== null && ct.includes("application/vnd.lunkwill.request-summary+json");
1236
+ }
1237
+ function responseJson(response) {
1238
+ return __async$6(this, null, function* () {
1239
+ try {
1240
+ return response.json();
1241
+ } catch (e) {
1242
+ throw new Error();
1243
+ }
1244
+ });
1245
+ }
1246
+ function lunkwillResponseUrl(lwResp) {
1247
+ return __async$6(this, null, function* () {
1248
+ const lwData = yield responseJson(lwResp);
1249
+ let delay = lwData.delay_ms;
1250
+ const retry = lwData.retry_ms !== void 0 ? lwData.retry_ms : 2e3;
1251
+ const sum = `/api/lunkwill/${lwData.id}/summary`;
1252
+ const res = `/api/lunkwill/${lwData.id}/response`;
1253
+ const sleep = (msec) => new Promise((resolve) => setTimeout(resolve, msec));
1254
+ let failed = false;
1255
+ let ready = false;
1256
+ while (!ready) {
1257
+ yield sleep(failed ? retry : delay);
1258
+ failed = false;
1259
+ let lwResp2;
1260
+ let lwData2;
1261
+ try {
1262
+ lwResp2 = yield fetch(sum, { credentials: "same-origin" });
1263
+ lwData2 = yield lwResp2.json();
1264
+ } catch (e) {
1265
+ failed = true;
1266
+ continue;
1267
+ }
1268
+ switch (lwData2.status) {
1269
+ case void 0:
1270
+ throw new LunkwillError(void 0, lwData2);
1271
+ case "ready":
1272
+ ready = true;
1273
+ break;
1274
+ case "cancelled":
1275
+ throw new LunkwillRequestCancelled(lwData2);
1276
+ case "failed":
1277
+ throw new LunkwillRequestFailed(lwData2);
1278
+ case "spooled":
1279
+ case "processing":
1280
+ case "buffering":
1281
+ delay = lwData2.delay_ms;
1282
+ break;
1283
+ default:
1284
+ throw new LunkwillError(void 0, lwData2);
1022
1285
  }
1023
1286
  }
1024
- if (typeof resource === "string") {
1025
- return this._fetchResourceBy({ keyname: resource }, opt);
1026
- } else if (typeof resource === "number") {
1027
- return this._fetchResourceById(resource, opt);
1028
- } else if (isObject(resource)) {
1029
- return this._fetchResourceBy(resource, opt);
1287
+ return res;
1288
+ });
1289
+ }
1290
+ function lunkwillFetch(lwRespUrl) {
1291
+ return __async$6(this, null, function* () {
1292
+ try {
1293
+ return yield window.fetch(lwRespUrl, { credentials: "same-origin" });
1294
+ } catch (e) {
1295
+ throw new NetworksResponseError();
1030
1296
  }
1031
- return Promise.resolve(void 0);
1032
- }
1033
- getOneOrFail(resource, requestOptions) {
1034
- return this.getOne(resource, requestOptions).then((res) => {
1035
- if (res) {
1036
- return res;
1037
- }
1038
- throw new ResourceNotFoundError();
1039
- });
1040
- }
1041
- /**
1042
- * A fast way to retrieve resource ID for any resource definition.
1043
- * @param resource - Any available resource definition
1044
- *
1045
- * @remarks
1046
- * There are situations when exactly the resource id is needed
1047
- * (for example, to compose the correct request to the api)
1048
- * then this method will come in handy to facilitate the extraction of the identifier
1049
- * if the resource is specified through a keyname or other parameters.
1050
- */
1051
- getId(resource, requestOptions) {
1052
- if (typeof resource === "number") {
1053
- return Promise.resolve(resource);
1054
- } else if (typeof resource === "string" || isObject(resource)) {
1055
- return this.getOne(resource, requestOptions).then((res) => {
1056
- if (res) {
1057
- return res.resource.id;
1297
+ });
1298
+ }
1299
+ const mediaContentTypes = [
1300
+ "application/pdf",
1301
+ "image/png",
1302
+ "image/jpeg",
1303
+ "image/tiff",
1304
+ "text/csv"
1305
+ ];
1306
+ const mediaContentTypesRegex = new RegExp(mediaContentTypes.join("|"));
1307
+ function isMediaContentType(contentType) {
1308
+ return mediaContentTypesRegex.test(contentType);
1309
+ }
1310
+ function encodeQueryParams(value) {
1311
+ const result = [];
1312
+ for (const [k, v] of Object.entries(value)) {
1313
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
1314
+ result.push(`${k}=${encodeURIComponent(v)}`);
1315
+ } else if (Array.isArray(v)) {
1316
+ result.push(`${k}=${v.map(encodeURIComponent).join(",")}`);
1317
+ } else {
1318
+ for (const [sk, sv] of Object.entries(v)) {
1319
+ const ske = `${k}[${encodeURIComponent(sk)}]`;
1320
+ if (typeof sv === "string" || typeof sv === "number" || typeof sv === "boolean") {
1321
+ result.push(`${ske}=${encodeURIComponent(sv)}`);
1322
+ } else if (Array.isArray(sv)) {
1323
+ const sve = sv.map(encodeURIComponent);
1324
+ result.push(`${ske}=${sve.join(",")}`);
1058
1325
  }
1059
- });
1326
+ }
1060
1327
  }
1061
- return Promise.resolve(void 0);
1062
1328
  }
1063
- /**
1064
- * A fast way to retrieve resource ID for any resource definition.
1065
- * @param resource - Any available resource definition
1066
- *
1067
- * @remarks
1068
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1069
- * To not make one more checks if the resource is definitely exists
1070
- */
1071
- getIdOrFail(resource, requestOptions) {
1072
- return this.getId(resource, requestOptions).then((resp) => {
1073
- if (resp === void 0) {
1074
- throw new Error();
1075
- }
1076
- return resp;
1077
- });
1329
+ return result.join("&");
1330
+ }
1331
+ function generateUrl(path, query) {
1332
+ let urlParams = "";
1333
+ if (query !== void 0) {
1334
+ urlParams = "?" + encodeQueryParams(query);
1335
+ }
1336
+ return path + urlParams;
1337
+ }
1338
+ function request(path, options, cacheEngine) {
1339
+ return __async$6(this, null, function* () {
1340
+ var _b;
1341
+ const defaults = {
1342
+ method: "GET",
1343
+ credentials: "same-origin",
1344
+ headers: {}
1345
+ };
1346
+ const _a = __spreadValues$7(__spreadValues$7({}, defaults), options), {
1347
+ withCredentials,
1348
+ responseType,
1349
+ cacheProps,
1350
+ cacheName,
1351
+ lunkwill,
1352
+ cache,
1353
+ query,
1354
+ json
1355
+ } = _a, opt = __objRest$2(_a, [
1356
+ "withCredentials",
1357
+ "responseType",
1358
+ "cacheProps",
1359
+ "cacheName",
1360
+ "lunkwill",
1361
+ "cache",
1362
+ "query",
1363
+ "json"
1364
+ ]);
1365
+ if (withCredentials) {
1366
+ opt.credentials = "include";
1367
+ }
1368
+ let useLunkwill = false;
1369
+ if (lunkwill !== void 0) {
1370
+ lunkwill.toHeaders(opt.headers || {});
1371
+ useLunkwill = true;
1372
+ }
1373
+ const lunkwillReturnUrl = !!opt.lunkwillReturnUrl;
1374
+ delete opt.lunkwillReturnUrl;
1375
+ if (json !== void 0) {
1376
+ opt.body = JSON.stringify(json);
1377
+ const headers = opt.headers || {};
1378
+ headers["Content-Type"] = "application/json";
1379
+ opt.headers = headers;
1380
+ }
1381
+ const url = generateUrl(path, query);
1382
+ const makeRequest = () => __async$6(this, null, function* () {
1383
+ let response;
1384
+ try {
1385
+ response = yield fetch(url, opt);
1386
+ } catch (e) {
1387
+ if (opt.signal && opt.signal.aborted) {
1388
+ throw e;
1389
+ }
1390
+ throw new NetworksResponseError();
1391
+ }
1392
+ if (useLunkwill && lunkwillCheckResponse(response)) {
1393
+ const lwRespUrl = yield lunkwillResponseUrl(response);
1394
+ if (lunkwillReturnUrl) {
1395
+ return lwRespUrl;
1396
+ }
1397
+ response = yield lunkwillFetch(lwRespUrl);
1398
+ }
1399
+ const respCType = response.headers.get("content-type");
1400
+ const respJSON = respCType && (respCType.includes("application/json") || respCType.includes("application/vnd.lunkwill.request-summary+json"));
1401
+ let body;
1402
+ try {
1403
+ const respMedia = respCType && isMediaContentType(respCType);
1404
+ if (responseType === "blob" || respMedia) {
1405
+ body = yield response.blob();
1406
+ } else if (respJSON) {
1407
+ body = yield response.json();
1408
+ } else {
1409
+ throw new InvalidResponseError();
1410
+ }
1411
+ } catch (e) {
1412
+ if (e.name === "AbortError" || e instanceof InvalidResponseError) {
1413
+ throw e;
1414
+ }
1415
+ throw new InvalidResponseError();
1416
+ }
1417
+ if (400 <= response.status && response.status <= 599) {
1418
+ throw new ServerResponseError(body);
1419
+ }
1420
+ return body;
1421
+ });
1422
+ if (cacheEngine && ((_b = opt.method) == null ? void 0 : _b.toUpperCase()) === "GET") {
1423
+ const props = cacheProps ? cacheProps : __spreadValues$7({}, objectRemoveEmpty({
1424
+ withCredentials,
1425
+ responseType
1426
+ }));
1427
+ return cacheEngine.add(cacheName || url, makeRequest, {
1428
+ props,
1429
+ expirationTime: cache ? void 0 : 500
1430
+ });
1431
+ }
1432
+ return makeRequest();
1433
+ });
1434
+ }
1435
+
1436
+ var __defProp$8 = Object.defineProperty;
1437
+ var __defProps$4 = Object.defineProperties;
1438
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
1439
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
1440
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
1441
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
1442
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1443
+ var __spreadValues$6 = (a, b) => {
1444
+ for (var prop in b || (b = {}))
1445
+ if (__hasOwnProp$6.call(b, prop))
1446
+ __defNormalProp$8(a, prop, b[prop]);
1447
+ if (__getOwnPropSymbols$6)
1448
+ for (var prop of __getOwnPropSymbols$6(b)) {
1449
+ if (__propIsEnum$6.call(b, prop))
1450
+ __defNormalProp$8(a, prop, b[prop]);
1451
+ }
1452
+ return a;
1453
+ };
1454
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1455
+ var __objRest$1 = (source, exclude) => {
1456
+ var target = {};
1457
+ for (var prop in source)
1458
+ if (__hasOwnProp$6.call(source, prop) && exclude.indexOf(prop) < 0)
1459
+ target[prop] = source[prop];
1460
+ if (source != null && __getOwnPropSymbols$6)
1461
+ for (var prop of __getOwnPropSymbols$6(source)) {
1462
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$6.call(source, prop))
1463
+ target[prop] = source[prop];
1464
+ }
1465
+ return target;
1466
+ };
1467
+ var __async$5 = (__this, __arguments, generator) => {
1468
+ return new Promise((resolve, reject) => {
1469
+ var fulfilled = (value) => {
1470
+ try {
1471
+ step(generator.next(value));
1472
+ } catch (e) {
1473
+ reject(e);
1474
+ }
1475
+ };
1476
+ var rejected = (value) => {
1477
+ try {
1478
+ step(generator.throw(value));
1479
+ } catch (e) {
1480
+ reject(e);
1481
+ }
1482
+ };
1483
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1484
+ step((generator = generator.apply(__this, __arguments)).next());
1485
+ });
1486
+ };
1487
+ function routeURL(name, baseUrl, routeData, ...rest) {
1488
+ const [template, ...params] = routeData[name];
1489
+ const first = rest[0];
1490
+ let sub;
1491
+ if (first === void 0) {
1492
+ sub = [];
1493
+ } else if (typeof first === "object" && first !== null) {
1494
+ if (rest.length > 1) {
1495
+ throw new Error("Too many arguments for route(name, object)!");
1496
+ }
1497
+ sub = [];
1498
+ for (const [p, v] of Object.entries(first)) {
1499
+ sub[params.indexOf(p)] = String(v);
1500
+ }
1501
+ } else {
1502
+ sub = rest.map((v) => String(v));
1503
+ }
1504
+ return fixUrlStr(
1505
+ baseUrl + template.replace(/\{(\w+)\}/g, function(m, a) {
1506
+ const idx = parseInt(a);
1507
+ const value = sub[idx];
1508
+ if (value === void 0) {
1509
+ const msg = `Undefined parameter ${idx} in "${template}".`;
1510
+ throw new Error(msg);
1511
+ }
1512
+ return String(value);
1513
+ })
1514
+ );
1515
+ }
1516
+ function route(name, connector, ...rest) {
1517
+ const result = {
1518
+ url: (opt) => __async$5(this, null, function* () {
1519
+ var _a;
1520
+ const routeData = yield connector.connect();
1521
+ const template = routeURL(
1522
+ name,
1523
+ (_a = connector.options.baseUrl) != null ? _a : "",
1524
+ routeData,
1525
+ ...rest
1526
+ );
1527
+ return generateUrl(template, opt == null ? void 0 : opt.query);
1528
+ })
1529
+ };
1530
+ const methods = ["get", "post", "put", "delete", "patch"];
1531
+ for (const method of methods) {
1532
+ const methodResp = (requestOptions) => __async$5(this, null, function* () {
1533
+ var _b;
1534
+ const _a = requestOptions || {}, { headers: optHeaders } = _a, restOpt = __objRest$1(_a, ["headers"]);
1535
+ const routeData = yield connector.connect();
1536
+ const template = routeURL(
1537
+ name,
1538
+ (_b = connector.options.baseUrl) != null ? _b : "",
1539
+ routeData,
1540
+ ...rest
1541
+ );
1542
+ const headers = objectRemoveEmpty(__spreadValues$6(__spreadValues$6({}, connector.getAuthorizationHeaders()), optHeaders != null ? optHeaders : {}));
1543
+ return request(
1544
+ template,
1545
+ __spreadProps$4(__spreadValues$6({
1546
+ headers
1547
+ }, restOpt), {
1548
+ method
1549
+ }),
1550
+ connector.cache
1551
+ );
1552
+ });
1553
+ result[method] = methodResp;
1554
+ }
1555
+ return result;
1556
+ }
1557
+
1558
+ function isObject(val) {
1559
+ return Object.prototype.toString.call(val) === "[object Object]";
1560
+ }
1561
+
1562
+ let loadData;
1563
+ {
1564
+ loadData = (url, callback, options = {}, error, onCancel) => {
1565
+ options.method = options.method || "GET";
1566
+ const xhr = new XMLHttpRequest();
1567
+ xhr.open(options.method || "GET", url, true);
1568
+ if (options.responseType === "blob") {
1569
+ xhr.responseType = options.responseType;
1570
+ }
1571
+ const getResponseText = () => {
1572
+ try {
1573
+ return JSON.parse(xhr.responseText);
1574
+ } catch (er) {
1575
+ return xhr.responseText;
1576
+ }
1577
+ };
1578
+ const processingResponse = (forError = false) => {
1579
+ const cb = forError ? error : callback;
1580
+ if (options.responseType === "blob") {
1581
+ cb(xhr.response);
1582
+ } else {
1583
+ if (xhr.responseText) {
1584
+ cb(getResponseText());
1585
+ } else {
1586
+ error({ message: "" });
1587
+ }
1588
+ }
1589
+ };
1590
+ xhr.onload = () => {
1591
+ if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1592
+ error(new NgwError(getResponseText()));
1593
+ }
1594
+ processingResponse();
1595
+ };
1596
+ xhr.onerror = (er) => {
1597
+ if (xhr.status === 0) {
1598
+ error(new NetworkError(url));
1599
+ } else {
1600
+ error(er);
1601
+ }
1602
+ };
1603
+ xhr.upload.onprogress = function(e) {
1604
+ if (e.lengthComputable) {
1605
+ const percentComplete = e.loaded / e.total * 100;
1606
+ if (options.onProgress) {
1607
+ options.onProgress(percentComplete, e);
1608
+ }
1609
+ }
1610
+ };
1611
+ const headers = options.headers;
1612
+ if (headers) {
1613
+ for (const h in headers) {
1614
+ const header = headers[h];
1615
+ if (typeof header === "string") {
1616
+ xhr.setRequestHeader(h, header);
1617
+ }
1618
+ }
1619
+ }
1620
+ if (options.withCredentials !== void 0) {
1621
+ xhr.withCredentials = options.withCredentials;
1622
+ }
1623
+ let data;
1624
+ if (options.file) {
1625
+ data = new FormData();
1626
+ data.append("file", options.file);
1627
+ if (options.data) {
1628
+ for (const d in options.data) {
1629
+ data.append(d, data[d]);
1630
+ }
1631
+ }
1632
+ } else {
1633
+ data = options.data ? typeof options.data === "string" ? options.data : JSON.stringify(options.data) : null;
1634
+ }
1635
+ if (onCancel) {
1636
+ onCancel(() => {
1637
+ xhr.abort();
1638
+ });
1639
+ }
1640
+ xhr.send(data);
1641
+ };
1642
+ }
1643
+
1644
+ const templateRe = /\{ *([\w_-]+) *\}/g;
1645
+ function template(str, data) {
1646
+ return str.replace(templateRe, (s, key) => {
1647
+ let value = data[key];
1648
+ if (value === void 0) {
1649
+ throw new Error("No value provided for letiable " + s);
1650
+ } else if (typeof value === "function") {
1651
+ value = value(data);
1652
+ }
1653
+ return value;
1654
+ });
1655
+ }
1656
+
1657
+ var __defProp$7 = Object.defineProperty;
1658
+ var __defProps$3 = Object.defineProperties;
1659
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
1660
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
1661
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
1662
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
1663
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1664
+ var __spreadValues$5 = (a, b) => {
1665
+ for (var prop in b || (b = {}))
1666
+ if (__hasOwnProp$5.call(b, prop))
1667
+ __defNormalProp$7(a, prop, b[prop]);
1668
+ if (__getOwnPropSymbols$5)
1669
+ for (var prop of __getOwnPropSymbols$5(b)) {
1670
+ if (__propIsEnum$5.call(b, prop))
1671
+ __defNormalProp$7(a, prop, b[prop]);
1672
+ }
1673
+ return a;
1674
+ };
1675
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
1676
+ var __objRest = (source, exclude) => {
1677
+ var target = {};
1678
+ for (var prop in source)
1679
+ if (__hasOwnProp$5.call(source, prop) && exclude.indexOf(prop) < 0)
1680
+ target[prop] = source[prop];
1681
+ if (source != null && __getOwnPropSymbols$5)
1682
+ for (var prop of __getOwnPropSymbols$5(source)) {
1683
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$5.call(source, prop))
1684
+ target[prop] = source[prop];
1685
+ }
1686
+ return target;
1687
+ };
1688
+ var __publicField$4 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
1689
+ var __async$4 = (__this, __arguments, generator) => {
1690
+ return new Promise((resolve, reject) => {
1691
+ var fulfilled = (value) => {
1692
+ try {
1693
+ step(generator.next(value));
1694
+ } catch (e) {
1695
+ reject(e);
1696
+ }
1697
+ };
1698
+ var rejected = (value) => {
1699
+ try {
1700
+ step(generator.throw(value));
1701
+ } catch (e) {
1702
+ reject(e);
1703
+ }
1704
+ };
1705
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1706
+ step((generator = generator.apply(__this, __arguments)).next());
1707
+ });
1708
+ };
1709
+ let ID = 0;
1710
+ let REQUEST_ID = 0;
1711
+ class NgwConnector {
1712
+ constructor(options) {
1713
+ this.options = options;
1714
+ __publicField$4(this, "id", ID++);
1715
+ __publicField$4(this, "emitter", new EventEmitter());
1716
+ __publicField$4(this, "user");
1717
+ __publicField$4(this, "cache");
1718
+ __publicField$4(this, "withCredentials");
1719
+ __publicField$4(this, "client", `NextGIS-NGW-Connector/${pkg.version}`);
1720
+ __publicField$4(this, "routeStr", "/api/component/pyramid/route");
1721
+ __publicField$4(this, "activeRequests", {});
1722
+ __publicField$4(this, "requestTransform");
1723
+ const exist = findConnector(options);
1724
+ this.cache = new Cache({ namespace: options.cacheId });
1725
+ if (exist) {
1726
+ return exist;
1727
+ } else {
1728
+ const { route: route2, requestTransform, withCredentials } = this.options;
1729
+ if (route2) {
1730
+ this.routeStr = route2;
1731
+ }
1732
+ if (requestTransform) {
1733
+ this.requestTransform = requestTransform;
1734
+ }
1735
+ if (withCredentials !== void 0) {
1736
+ this.withCredentials = withCredentials;
1737
+ }
1738
+ addConnector(this);
1739
+ }
1740
+ }
1741
+ /**
1742
+ * Clear the cache.
1743
+ */
1744
+ clearCache() {
1745
+ this.cache.clean();
1746
+ }
1747
+ setRequestTransform(requestTransform) {
1748
+ this.requestTransform = requestTransform;
1749
+ }
1750
+ /**
1751
+ * Fast way to specify the connection address to NextGIS Web.
1752
+ * The current connection will be severed.
1753
+ * @param baseUrl - NGW url
1754
+ */
1755
+ setNgw(baseUrl) {
1756
+ this.logout();
1757
+ this.options.baseUrl = baseUrl;
1758
+ addConnector(this);
1759
+ }
1760
+ /**
1761
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
1762
+ * @remarks
1763
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1764
+ * Can be used to check connection.
1765
+ * @example
1766
+ * ```javascript
1767
+ * const connector = new NgwConnector({ baseUrl: 'https://demo.nextgis.com' });
1768
+ * connector.connect()
1769
+ * .then(() => console.log('Ok'))
1770
+ * .catch((er) => console.log('Connection problem', er));
1771
+ * ```
1772
+ */
1773
+ connect() {
1774
+ return __async$4(this, null, function* () {
1775
+ const auth = this.options.auth;
1776
+ if (auth) {
1777
+ const { login, password } = auth;
1778
+ if (login && password) {
1779
+ yield this._login({ login, password });
1780
+ }
1781
+ }
1782
+ const routeUrl = `${this.routeStr}?client=${this.client}`;
1783
+ return yield this.makeQuery(
1784
+ routeUrl,
1785
+ {},
1786
+ {
1787
+ cacheName: "route",
1788
+ cache: true,
1789
+ cacheProps: {
1790
+ id: this.id,
1791
+ auth,
1792
+ baseUrl: this.options.baseUrl
1793
+ }
1794
+ }
1795
+ );
1796
+ });
1797
+ }
1798
+ /**
1799
+ * Quick way to change NextGIS Web user.
1800
+ * @param credentials - New user credentials
1801
+ */
1802
+ login(credentials, options) {
1803
+ this.logout();
1804
+ addConnector(this);
1805
+ return this._login(credentials, options);
1806
+ }
1807
+ /**
1808
+ * Disconnecting a user. Aborting all current requests
1809
+ */
1810
+ logout() {
1811
+ this.abort();
1812
+ removeConnector(this);
1813
+ this.options.auth = void 0;
1814
+ this.user = void 0;
1815
+ this.clearCache();
1816
+ this.emitter.emit("logout");
1817
+ }
1818
+ getUserInfo(credentials, options) {
1819
+ return __async$4(this, null, function* () {
1820
+ if (this.user && this.user.id) {
1821
+ return this.user;
1822
+ }
1823
+ if (credentials) {
1824
+ this.options.auth = credentials;
1825
+ }
1826
+ const options_ = __spreadValues$5({
1827
+ headers: this.getAuthorizationHeaders(credentials),
1828
+ cache: true
1829
+ }, options);
1830
+ return this.makeQuery(
1831
+ "/api/component/auth/current_user",
1832
+ {},
1833
+ options_
1834
+ );
1835
+ });
1836
+ }
1837
+ /**
1838
+ * Obtaining the required Headers for authentication of requests in the NGW.
1839
+ */
1840
+ getAuthorizationHeaders(credentials) {
1841
+ const client = this.makeClientId(credentials);
1842
+ if (client) {
1843
+ return {
1844
+ Authorization: `Basic ${client}`
1845
+ };
1846
+ }
1847
+ return {};
1848
+ }
1849
+ makeClientId(credentials) {
1850
+ credentials = credentials || this.options.auth;
1851
+ if (credentials) {
1852
+ const { login, password } = credentials;
1853
+ const encodedStr = [login, password].map(encodeURIComponent).join(":");
1854
+ {
1855
+ return window.btoa(encodedStr);
1856
+ }
1857
+ }
1858
+ }
1859
+ /** Stop all api requests */
1860
+ abort() {
1861
+ for (const abortController of Object.values(this.activeRequests)) {
1862
+ abortController.abort();
1863
+ }
1864
+ this.activeRequests = {};
1865
+ }
1866
+ getActiveApiRequests() {
1867
+ return __spreadValues$5({}, this.activeRequests);
1868
+ }
1869
+ route(name, ...rest) {
1870
+ return route(name, this, ...rest);
1871
+ }
1872
+ /**
1873
+ * Send request to NGW.
1874
+ * @param url - URL address to NGW
1875
+ * @param params - Query params
1876
+ * @param options - Request options
1877
+ */
1878
+ makeQuery(_0, _1) {
1879
+ return __async$4(this, arguments, function* (url, params, options = {}) {
1880
+ var _b;
1881
+ url = (this.options.baseUrl ? this.options.baseUrl : "") + url;
1882
+ if (!url) {
1883
+ throw new Error("Empty `url` not allowed");
1884
+ }
1885
+ if (params) {
1886
+ const _a = params, restParams = __objRest(_a, ["paramList"]);
1887
+ url = template(url, restParams);
1888
+ }
1889
+ url = encodeURI(fixUrlStr(url));
1890
+ options = __spreadValues$5({ withCredentials: this.withCredentials }, options);
1891
+ const {
1892
+ cache,
1893
+ signal: externalSignal,
1894
+ method = "GET",
1895
+ headers,
1896
+ cacheName,
1897
+ cacheProps,
1898
+ responseType,
1899
+ withCredentials
1900
+ } = options;
1901
+ const internalAbortController = new AbortController();
1902
+ const internalSignal = internalAbortController.signal;
1903
+ if (externalSignal) {
1904
+ if (externalSignal.aborted) {
1905
+ throw new AbortError();
1906
+ }
1907
+ externalSignal.addEventListener("abort", () => {
1908
+ internalAbortController.abort();
1909
+ });
1910
+ }
1911
+ options.signal = internalSignal;
1912
+ const createPromise = () => __async$4(this, null, function* () {
1913
+ const id = REQUEST_ID++;
1914
+ this.activeRequests[id] = internalAbortController;
1915
+ try {
1916
+ return this._loadData(url, options);
1917
+ } finally {
1918
+ this._cleanActiveRequest(id);
1919
+ }
1920
+ });
1921
+ if (method === "GET") {
1922
+ const cacheOptions = cacheProps ? cacheProps : __spreadProps$3(__spreadValues$5({}, objectRemoveEmpty({
1923
+ headers,
1924
+ withCredentials,
1925
+ responseType,
1926
+ baseUrl: this.options.baseUrl,
1927
+ userId: (_b = this.user) == null ? void 0 : _b.id
1928
+ })), {
1929
+ params
1930
+ });
1931
+ return this.cache.add(cacheName || url, createPromise, {
1932
+ props: cacheOptions,
1933
+ expirationTime: cache ? void 0 : 500
1934
+ });
1935
+ }
1936
+ return createPromise();
1937
+ });
1938
+ }
1939
+ _loadData(url, options) {
1940
+ options.responseType = options.responseType || "json";
1941
+ return new Promise((resolve, reject) => {
1942
+ var _a;
1943
+ if (this.user) {
1944
+ options = options || {};
1945
+ options.headers = __spreadValues$5(__spreadValues$5({}, this.getAuthorizationHeaders()), options.headers);
1946
+ }
1947
+ if (this.requestTransform) {
1948
+ const [transUrl, transOptions] = this.requestTransform(url, options);
1949
+ url = transUrl;
1950
+ options = transOptions;
1951
+ }
1952
+ let runOnAbort = void 0;
1953
+ loadData(url, resolve, options, reject, (handler) => {
1954
+ runOnAbort = handler;
1955
+ });
1956
+ (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
1957
+ if (runOnAbort !== void 0) {
1958
+ runOnAbort();
1959
+ }
1960
+ reject(new AbortError());
1961
+ });
1962
+ }).catch((httpError) => {
1963
+ if (httpError.name !== "AbortError") {
1964
+ {
1965
+ console.warn("DEV WARN", httpError);
1966
+ }
1967
+ const er = this._handleHttpError(httpError);
1968
+ if (er) {
1969
+ throw er;
1970
+ }
1971
+ }
1972
+ throw httpError;
1973
+ });
1974
+ }
1975
+ _login(credentials, options) {
1976
+ return __async$4(this, null, function* () {
1977
+ try {
1978
+ const data = yield this.getUserInfo(credentials, options);
1979
+ this.user = data;
1980
+ this.emitter.emit("login", data);
1981
+ return data;
1982
+ } catch (er) {
1983
+ this.emitter.emit("login:error", er);
1984
+ throw er;
1985
+ }
1986
+ });
1987
+ }
1988
+ _cleanActiveRequest(requestId) {
1989
+ delete this.activeRequests[requestId];
1990
+ }
1991
+ _handleHttpError(er) {
1992
+ if (er) {
1993
+ if (er instanceof NgwError) {
1994
+ if (er.exception === "nextgisweb.resource.exception.ResourceNotFound") {
1995
+ throw new ResourceNotFoundError(er);
1996
+ } else if (er.exception === "nextgisweb.core.exception.InsufficientPermissions") {
1997
+ throw new InsufficientPermissionsError(er);
1998
+ }
1999
+ }
2000
+ }
2001
+ return er;
2002
+ }
2003
+ }
2004
+ __publicField$4(NgwConnector, "errors", errors);
2005
+
2006
+ function resourceCompare(res1, res2) {
2007
+ return objectDeepEqual(res1, res2);
2008
+ }
2009
+
2010
+ const exclude = ["description"];
2011
+ function resourceToQuery(resource, prefix = "") {
2012
+ prefix = prefix ? prefix + "__" : "";
2013
+ const query = {};
2014
+ for (const [key, value] of Object.entries(resource)) {
2015
+ if (exclude.indexOf(key) === -1) {
2016
+ if (isObject(value)) {
2017
+ if (key === "owner_user") {
2018
+ const children = resourceToQuery(
2019
+ value,
2020
+ key
2021
+ );
2022
+ Object.assign(query, children);
2023
+ } else if (key === "parent" && "id" in value) {
2024
+ query.parent_id = value.id;
2025
+ }
2026
+ } else if (defined(value)) {
2027
+ query[prefix + key] = value;
2028
+ }
2029
+ }
2030
+ }
2031
+ return query;
2032
+ }
2033
+
2034
+ var __defProp$6 = Object.defineProperty;
2035
+ var __defProps$2 = Object.defineProperties;
2036
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
2037
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
2038
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
2039
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
2040
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2041
+ var __spreadValues$4 = (a, b) => {
2042
+ for (var prop in b || (b = {}))
2043
+ if (__hasOwnProp$4.call(b, prop))
2044
+ __defNormalProp$6(a, prop, b[prop]);
2045
+ if (__getOwnPropSymbols$4)
2046
+ for (var prop of __getOwnPropSymbols$4(b)) {
2047
+ if (__propIsEnum$4.call(b, prop))
2048
+ __defNormalProp$6(a, prop, b[prop]);
2049
+ }
2050
+ return a;
2051
+ };
2052
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
2053
+ var __publicField$3 = (obj, key, value) => __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
2054
+ var __async$3 = (__this, __arguments, generator) => {
2055
+ return new Promise((resolve, reject) => {
2056
+ var fulfilled = (value) => {
2057
+ try {
2058
+ step(generator.next(value));
2059
+ } catch (e) {
2060
+ reject(e);
2061
+ }
2062
+ };
2063
+ var rejected = (value) => {
2064
+ try {
2065
+ step(generator.throw(value));
2066
+ } catch (e) {
2067
+ reject(e);
2068
+ }
2069
+ };
2070
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
2071
+ step((generator = generator.apply(__this, __arguments)).next());
2072
+ });
2073
+ };
2074
+ class ResourcesControl {
2075
+ constructor({
2076
+ connector,
2077
+ cacheId
2078
+ }) {
2079
+ __publicField$3(this, "cache");
2080
+ __publicField$3(this, "connector");
2081
+ this.connector = connector;
2082
+ this.cache = new Cache({ namespace: cacheId });
2083
+ }
2084
+ // -------------------------------------------------------------------------
2085
+ // Resource Methods
2086
+ // -------------------------------------------------------------------------
2087
+ /**
2088
+ * Receive resource from NGW by id, keyname or search-object parameter.
2089
+ * @param resource - Resource id, keyname or search-object
2090
+ *
2091
+ * @remarks
2092
+ * Fetching resource would be cached to speed up next call
2093
+ */
2094
+ getOne(resource, requestOptions) {
2095
+ const opt = __spreadValues$4({}, requestOptions);
2096
+ if (typeof resource === "string") ; else if (typeof resource === "number") ; else if (isObject(resource)) {
2097
+ if (resource.id !== void 0) {
2098
+ resource.id;
2099
+ } else {
2100
+ if (resource.keyname) {
2101
+ resource.keyname;
2102
+ }
2103
+ if (resource.display_name) {
2104
+ resource.display_name;
2105
+ }
2106
+ }
2107
+ }
2108
+ if (typeof resource === "string") {
2109
+ return this._fetchResourceBy({ keyname: resource }, opt);
2110
+ } else if (typeof resource === "number") {
2111
+ return this._fetchResourceById(resource, opt);
2112
+ } else if (isObject(resource)) {
2113
+ return this._fetchResourceBy(resource, opt);
2114
+ }
2115
+ return Promise.resolve(void 0);
2116
+ }
2117
+ getOneOrFail(resource, requestOptions) {
2118
+ return this.getOne(resource, requestOptions).then((res) => {
2119
+ if (res) {
2120
+ return res;
2121
+ }
2122
+ throw new ResourceNotFoundError();
2123
+ });
2124
+ }
2125
+ /**
2126
+ * A fast way to retrieve resource ID for any resource definition.
2127
+ * @param resource - Any available resource definition
2128
+ *
2129
+ * @remarks
2130
+ * There are situations when exactly the resource id is needed
2131
+ * (for example, to compose the correct request to the api)
2132
+ * then this method will come in handy to facilitate the extraction of the identifier
2133
+ * if the resource is specified through a keyname or other parameters.
2134
+ */
2135
+ getId(resource, requestOptions) {
2136
+ if (typeof resource === "number") {
2137
+ return Promise.resolve(resource);
2138
+ } else if (typeof resource === "string" || isObject(resource)) {
2139
+ return this.getOne(resource, requestOptions).then((res) => {
2140
+ if (res) {
2141
+ return res.resource.id;
2142
+ }
2143
+ });
2144
+ }
2145
+ return Promise.resolve(void 0);
2146
+ }
2147
+ /**
2148
+ * A fast way to retrieve resource ID for any resource definition.
2149
+ * @param resource - Any available resource definition
2150
+ *
2151
+ * @remarks
2152
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
2153
+ * To not make one more checks if the resource is definitely exists
2154
+ */
2155
+ getIdOrFail(resource, requestOptions) {
2156
+ return this.getId(resource, requestOptions).then((resp) => {
2157
+ if (resp === void 0) {
2158
+ throw new Error();
2159
+ }
2160
+ return resp;
2161
+ });
1078
2162
  }
1079
2163
  getMany(resource, requestOptions) {
1080
2164
  return this._resourceCacheFilter(resource).then((items) => {
@@ -1085,9 +2169,11 @@ class ResourcesControl {
1085
2169
  } else {
1086
2170
  Object.assign(query, resourceToQuery(resource));
1087
2171
  }
1088
- return this.connector.get("resource.search", requestOptions, __spreadValues$5({
1089
- serialization: "full"
1090
- }, query)).then((resources) => {
2172
+ return this.connector.route("resource.search").get(__spreadProps$2(__spreadValues$4({}, requestOptions), {
2173
+ query: __spreadValues$4({
2174
+ serialization: "full"
2175
+ }, query)
2176
+ })).then((resources) => {
1091
2177
  if ((requestOptions == null ? void 0 : requestOptions.cache) && resources) {
1092
2178
  for (const x of resources) {
1093
2179
  this.cache.add("resource.item", Promise.resolve(x), {
@@ -1103,7 +2189,8 @@ class ResourcesControl {
1103
2189
  }
1104
2190
  getParent(resource, requestOptions) {
1105
2191
  return this.getOne(resource, requestOptions).then((child) => {
1106
- if (child) {
2192
+ var _a, _b;
2193
+ if ((_b = (_a = child == null ? void 0 : child.resource) == null ? void 0 : _a.parent) == null ? void 0 : _b.id) {
1107
2194
  return this.getOne(child.resource.parent.id, requestOptions);
1108
2195
  }
1109
2196
  return Promise.resolve(void 0);
@@ -1135,10 +2222,21 @@ class ResourcesControl {
1135
2222
  }
1136
2223
  });
1137
2224
  }
1138
- _getChildrenOf(parent, requestOptions, _items = []) {
1139
- return this.connector.get("resource.collection", requestOptions, {
1140
- parent
1141
- }).then((items) => {
2225
+ _getChildrenOf(_0, _1) {
2226
+ return __async$3(this, arguments, function* (parentDef, requestOptions, _items = []) {
2227
+ let parent = void 0;
2228
+ if (typeof parentDef === "string") {
2229
+ parent = yield this.getId(parentDef, requestOptions);
2230
+ } else if (typeof parentDef === "object") {
2231
+ parent = parentDef.id;
2232
+ } else {
2233
+ parent = parentDef;
2234
+ }
2235
+ const items = yield this.connector.route("resource.collection").get(__spreadProps$2(__spreadValues$4({}, requestOptions), {
2236
+ query: {
2237
+ parent
2238
+ }
2239
+ }));
1142
2240
  const recursivePromises = [];
1143
2241
  for (const item of items) {
1144
2242
  if (requestOptions == null ? void 0 : requestOptions.cache) {
@@ -1162,7 +2260,7 @@ class ResourcesControl {
1162
2260
  });
1163
2261
  }
1164
2262
  _cleanResourceItemCache(id) {
1165
- return __async$4(this, null, function* () {
2263
+ return __async$3(this, null, function* () {
1166
2264
  var _a;
1167
2265
  const all = this.cache.all();
1168
2266
  const toDelete = [];
@@ -1187,7 +2285,7 @@ class ResourcesControl {
1187
2285
  });
1188
2286
  }
1189
2287
  _fetchResourceById(id, requestOptions) {
1190
- return this.connector.get("resource.item", requestOptions, { id });
2288
+ return this.connector.route("resource.item", { id }).get(requestOptions);
1191
2289
  }
1192
2290
  _fetchResourceBy(resource, requestOptions) {
1193
2291
  return this.getMany(resource, requestOptions).then((resources) => {
@@ -1208,86 +2306,30 @@ class ResourcesControl {
1208
2306
  }
1209
2307
  return resourceCompare(resource, x.resource);
1210
2308
  }
1211
- });
1212
- return items;
1213
- }
1214
- );
1215
- }
1216
- }
1217
-
1218
- const CONNECTORS = [];
1219
- function addConnector(connector) {
1220
- CONNECTORS.push(connector);
1221
- }
1222
- function findConnector(options) {
1223
- return CONNECTORS.find((x) => {
1224
- if (x.options.baseUrl === options.baseUrl) {
1225
- if (options.auth) {
1226
- if (x.options.auth) {
1227
- return objectDeepEqual(x.options.auth, options.auth);
1228
- }
1229
- } else {
1230
- return true;
1231
- }
1232
- }
1233
- });
1234
- }
1235
- function removeConnector(connector) {
1236
- const index = CONNECTORS.indexOf(connector);
1237
- if (index !== -1) {
1238
- CONNECTORS.splice(index, 1);
1239
- }
1240
- }
1241
-
1242
- class AbortError extends Error {
1243
- constructor(message = "AbortError") {
1244
- super(message);
1245
- this.name = "AbortError";
1246
- }
1247
- }
1248
-
1249
- var __defProp$7 = Object.defineProperty;
1250
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1251
- var __publicField$4 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
1252
- class InsufficientPermissionsError extends NgwError {
1253
- constructor(obj) {
1254
- super(obj);
1255
- __publicField$4(this, "name", "InsufficientPermissionsError");
1256
- __publicField$4(this, "exception", "nextgisweb.core.exception.InsufficientPermissions");
1257
- Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1258
- }
1259
- }
1260
-
1261
- const templateRe = /\{ *([\w_-]+) *\}/g;
1262
- function template(str, data) {
1263
- return str.replace(templateRe, (s, key) => {
1264
- let value = data[key];
1265
- if (value === void 0) {
1266
- throw new Error("No value provided for letiable " + s);
1267
- } else if (typeof value === "function") {
1268
- value = value(data);
1269
- }
1270
- return value;
1271
- });
2309
+ });
2310
+ return items;
2311
+ }
2312
+ );
2313
+ }
1272
2314
  }
1273
2315
 
1274
- var __defProp$6 = Object.defineProperty;
1275
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
1276
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
1277
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
1278
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1279
- var __spreadValues$4 = (a, b) => {
2316
+ var __defProp$5 = Object.defineProperty;
2317
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
2318
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
2319
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
2320
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2321
+ var __spreadValues$3 = (a, b) => {
1280
2322
  for (var prop in b || (b = {}))
1281
- if (__hasOwnProp$4.call(b, prop))
1282
- __defNormalProp$6(a, prop, b[prop]);
1283
- if (__getOwnPropSymbols$4)
1284
- for (var prop of __getOwnPropSymbols$4(b)) {
1285
- if (__propIsEnum$4.call(b, prop))
1286
- __defNormalProp$6(a, prop, b[prop]);
2323
+ if (__hasOwnProp$3.call(b, prop))
2324
+ __defNormalProp$5(a, prop, b[prop]);
2325
+ if (__getOwnPropSymbols$3)
2326
+ for (var prop of __getOwnPropSymbols$3(b)) {
2327
+ if (__propIsEnum$3.call(b, prop))
2328
+ __defNormalProp$5(a, prop, b[prop]);
1287
2329
  }
1288
2330
  return a;
1289
2331
  };
1290
- var __async$3 = (__this, __arguments, generator) => {
2332
+ var __async$2 = (__this, __arguments, generator) => {
1291
2333
  return new Promise((resolve, reject) => {
1292
2334
  var fulfilled = (value) => {
1293
2335
  try {
@@ -1308,7 +2350,7 @@ var __async$3 = (__this, __arguments, generator) => {
1308
2350
  });
1309
2351
  };
1310
2352
  function apiRequest(opt) {
1311
- return __async$3(this, null, function* () {
2353
+ return __async$2(this, null, function* () {
1312
2354
  const { params, name, connector, requestOptions } = opt;
1313
2355
  const apiItems = yield connector.connect();
1314
2356
  let apiItem = apiItems && apiItems[name];
@@ -1337,334 +2379,48 @@ function apiRequest(opt) {
1337
2379
  });
1338
2380
  }
1339
2381
  for (const p in params) {
1340
- if (apiItem.indexOf(p) === -1) {
1341
- paramArray.push(`${p}=${params[p]}`);
1342
- }
1343
- }
1344
- if (paramArray.length) {
1345
- url = `${url}?${paramArray.join("&")}`;
1346
- }
1347
- }
1348
- if (url) {
1349
- return connector.makeQuery(url, params, __spreadValues$4({
1350
- cacheName: name
1351
- }, requestOptions));
1352
- } else {
1353
- throw new Error("Request URL is not set");
1354
- }
1355
- } else {
1356
- return void 0;
1357
- }
1358
- });
1359
- }
1360
-
1361
- var __defProp$5 = Object.defineProperty;
1362
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1363
- var __publicField$3 = (obj, key, value) => __defNormalProp$5(obj, key + "" , value);
1364
- class NetworkError extends Error {
1365
- constructor(url) {
1366
- super();
1367
- __publicField$3(this, "name", "NetworkError");
1368
- Object.setPrototypeOf(this, NetworkError.prototype);
1369
- this.message = `Unable to request ${url}.
1370
- Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`;
1371
- }
1372
- }
1373
-
1374
- let loadData;
1375
- {
1376
- loadData = (url, callback, options = {}, error, onCancel) => {
1377
- options.method = options.method || "GET";
1378
- const xhr = new XMLHttpRequest();
1379
- xhr.open(options.method || "GET", url, true);
1380
- if (options.responseType === "blob") {
1381
- xhr.responseType = options.responseType;
1382
- }
1383
- const getResponseText = () => {
1384
- try {
1385
- return JSON.parse(xhr.responseText);
1386
- } catch (er) {
1387
- return xhr.responseText;
1388
- }
1389
- };
1390
- const processingResponse = (forError = false) => {
1391
- const cb = forError ? error : callback;
1392
- if (options.responseType === "blob") {
1393
- cb(xhr.response);
1394
- } else {
1395
- if (xhr.responseText) {
1396
- cb(getResponseText());
1397
- } else {
1398
- error({ message: "" });
1399
- }
1400
- }
1401
- };
1402
- xhr.onload = () => {
1403
- if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1404
- error(new NgwError(getResponseText()));
1405
- }
1406
- processingResponse();
1407
- };
1408
- xhr.onerror = (er) => {
1409
- if (xhr.status === 0) {
1410
- error(new NetworkError(url));
1411
- } else {
1412
- error(er);
1413
- }
1414
- };
1415
- xhr.upload.onprogress = function(e) {
1416
- if (e.lengthComputable) {
1417
- const percentComplete = e.loaded / e.total * 100;
1418
- if (options.onProgress) {
1419
- options.onProgress(percentComplete, e);
1420
- }
1421
- }
1422
- };
1423
- const headers = options.headers;
1424
- if (headers) {
1425
- for (const h in headers) {
1426
- const header = headers[h];
1427
- if (typeof header === "string") {
1428
- xhr.setRequestHeader(h, header);
1429
- }
1430
- }
1431
- }
1432
- if (options.withCredentials !== void 0) {
1433
- xhr.withCredentials = options.withCredentials;
1434
- }
1435
- let data;
1436
- if (options.file) {
1437
- data = new FormData();
1438
- data.append("file", options.file);
1439
- if (options.data) {
1440
- for (const d in options.data) {
1441
- data.append(d, data[d]);
1442
- }
1443
- }
1444
- } else {
1445
- data = options.data ? typeof options.data === "string" ? options.data : JSON.stringify(options.data) : null;
1446
- }
1447
- if (onCancel) {
1448
- onCancel(() => {
1449
- xhr.abort();
1450
- });
1451
- }
1452
- xhr.send(data);
1453
- };
1454
- }
1455
-
1456
- var __defProp$4 = Object.defineProperty;
1457
- var __defProps$2 = Object.defineProperties;
1458
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
1459
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
1460
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1461
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
1462
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1463
- var __spreadValues$3 = (a, b) => {
1464
- for (var prop in b || (b = {}))
1465
- if (__hasOwnProp$3.call(b, prop))
1466
- __defNormalProp$4(a, prop, b[prop]);
1467
- if (__getOwnPropSymbols$3)
1468
- for (var prop of __getOwnPropSymbols$3(b)) {
1469
- if (__propIsEnum$3.call(b, prop))
1470
- __defNormalProp$4(a, prop, b[prop]);
1471
- }
1472
- return a;
1473
- };
1474
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
1475
- var __objRest = (source, exclude) => {
1476
- var target = {};
1477
- for (var prop in source)
1478
- if (__hasOwnProp$3.call(source, prop) && exclude.indexOf(prop) < 0)
1479
- target[prop] = source[prop];
1480
- if (source != null && __getOwnPropSymbols$3)
1481
- for (var prop of __getOwnPropSymbols$3(source)) {
1482
- if (exclude.indexOf(prop) < 0 && __propIsEnum$3.call(source, prop))
1483
- target[prop] = source[prop];
1484
- }
1485
- return target;
1486
- };
1487
- var __publicField$2 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
1488
- var __async$2 = (__this, __arguments, generator) => {
1489
- return new Promise((resolve, reject) => {
1490
- var fulfilled = (value) => {
1491
- try {
1492
- step(generator.next(value));
1493
- } catch (e) {
1494
- reject(e);
1495
- }
1496
- };
1497
- var rejected = (value) => {
1498
- try {
1499
- step(generator.throw(value));
1500
- } catch (e) {
1501
- reject(e);
1502
- }
1503
- };
1504
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1505
- step((generator = generator.apply(__this, __arguments)).next());
1506
- });
1507
- };
1508
- let ID = 0;
1509
- let REQUEST_ID = 0;
1510
- class NgwConnector {
1511
- constructor(options) {
1512
- this.options = options;
1513
- __publicField$2(this, "id", ID++);
1514
- __publicField$2(this, "emitter", new EventEmitter());
1515
- __publicField$2(this, "user");
1516
- __publicField$2(this, "resources");
1517
- __publicField$2(this, "cache");
1518
- __publicField$2(this, "routeStr", "/api/component/pyramid/route");
1519
- __publicField$2(this, "activeRequests", {});
1520
- __publicField$2(this, "requestTransform");
1521
- const exist = findConnector(options);
1522
- this.cache = new Cache({ namespace: options.cacheId });
1523
- if (exist) {
1524
- return exist;
1525
- } else {
1526
- if (this.options.route) {
1527
- this.routeStr = this.options.route;
1528
- }
1529
- if (this.options.requestTransform) {
1530
- this.requestTransform = this.options.requestTransform;
1531
- }
1532
- this.resources = new ResourcesControl({
1533
- connector: this,
1534
- cacheId: options.cacheId
1535
- });
1536
- addConnector(this);
1537
- }
1538
- }
1539
- static create(options) {
1540
- return new this(options);
1541
- }
1542
- /**
1543
- * Clear the cache.
1544
- */
1545
- clearCache() {
1546
- this.cache.clean();
1547
- this.resources.cache.clean();
1548
- }
1549
- setRequestTransform(requestTransform) {
1550
- this.requestTransform = requestTransform;
1551
- }
1552
- /**
1553
- * Fast way to specify the connection address to NextGIS Web.
1554
- * The current connection will be severed.
1555
- * @param baseUrl - NGW url
1556
- */
1557
- setNgw(baseUrl) {
1558
- this.logout();
1559
- this.options.baseUrl = baseUrl;
1560
- addConnector(this);
1561
- }
1562
- /**
1563
- * Establishing a connection with NextGIS Web to fulfill all other requests.
1564
- * @remarks
1565
- * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1566
- * Can be used to check connection.
1567
- * @example
1568
- * ```javascript
1569
- * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1570
- * connector.connect()
1571
- * .then(() => console.log('Ok'))
1572
- * .catch((er) => console.log('Connection problem', er));
1573
- * ```
1574
- */
1575
- connect() {
1576
- return __async$2(this, null, function* () {
1577
- const auth = this.options.auth;
1578
- if (auth) {
1579
- const { login, password } = auth;
1580
- if (login && password) {
1581
- yield this._login({ login, password });
1582
- }
1583
- }
1584
- return yield this.makeQuery(
1585
- this.routeStr,
1586
- {},
1587
- {
1588
- cacheName: "route",
1589
- cache: true,
1590
- cacheProps: {
1591
- id: this.id,
1592
- auth,
1593
- baseUrl: this.options.baseUrl
2382
+ if (apiItem.indexOf(p) === -1) {
2383
+ paramArray.push(`${p}=${params[p]}`);
1594
2384
  }
1595
2385
  }
1596
- );
1597
- });
1598
- }
1599
- /**
1600
- * Quick way to change NextGIS Web user.
1601
- * @param credentials - New user credentials
1602
- */
1603
- login(credentials, options) {
1604
- this.logout();
1605
- addConnector(this);
1606
- return this._login(credentials, options);
1607
- }
1608
- /**
1609
- * Disconnecting a user. Aborting all current requests
1610
- */
1611
- logout() {
1612
- this.abort();
1613
- removeConnector(this);
1614
- this.options.auth = void 0;
1615
- this.user = void 0;
1616
- this.clearCache();
1617
- this.emitter.emit("logout");
1618
- }
1619
- getUserInfo(credentials, options) {
1620
- return __async$2(this, null, function* () {
1621
- if (this.user && this.user.id) {
1622
- return this.user;
2386
+ if (paramArray.length) {
2387
+ url = `${url}?${paramArray.join("&")}`;
2388
+ }
1623
2389
  }
1624
- if (credentials) {
1625
- this.options.auth = credentials;
2390
+ if (url) {
2391
+ return connector.makeQuery(url, params, __spreadValues$3({
2392
+ cacheName: name
2393
+ }, requestOptions));
2394
+ } else {
2395
+ throw new Error("Request URL is not set");
1626
2396
  }
1627
- const options_ = __spreadValues$3({
1628
- headers: this.getAuthorizationHeaders(credentials)
1629
- }, options);
1630
- return this.makeQuery(
1631
- "/api/component/auth/current_user",
1632
- {},
1633
- options_
1634
- );
2397
+ } else {
2398
+ return void 0;
2399
+ }
2400
+ });
2401
+ }
2402
+
2403
+ var __defProp$4 = Object.defineProperty;
2404
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2405
+ var __publicField$2 = (obj, key, value) => __defNormalProp$4(obj, key + "" , value);
2406
+ class NgwConnectorExtended extends NgwConnector {
2407
+ constructor(options) {
2408
+ super(options);
2409
+ __publicField$2(this, "resources");
2410
+ this.resources = new ResourcesControl({
2411
+ connector: this,
2412
+ cacheId: options.cacheId
1635
2413
  });
1636
2414
  }
2415
+ static create(options) {
2416
+ return new this(options);
2417
+ }
1637
2418
  /**
1638
- * Obtaining the required Headers for authentication of requests in the NGW.
2419
+ * Clear the cache.
1639
2420
  */
1640
- getAuthorizationHeaders(credentials) {
1641
- const client = this.makeClientId(credentials);
1642
- if (client) {
1643
- return {
1644
- Authorization: `Basic ${client}`
1645
- };
1646
- }
1647
- }
1648
- makeClientId(credentials) {
1649
- credentials = credentials || this.options.auth;
1650
- if (credentials) {
1651
- const { login, password } = credentials;
1652
- const str = `${login}:${password}`;
1653
- const encodedStr = encodeURIComponent(str);
1654
- {
1655
- return window.btoa(encodedStr);
1656
- }
1657
- }
1658
- }
1659
- /** Stop all api requests */
1660
- abort() {
1661
- for (const abortController of Object.values(this.activeRequests)) {
1662
- abortController.abort();
1663
- }
1664
- this.activeRequests = {};
1665
- }
1666
- getActiveApiRequests() {
1667
- return __spreadValues$3({}, this.activeRequests);
2421
+ clearCache() {
2422
+ super.clearCache();
2423
+ this.resources.cache.clean();
1668
2424
  }
1669
2425
  /**
1670
2426
  * Send request to NGW api router.
@@ -1783,74 +2539,6 @@ class NgwConnector {
1783
2539
  options
1784
2540
  );
1785
2541
  }
1786
- /**
1787
- * Send request to NGW.
1788
- * @param url - URL address to NGW
1789
- * @param params - Query params
1790
- * @param options - Request options
1791
- */
1792
- makeQuery(_0, _1) {
1793
- return __async$2(this, arguments, function* (url, params, options = {}) {
1794
- var _b;
1795
- url = (this.options.baseUrl ? this.options.baseUrl : "") + url;
1796
- if (!url) {
1797
- throw new Error("Empty `url` not allowed");
1798
- }
1799
- if (params) {
1800
- const _a = params, restParams = __objRest(_a, ["paramList"]);
1801
- url = template(url, restParams);
1802
- }
1803
- url = encodeURI(fixUrlStr(url));
1804
- const {
1805
- cache,
1806
- signal: externalSignal,
1807
- method = "GET",
1808
- headers,
1809
- cacheName,
1810
- cacheProps,
1811
- responseType,
1812
- withCredentials
1813
- } = options;
1814
- const internalAbortController = new AbortController();
1815
- const internalSignal = internalAbortController.signal;
1816
- if (externalSignal) {
1817
- if (externalSignal.aborted) {
1818
- throw new AbortError();
1819
- }
1820
- externalSignal.addEventListener("abort", () => {
1821
- internalAbortController.abort();
1822
- });
1823
- }
1824
- options.signal = internalSignal;
1825
- const createPromise = () => __async$2(this, null, function* () {
1826
- const id = REQUEST_ID++;
1827
- this.activeRequests[id] = internalAbortController;
1828
- try {
1829
- return this._loadData(url, options);
1830
- } finally {
1831
- this._cleanActiveRequest(id);
1832
- }
1833
- });
1834
- if (cache && method === "GET") {
1835
- const cacheOptions = cacheProps ? cacheProps : __spreadProps$2(__spreadValues$3({}, objectRemoveEmpty({
1836
- headers,
1837
- withCredentials,
1838
- responseType,
1839
- baseUrl: this.options.baseUrl,
1840
- userId: (_b = this.user) == null ? void 0 : _b.id
1841
- })), {
1842
- params
1843
- });
1844
- return this.cache.add(
1845
- cacheName || url,
1846
- createPromise,
1847
- cacheOptions,
1848
- false
1849
- );
1850
- }
1851
- return createPromise();
1852
- });
1853
- }
1854
2542
  // -------------------------------------------------------------------------
1855
2543
  // Resource Methods
1856
2544
  // -------------------------------------------------------------------------
@@ -1926,78 +2614,7 @@ class NgwConnector {
1926
2614
  deleteResource(resource) {
1927
2615
  return this.resources.delete(resource);
1928
2616
  }
1929
- /**
1930
- * @internal
1931
- */
1932
- _loadData(url, options) {
1933
- options.responseType = options.responseType || "json";
1934
- return new Promise((resolve, reject) => {
1935
- var _a;
1936
- if (this.user) {
1937
- options = options || {};
1938
- options.headers = __spreadValues$3(__spreadValues$3({}, this.getAuthorizationHeaders()), options.headers);
1939
- }
1940
- if (this.requestTransform) {
1941
- const [transUrl, transOptions] = this.requestTransform(url, options);
1942
- url = transUrl;
1943
- options = transOptions;
1944
- }
1945
- let runOnAbort = void 0;
1946
- loadData(url, resolve, options, reject, (handler) => {
1947
- runOnAbort = handler;
1948
- });
1949
- (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
1950
- if (runOnAbort !== void 0) {
1951
- runOnAbort();
1952
- }
1953
- reject(new AbortError());
1954
- });
1955
- }).catch((httpError) => {
1956
- if (httpError.name !== "AbortError") {
1957
- {
1958
- console.warn("DEV WARN", httpError);
1959
- }
1960
- const er = this._handleHttpError(httpError);
1961
- if (er) {
1962
- throw er;
1963
- }
1964
- }
1965
- throw httpError;
1966
- });
1967
- }
1968
- _login(credentials, options) {
1969
- return __async$2(this, null, function* () {
1970
- try {
1971
- const data = yield this.getUserInfo(credentials, options);
1972
- this.user = data;
1973
- this.emitter.emit("login", data);
1974
- return data;
1975
- } catch (er) {
1976
- this.emitter.emit("login:error", er);
1977
- throw er;
1978
- }
1979
- });
1980
- }
1981
- _cleanActiveRequest(requestId) {
1982
- delete this.activeRequests[requestId];
1983
- }
1984
- _handleHttpError(er) {
1985
- if (er) {
1986
- if (er instanceof NgwError) {
1987
- if (er.exception === "nextgisweb.resource.exception.ResourceNotFound") {
1988
- throw new ResourceNotFoundError(er);
1989
- } else if (er.exception === "nextgisweb.core.exception.InsufficientPermissions") {
1990
- throw new InsufficientPermissionsError(er);
1991
- }
1992
- }
1993
- }
1994
- return er;
1995
- }
1996
2617
  }
1997
- __publicField$2(NgwConnector, "errors", {
1998
- NgwError,
1999
- ResourceNotFoundError
2000
- });
2001
2618
 
2002
2619
  function reEscape(s) {
2003
2620
  return s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
@@ -2069,6 +2686,10 @@ function propertiesFilter(properties, filters) {
2069
2686
  return logic === "any" ? filters_.some(filterFunction) : filters_.every(filterFunction);
2070
2687
  }
2071
2688
 
2689
+ const config = {
2690
+ defaultRequestLimit: 7e3
2691
+ };
2692
+
2072
2693
  var __defProp$3 = Object.defineProperty;
2073
2694
  var __defProps$1 = Object.defineProperties;
2074
2695
  var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
@@ -2114,15 +2735,12 @@ const FEATURE_REQUEST_PARAMS = {
2114
2735
  };
2115
2736
  function updateItemRequestParam(params, options) {
2116
2737
  const { extensions, geom, fields, srs, ilike, like } = options;
2117
- const extensionsStr = extensions ? extensions.join(",") : "";
2118
- if (extensionsStr !== "*") {
2119
- params.extensions = extensionsStr;
2120
- }
2121
- if (fields !== void 0) {
2122
- params.fields = Array.isArray(fields) ? fields.join(",") : "";
2738
+ params.extensions = extensions ? extensions : [];
2739
+ if (fields) {
2740
+ params.fields = fields;
2123
2741
  }
2124
2742
  if (geom !== void 0) {
2125
- params.geom = geom ? "yes" : "no";
2743
+ params.geom = geom;
2126
2744
  if (!geom) {
2127
2745
  delete params.srs;
2128
2746
  delete params.geom_format;
@@ -2137,6 +2755,15 @@ function updateItemRequestParam(params, options) {
2137
2755
  params.srs = srs;
2138
2756
  }
2139
2757
  }
2758
+ function paramListToQuery(paramList) {
2759
+ return paramList.reduce(
2760
+ (acc, [key, value]) => {
2761
+ acc[key] = value;
2762
+ return acc;
2763
+ },
2764
+ {}
2765
+ );
2766
+ }
2140
2767
  function createFeatureFieldFilterQueries(opt) {
2141
2768
  return __async$1(this, null, function* () {
2142
2769
  const queries = getQueries(opt);
@@ -2237,6 +2864,7 @@ function fetchNgwLayerItemsRequest(options) {
2237
2864
  const params = __spreadValues$2({}, FEATURE_REQUEST_PARAMS);
2238
2865
  const {
2239
2866
  limit,
2867
+ query,
2240
2868
  cache,
2241
2869
  signal,
2242
2870
  offset,
@@ -2247,12 +2875,10 @@ function fetchNgwLayerItemsRequest(options) {
2247
2875
  intersects,
2248
2876
  resourceId
2249
2877
  } = options;
2250
- if (limit) {
2251
- if (limit !== Number.POSITIVE_INFINITY) {
2252
- params.limit = limit;
2253
- }
2878
+ if (limit && limit !== Number.POSITIVE_INFINITY) {
2879
+ params.limit = limit;
2254
2880
  } else {
2255
- params.limit = 7e3;
2881
+ params.limit = config.defaultRequestLimit;
2256
2882
  }
2257
2883
  if (offset) {
2258
2884
  params.offset = offset;
@@ -2271,16 +2897,9 @@ function fetchNgwLayerItemsRequest(options) {
2271
2897
  params.intersects = intersects;
2272
2898
  }
2273
2899
  if (paramList) {
2274
- params.paramList = paramList;
2275
- }
2276
- const reqParams = __spreadValues$2({
2277
- id: resourceId
2278
- }, params);
2279
- return connector.get(
2280
- "feature_layer.feature.collection",
2281
- { cache, signal },
2282
- reqParams
2283
- );
2900
+ Object.assign(params, paramListToQuery(paramList));
2901
+ }
2902
+ return connector.route("feature_layer.feature.collection", { id: Number(resourceId) }).get({ query: __spreadValues$2(__spreadValues$2({}, params), query), cache, signal });
2284
2903
  }
2285
2904
 
2286
2905
  function prepareNgwFieldsToPropertiesFilter(fields) {
@@ -2433,7 +3052,7 @@ const _NgwProvider = class _NgwProvider extends BaseProvider {
2433
3052
  "The `searchUrl` of `connectorOptions.baseUrl` are required"
2434
3053
  );
2435
3054
  }
2436
- this.connector = options.connector || new NgwConnector(__spreadValues({
3055
+ this.connector = options.connector || new NgwConnectorExtended(__spreadValues({
2437
3056
  baseUrl: this.searchUrl
2438
3057
  }, options.connectorOptions));
2439
3058
  this.searchResources = options.searchResources;
@@ -2482,7 +3101,7 @@ const _NgwProvider = class _NgwProvider extends BaseProvider {
2482
3101
  yield item;
2483
3102
  }
2484
3103
  } catch (er) {
2485
- if (er && "name" in er && er.name !== "CancelError") {
3104
+ if (er && "name" in er && er.name !== "AbortError") {
2486
3105
  console.warn(er);
2487
3106
  }
2488
3107
  }
@@ -2491,14 +3110,10 @@ const _NgwProvider = class _NgwProvider extends BaseProvider {
2491
3110
  }
2492
3111
  result(item) {
2493
3112
  const signal = this._makeSignal();
2494
- const req = this.connector.get(
2495
- "feature_layer.feature.item_extent",
2496
- { signal },
2497
- {
2498
- id: item.resourceId,
2499
- fid: item.featureId
2500
- }
2501
- ).then((x) => {
3113
+ const req = this.connector.route("feature_layer.feature.item_extent", {
3114
+ id: item.resourceId,
3115
+ fid: item.featureId
3116
+ }).get({ signal }).then((x) => {
2502
3117
  const e = x.extent;
2503
3118
  return {
2504
3119
  text: item.text,
@@ -2585,56 +3200,69 @@ var __asyncGenerator = (__this, __arguments, generator) => {
2585
3200
  };
2586
3201
  class NominatimProvider extends BaseProvider {
2587
3202
  constructor(options) {
2588
- super(options);
3203
+ super();
3204
+ this.options = options;
2589
3205
  __publicField(this, "searchUrl", "https://nominatim.openstreetmap.org");
2590
- __publicField(this, "_abort", []);
3206
+ __publicField(this, "_abortControllers", []);
2591
3207
  if (options && options.searchUrl) {
2592
3208
  this.searchUrl = options.searchUrl;
2593
3209
  }
2594
3210
  }
2595
3211
  abort() {
2596
- this._abort.forEach((x) => x());
2597
- this._abort = [];
3212
+ this._abortControllers.forEach((controller) => {
3213
+ controller.abort();
3214
+ });
3215
+ this._abortControllers = [];
2598
3216
  }
2599
3217
  search(val) {
2600
3218
  return __asyncGenerator(this, null, function* () {
2601
- const url = fixUrlStr(
2602
- // `${this.baseUrl}/search?format=geojson&polygon_geojson=1${window.locale === 'ru' ? '&accept-language=ru-RU,en-US' : ''}&q=${val}`
2603
- `${this.searchUrl}/search?format=geojson&polygon_geojson=1&q=${val}`
2604
- );
2605
- const request = new Promise((resolve, reject) => {
2606
- const xhr = new XMLHttpRequest();
2607
- xhr.open("GET", url, true);
2608
- xhr.onload = () => {
2609
- try {
2610
- const geojson = JSON.parse(xhr.responseText);
2611
- const features = geojson.features.map((x) => {
2612
- return {
2613
- geom: x,
2614
- extent: x.bbox,
2615
- text: x.properties && x.properties.display_name,
2616
- query: val
2617
- };
2618
- });
2619
- resolve(features);
2620
- } catch (er) {
2621
- reject(er);
2622
- }
2623
- };
2624
- xhr.onerror = (er) => {
2625
- reject(er);
2626
- };
2627
- this._abort.push(xhr.abort);
2628
- xhr.send();
2629
- }).catch((er) => {
2630
- if (er.name === "CancelError") ;
2631
- throw er;
3219
+ var _a, _b, _c, _d, _e, _f, _g;
3220
+ const params = new URLSearchParams({
3221
+ format: "geojson",
3222
+ polygon_geojson: "1",
3223
+ q: val,
3224
+ limit: ((_b = (_a = this.options) == null ? void 0 : _a.limit) == null ? void 0 : _b.toString()) || "10"
2632
3225
  });
2633
- const items = yield new __await(request);
2634
- if (items) {
2635
- for (const i of items) {
2636
- i.result = () => this.result(i);
2637
- yield i;
3226
+ if ((_c = this.options) == null ? void 0 : _c.countrycodes) {
3227
+ params.append("countrycodes", this.options.countrycodes);
3228
+ }
3229
+ if ((_d = this.options) == null ? void 0 : _d.addressdetails) {
3230
+ params.append("addressdetails", "1");
3231
+ }
3232
+ if ((_e = this.options) == null ? void 0 : _e.language) {
3233
+ params.append("accept-language", this.options.language);
3234
+ }
3235
+ if ((_f = this.options) == null ? void 0 : _f.bounded) {
3236
+ params.append("bounded", "1");
3237
+ }
3238
+ if ((_g = this.options) == null ? void 0 : _g.viewbox) {
3239
+ const [minLon, minLat, maxLon, maxLat] = this.options.viewbox;
3240
+ params.append("viewbox", `${minLon},${minLat},${maxLon},${maxLat}`);
3241
+ }
3242
+ const url = fixUrlStr(`${this.searchUrl}/search?${params.toString()}`);
3243
+ const controller = new AbortController();
3244
+ this._abortControllers.push(controller);
3245
+ try {
3246
+ const response = yield new __await(fetch(url, { signal: controller.signal }));
3247
+ if (!response.ok) {
3248
+ throw new Error(`Network response was not ok: ${response.statusText}`);
3249
+ }
3250
+ const geojson = yield new __await(response.json());
3251
+ const features = geojson.features.map((x) => {
3252
+ return {
3253
+ geom: x,
3254
+ extent: x.bbox,
3255
+ text: x.properties && x.properties.display_name,
3256
+ query: val
3257
+ };
3258
+ });
3259
+ for (const item of features) {
3260
+ item.result = () => this.result(item);
3261
+ yield item;
3262
+ }
3263
+ } catch (error) {
3264
+ if (error.name === "AbortError") ; else {
3265
+ throw error;
2638
3266
  }
2639
3267
  }
2640
3268
  });
@@ -2648,41 +3276,41 @@ class NominatimProvider extends BaseProvider {
2648
3276
  }
2649
3277
  reverse(coordinates) {
2650
3278
  return __asyncGenerator(this, null, function* () {
3279
+ var _a, _b;
2651
3280
  const [lng, lat] = coordinates;
2652
- const url = fixUrlStr(
2653
- `${this.searchUrl}/reverse?format=geojson&lat=${lat}&lon=${lng}`
2654
- );
2655
- const request = new Promise((resolve, reject) => {
2656
- const xhr = new XMLHttpRequest();
2657
- xhr.open("GET", url, true);
2658
- xhr.onload = () => {
2659
- try {
2660
- const geojson = JSON.parse(xhr.responseText);
2661
- const feature = geojson.features[0];
2662
- const result = {
2663
- geom: feature,
2664
- extent: feature.bbox,
2665
- text: feature.properties && feature.properties.display_name,
2666
- query: `${lat}, ${lng}`
2667
- };
2668
- resolve(result);
2669
- } catch (er) {
2670
- reject(er);
2671
- }
2672
- };
2673
- xhr.onerror = (er) => {
2674
- reject(er);
2675
- };
2676
- this._abort.push(xhr.abort);
2677
- xhr.send();
2678
- }).catch((er) => {
2679
- if (er.name === "CancelError") ;
2680
- throw er;
3281
+ const params = new URLSearchParams({
3282
+ format: "geojson",
3283
+ lat: lat.toString(),
3284
+ lon: lng.toString()
2681
3285
  });
2682
- const item = yield new __await(request);
2683
- if (item) {
3286
+ if ((_a = this.options) == null ? void 0 : _a.addressdetails) {
3287
+ params.append("addressdetails", "1");
3288
+ }
3289
+ if ((_b = this.options) == null ? void 0 : _b.language) {
3290
+ params.append("accept-language", this.options.language);
3291
+ }
3292
+ const url = fixUrlStr(`${this.searchUrl}/reverse?${params.toString()}`);
3293
+ const controller = new AbortController();
3294
+ this._abortControllers.push(controller);
3295
+ try {
3296
+ const response = yield new __await(fetch(url, { signal: controller.signal }));
3297
+ if (!response.ok) {
3298
+ throw new Error(`Network response was not ok: ${response.statusText}`);
3299
+ }
3300
+ const geojson = yield new __await(response.json());
3301
+ const feature = geojson.features[0];
3302
+ const item = {
3303
+ geom: feature,
3304
+ extent: feature.bbox,
3305
+ text: feature.properties && feature.properties.display_name,
3306
+ query: `${lat}, ${lng}`
3307
+ };
2684
3308
  item.result = () => this.result(item);
2685
3309
  yield item;
3310
+ } catch (error) {
3311
+ if (error.name === "AbortError") ; else {
3312
+ throw error;
3313
+ }
2686
3314
  }
2687
3315
  });
2688
3316
  }