@nextgis/geocoder 3.0.0-alpha.1 → 3.0.0-alpha.13

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.1; author: NextGIS */
1
+ /** Bundle of @nextgis/geocoder; version: 3.0.0-alpha.13; author: NextGIS */
2
2
  var Geocoder = (function (exports) {
3
3
  'use strict';
4
4
 
@@ -9,14 +9,6 @@ var Geocoder = (function (exports) {
9
9
  return typeof val === "string" ? !!val : defined(val);
10
10
  }
11
11
 
12
- function getBoundsCoordinates(b) {
13
- const westNorth = [b[0], b[1]];
14
- const eastNorth = [b[2], b[1]];
15
- const eastSouth = [b[2], b[3]];
16
- const westSouth = [b[0], b[3]];
17
- return [westNorth, eastNorth, eastSouth, westSouth, westNorth];
18
- }
19
-
20
12
  function degrees2meters(lng, lat) {
21
13
  lat = lat > 85.06 ? 85.06 : lat < -85.06 ? -85.06 : lat;
22
14
  const x = lng * 2003750834e-2 / 180;
@@ -25,10 +17,23 @@ var Geocoder = (function (exports) {
25
17
  return [x, y];
26
18
  }
27
19
 
20
+ function getBoundsCoordinates(b) {
21
+ const westNorth = [b[0], b[1]];
22
+ const eastNorth = [b[2], b[1]];
23
+ const eastSouth = [b[2], b[3]];
24
+ const westSouth = [b[0], b[3]];
25
+ return [westNorth, eastNorth, eastSouth, westSouth, westNorth];
26
+ }
27
+
28
28
  function isLngLatBoundsArray(array) {
29
29
  return Array.isArray(array) && array.length === 4 && array.every((x) => typeof x === "number");
30
30
  }
31
31
 
32
+ function round(val, toFixed) {
33
+ const n = 1;
34
+ return Math.round((val + Number.EPSILON) * n) / n;
35
+ }
36
+
32
37
  function objectAssign(target, ...sources) {
33
38
  for (const source of sources) {
34
39
  for (const prop of Object.getOwnPropertyNames(source)) {
@@ -83,11 +88,6 @@ var Geocoder = (function (exports) {
83
88
  return newObj;
84
89
  }
85
90
 
86
- function round(val, toFixed) {
87
- const n = 1;
88
- return Math.round((val + Number.EPSILON) * n) / n;
89
- }
90
-
91
91
  function isObject$1(val) {
92
92
  return Object.prototype.toString.call(val) === "[object Object]";
93
93
  }
@@ -107,28 +107,28 @@ var Geocoder = (function (exports) {
107
107
  }
108
108
  }
109
109
 
110
- var __defProp$d = Object.defineProperty;
111
- var __defProps$3 = Object.defineProperties;
112
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
113
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
114
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
115
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
110
+ var __defProp$i = Object.defineProperty;
111
+ var __defProps$5 = Object.defineProperties;
112
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
113
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
114
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
115
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
116
116
  var __knownSymbol$2 = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
117
- var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
118
- var __spreadValues$6 = (a, b) => {
117
+ var __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
118
+ var __spreadValues$8 = (a, b) => {
119
119
  for (var prop in b || (b = {}))
120
- if (__hasOwnProp$6.call(b, prop))
121
- __defNormalProp$d(a, prop, b[prop]);
122
- if (__getOwnPropSymbols$6)
123
- for (var prop of __getOwnPropSymbols$6(b)) {
124
- if (__propIsEnum$6.call(b, prop))
125
- __defNormalProp$d(a, prop, b[prop]);
120
+ if (__hasOwnProp$8.call(b, prop))
121
+ __defNormalProp$i(a, prop, b[prop]);
122
+ if (__getOwnPropSymbols$8)
123
+ for (var prop of __getOwnPropSymbols$8(b)) {
124
+ if (__propIsEnum$8.call(b, prop))
125
+ __defNormalProp$i(a, prop, b[prop]);
126
126
  }
127
127
  return a;
128
128
  };
129
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
130
- var __publicField$a = (obj, key, value) => __defNormalProp$d(obj, key + "" , value);
131
- var __async$5 = (__this, __arguments, generator) => {
129
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
130
+ var __publicField$d = (obj, key, value) => __defNormalProp$i(obj, key + "" , value);
131
+ var __async$7 = (__this, __arguments, generator) => {
132
132
  return new Promise((resolve, reject) => {
133
133
  var fulfilled = (value) => {
134
134
  try {
@@ -168,7 +168,7 @@ var Geocoder = (function (exports) {
168
168
  class Geocoder extends BaseGeocoder {
169
169
  constructor(options) {
170
170
  super(options);
171
- __publicField$a(this, "providers", []);
171
+ __publicField$d(this, "providers", []);
172
172
  if (options && options.providers) {
173
173
  this.providers = options.providers;
174
174
  }
@@ -192,7 +192,7 @@ var Geocoder = (function (exports) {
192
192
  for (var iter = __forAwait(results), more, temp, error; more = !(temp = yield new __await$2(iter.next())).done; more = false) {
193
193
  const r = temp.value;
194
194
  allProvidersFailed = false;
195
- yield __spreadProps$3(__spreadValues$6({}, r), { provider, _id: ID$1++ });
195
+ yield __spreadProps$5(__spreadValues$8({}, r), { provider, _id: ID$1++ });
196
196
  }
197
197
  } catch (temp) {
198
198
  error = [temp];
@@ -206,7 +206,7 @@ var Geocoder = (function (exports) {
206
206
  }
207
207
  } catch (err) {
208
208
  const er = err;
209
- if (er.name !== "CancelError") {
209
+ if (er.name !== "AbortError") {
210
210
  errors.push(er);
211
211
  }
212
212
  }
@@ -235,7 +235,7 @@ var Geocoder = (function (exports) {
235
235
  try {
236
236
  for (var iter = __forAwait(results), more, temp, error; more = !(temp = yield new __await$2(iter.next())).done; more = false) {
237
237
  const r = temp.value;
238
- yield __spreadProps$3(__spreadValues$6({}, r), { provider, _id: ID$1++ });
238
+ yield __spreadProps$5(__spreadValues$8({}, r), { provider, _id: ID$1++ });
239
239
  }
240
240
  } catch (temp) {
241
241
  error = [temp];
@@ -247,7 +247,7 @@ var Geocoder = (function (exports) {
247
247
  throw error[0];
248
248
  }
249
249
  }
250
- } catch (er) {
250
+ } catch (e) {
251
251
  }
252
252
  }
253
253
  });
@@ -259,7 +259,7 @@ var Geocoder = (function (exports) {
259
259
  * @returns A promise that resolves to the first reverse geocoding result, or undefined if no results are found.
260
260
  */
261
261
  reverseGeocodeFirstResult(coordinates) {
262
- return __async$5(this, null, function* () {
262
+ return __async$7(this, null, function* () {
263
263
  for (const provider of this.providers) {
264
264
  if (typeof provider.reverse === "function") {
265
265
  try {
@@ -288,9 +288,9 @@ var Geocoder = (function (exports) {
288
288
  }
289
289
  }
290
290
 
291
- var __defProp$c = Object.defineProperty;
292
- var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
293
- var __publicField$9 = (obj, key, value) => __defNormalProp$c(obj, typeof key !== "symbol" ? key + "" : key, value);
291
+ var __defProp$h = Object.defineProperty;
292
+ var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
293
+ var __publicField$c = (obj, key, value) => __defNormalProp$h(obj, typeof key !== "symbol" ? key + "" : key, value);
294
294
  class BaseProvider extends BaseGeocoder {
295
295
  constructor() {
296
296
  super(...arguments);
@@ -298,15 +298,254 @@ var Geocoder = (function (exports) {
298
298
  * URL endpoint for the search service.
299
299
  * This is where queries will be sent to obtain search results.
300
300
  */
301
- __publicField$9(this, "searchUrl");
301
+ __publicField$c(this, "searchUrl");
302
302
  /**
303
303
  * Label to represent the provider.
304
304
  * Useful for user interfaces to display the source of search results.
305
305
  */
306
- __publicField$9(this, "label");
306
+ __publicField$c(this, "label");
307
307
  }
308
308
  }
309
309
 
310
+ const templateRe = /\{ *([\w_-]+) *\}/g;
311
+ function template(str, data) {
312
+ return str.replace(templateRe, (s, key) => {
313
+ let value = data[key];
314
+ if (value === void 0) {
315
+ throw new Error("No value provided for letiable " + s);
316
+ } else if (typeof value === "function") {
317
+ value = value(data);
318
+ }
319
+ return value;
320
+ });
321
+ }
322
+
323
+ var __defProp$g = Object.defineProperty;
324
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
325
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
326
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
327
+ var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
328
+ var __spreadValues$7 = (a, b) => {
329
+ for (var prop in b || (b = {}))
330
+ if (__hasOwnProp$7.call(b, prop))
331
+ __defNormalProp$g(a, prop, b[prop]);
332
+ if (__getOwnPropSymbols$7)
333
+ for (var prop of __getOwnPropSymbols$7(b)) {
334
+ if (__propIsEnum$7.call(b, prop))
335
+ __defNormalProp$g(a, prop, b[prop]);
336
+ }
337
+ return a;
338
+ };
339
+ var __async$6 = (__this, __arguments, generator) => {
340
+ return new Promise((resolve, reject) => {
341
+ var fulfilled = (value) => {
342
+ try {
343
+ step(generator.next(value));
344
+ } catch (e) {
345
+ reject(e);
346
+ }
347
+ };
348
+ var rejected = (value) => {
349
+ try {
350
+ step(generator.throw(value));
351
+ } catch (e) {
352
+ reject(e);
353
+ }
354
+ };
355
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
356
+ step((generator = generator.apply(__this, __arguments)).next());
357
+ });
358
+ };
359
+ function apiRequest(opt) {
360
+ return __async$6(this, null, function* () {
361
+ const { params, name, connector, requestOptions } = opt;
362
+ const apiItems = yield connector.connect();
363
+ let apiItem = apiItems && apiItems[name];
364
+ if (apiItem) {
365
+ apiItem = [...apiItem];
366
+ let url = apiItem.shift();
367
+ if (apiItem.length) {
368
+ const replaceParams = {};
369
+ for (let fry = 0; fry < apiItem.length; fry++) {
370
+ const arg = apiItem[fry];
371
+ replaceParams[fry] = `{${arg}}`;
372
+ if (params[arg] === void 0) {
373
+ throw new Error(`\`${arg}\` URL API argument is not specified`);
374
+ }
375
+ }
376
+ if (url) {
377
+ url = template(url, replaceParams);
378
+ }
379
+ }
380
+ if (params) {
381
+ const paramArray = [];
382
+ const paramList = params.paramList;
383
+ if (Array.isArray(paramList)) {
384
+ paramList.forEach(([key, value]) => {
385
+ paramArray.push(`${key}=${value}`);
386
+ });
387
+ }
388
+ for (const p in params) {
389
+ if (apiItem.indexOf(p) === -1) {
390
+ paramArray.push(`${p}=${params[p]}`);
391
+ }
392
+ }
393
+ if (paramArray.length) {
394
+ url = `${url}?${paramArray.join("&")}`;
395
+ }
396
+ }
397
+ if (url) {
398
+ return connector.makeQuery(url, params, __spreadValues$7({
399
+ cacheName: name
400
+ }, requestOptions));
401
+ } else {
402
+ throw new Error("Request URL is not set");
403
+ }
404
+ } else {
405
+ return void 0;
406
+ }
407
+ });
408
+ }
409
+
410
+ var __defProp$f = Object.defineProperty;
411
+ var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
412
+ var __publicField$b = (obj, key, value) => __defNormalProp$f(obj, typeof key !== "symbol" ? key + "" : key, value);
413
+ const _Cache = class _Cache {
414
+ constructor(options = {}) {
415
+ __publicField$b(this, "cache", []);
416
+ var _a;
417
+ const namespace = (_a = options.namespace) != null ? _a : "default";
418
+ if (_Cache.instance[namespace]) {
419
+ return _Cache.instance[namespace];
420
+ }
421
+ _Cache.instance[namespace] = this;
422
+ return this;
423
+ }
424
+ clean() {
425
+ this.cache.length = 0;
426
+ }
427
+ all() {
428
+ return this.cache;
429
+ }
430
+ /**
431
+ * Caching only a non-empty value.
432
+ *
433
+ * Useful for get or create strategy
434
+ * @example
435
+ * ```javascript
436
+ * const cache = new Cache();
437
+ * const getItemFunc = () => fetch(url).then((data) => {
438
+ * return data.json(); // undefined
439
+ * });
440
+ * const item = await cache.addFull('foo', getItemFunc);
441
+ * if (!item) {
442
+ * await createItem(); // 'New item'
443
+ * }
444
+ *
445
+ * // somewhere else in the code
446
+ * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
447
+ * console.log(resp); // 'New item'
448
+ * });
449
+ * ```
450
+ */
451
+ addFull(key, valueToSet, propsOrOptions, expirationTime) {
452
+ if (typeof propsOrOptions === "object" && "valueToSet" in propsOrOptions) {
453
+ propsOrOptions.onlyFull = true;
454
+ }
455
+ return this.add(key, valueToSet, propsOrOptions, true, expirationTime);
456
+ }
457
+ add(key, valueToSet, propsOrOptions, onlyFull, expirationTime) {
458
+ let opt;
459
+ let props;
460
+ if (typeof propsOrOptions === "object" && "valueToSet" in propsOrOptions) {
461
+ opt = propsOrOptions;
462
+ onlyFull = opt.onlyFull;
463
+ expirationTime = opt.expirationTime;
464
+ props = opt.props;
465
+ } else {
466
+ props = propsOrOptions;
467
+ }
468
+ const exist = this._find(key, props);
469
+ if (!exist) {
470
+ let value;
471
+ if (valueToSet instanceof Function) {
472
+ value = valueToSet();
473
+ } else {
474
+ value = valueToSet;
475
+ }
476
+ const nonEmptyProps = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
477
+ expirationTime = expirationTime ? Date.now() + expirationTime : void 0;
478
+ const cacheItem = {
479
+ key,
480
+ value,
481
+ props: nonEmptyProps,
482
+ expirationTime
483
+ };
484
+ if (onlyFull && !full(value)) {
485
+ return value;
486
+ }
487
+ this.cache.push(cacheItem);
488
+ if (value instanceof Promise) {
489
+ value.catch(() => {
490
+ this.delete(key, props);
491
+ });
492
+ if (onlyFull) {
493
+ value.then((x) => {
494
+ if (!full(x)) {
495
+ this.delete(key, props);
496
+ }
497
+ return x;
498
+ });
499
+ }
500
+ return value;
501
+ }
502
+ return value;
503
+ } else {
504
+ return exist.value;
505
+ }
506
+ }
507
+ match(key, props) {
508
+ const cacheRecord = this._find(key, props);
509
+ if (cacheRecord && cacheRecord.expirationTime && Date.now() > cacheRecord.expirationTime) {
510
+ this.delete(cacheRecord);
511
+ return void 0;
512
+ }
513
+ return cacheRecord == null ? void 0 : cacheRecord.value;
514
+ }
515
+ matchAll(key, props) {
516
+ const now = Date.now();
517
+ this.cache.forEach((item) => {
518
+ if (item.expirationTime && now > item.expirationTime) {
519
+ this.delete(item);
520
+ }
521
+ });
522
+ if (key) {
523
+ return this.cache.filter((x) => this._filter(x, key, props)).map((x) => x.value);
524
+ }
525
+ return this.cache.map((x) => x.value);
526
+ }
527
+ delete(keyOrItem, props) {
528
+ const itemsToDelete = typeof keyOrItem === "string" ? this.cache.filter((x) => this._filter(x, keyOrItem, props)) : [keyOrItem];
529
+ for (const item of itemsToDelete) {
530
+ const index = this.cache.indexOf(item);
531
+ if (index !== -1) {
532
+ this.cache.splice(index, 1);
533
+ }
534
+ }
535
+ }
536
+ _find(key, props) {
537
+ return this.cache.find((x) => this._filter(x, key, props));
538
+ }
539
+ _filter(item, key, props) {
540
+ if (item.key !== key) return false;
541
+ if (!props) return true;
542
+ const itemProps = item.props;
543
+ return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
544
+ }
545
+ };
546
+ __publicField$b(_Cache, "instance", {});
547
+ let Cache = _Cache;
548
+
310
549
  var domain;
311
550
 
312
551
  // This constructor is used to store event handlers. Instantiating this is
@@ -337,7 +576,7 @@ var Geocoder = (function (exports) {
337
576
  this.domain = null;
338
577
  if (EventEmitter.usingDomains) {
339
578
  // if there is an active domain, then attach to it.
340
- if (domain.active ) ;
579
+ if (domain.active) ;
341
580
  }
342
581
 
343
582
  if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
@@ -779,142 +1018,164 @@ var Geocoder = (function (exports) {
779
1018
  return ret;
780
1019
  }
781
1020
 
782
- var __defProp$b = Object.defineProperty;
783
- var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
784
- var __publicField$8 = (obj, key, value) => __defNormalProp$b(obj, typeof key !== "symbol" ? key + "" : key, value);
785
- const _Cache = class _Cache {
786
- constructor(options = {}) {
787
- __publicField$8(this, "cache", []);
788
- var _a;
789
- const namespace = (_a = options.namespace) != null ? _a : "default";
790
- if (_Cache.instance[namespace]) {
791
- return _Cache.instance[namespace];
792
- }
793
- _Cache.instance[namespace] = this;
794
- return this;
1021
+ var pkg = {
1022
+ name: "@nextgis/ngw-connector",
1023
+ version: "3.0.0-alpha.13",
1024
+ _priority: 12,
1025
+ description: "A lightweight HTTP client optimized for use with NextGIS Web API",
1026
+ main: "index.js",
1027
+ module: "lib/ngw-connector.esm-bundler.js",
1028
+ unpkg: "lib/ngw-connector.global.prod.js",
1029
+ jsdelivr: "lib/ngw-connector.global.prod.js",
1030
+ types: "lib/index.d.ts",
1031
+ dependencies: {
1032
+ "@nextgis/cache": "^3.0.0-alpha.13",
1033
+ "@nextgis/cancelable-promise": "^3.0.0-alpha.13",
1034
+ "@nextgis/utils": "^3.0.0-alpha.13",
1035
+ "@types/events": "^3.0.0",
1036
+ events: "*",
1037
+ "form-data": "^4.0.0"
1038
+ },
1039
+ devDependencies: {
1040
+ "@nextgis/build-tools": "^3.0.0-alpha.13"
1041
+ },
1042
+ scripts: {
1043
+ clean: "rimraf ./lib",
1044
+ dev: "node ../build-tools/lib/build.js",
1045
+ prod: "npm run dev -- --release",
1046
+ lint: "eslint ./src/**/*.ts --fix --c ../../.eslintrc",
1047
+ watch: "npm run dev -- --watch",
1048
+ "gen:types": "node ./scripts/generator"
1049
+ },
1050
+ buildOptions: {
1051
+ name: "NgwConnector",
1052
+ formats: [
1053
+ "esm-bundler",
1054
+ "esm-browser",
1055
+ "cjs",
1056
+ "global"
1057
+ ]
1058
+ },
1059
+ keywords: [
1060
+ "NextGIS",
1061
+ "MAP"
1062
+ ],
1063
+ author: "NextGIS",
1064
+ files: [
1065
+ "index.js",
1066
+ "lib"
1067
+ ],
1068
+ license: "MIT",
1069
+ homepage: "https://github.com/nextgis/nextgis_frontend/tree/master/packages/ngw-connector#readme",
1070
+ repository: {
1071
+ type: "git",
1072
+ url: "git://github.com/nextgis/nextgis_frontend.git"
1073
+ },
1074
+ engines: {
1075
+ node: ">=18.20.4"
1076
+ },
1077
+ gitHead: "edc68033f914f6c95c4125b9738bba6d36e990b4"
1078
+ };
1079
+
1080
+ class AbortError extends Error {
1081
+ constructor(message = "AbortError") {
1082
+ super(message);
1083
+ this.name = "AbortError";
795
1084
  }
796
- clean() {
797
- this.cache.length = 0;
1085
+ }
1086
+
1087
+ var __defProp$e = Object.defineProperty;
1088
+ var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1089
+ var __publicField$a = (obj, key, value) => __defNormalProp$e(obj, typeof key !== "symbol" ? key + "" : key, value);
1090
+ class NgwError extends Error {
1091
+ constructor(er) {
1092
+ super();
1093
+ __publicField$a(this, "name", "NgwError");
1094
+ __publicField$a(this, "title");
1095
+ __publicField$a(this, "message");
1096
+ __publicField$a(this, "detail");
1097
+ __publicField$a(this, "exception");
1098
+ __publicField$a(this, "status_code");
1099
+ __publicField$a(this, "data");
1100
+ __publicField$a(this, "guru_meditation");
1101
+ Object.assign(this, er);
1102
+ Object.setPrototypeOf(this, NgwError.prototype);
798
1103
  }
799
- all() {
800
- return this.cache;
1104
+ }
1105
+
1106
+ var __defProp$d = Object.defineProperty;
1107
+ var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1108
+ var __publicField$9 = (obj, key, value) => __defNormalProp$d(obj, typeof key !== "symbol" ? key + "" : key, value);
1109
+ class InsufficientPermissionsError extends NgwError {
1110
+ constructor(obj) {
1111
+ super(obj);
1112
+ __publicField$9(this, "name", "InsufficientPermissionsError");
1113
+ __publicField$9(this, "exception", "nextgisweb.core.exception.InsufficientPermissions");
1114
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
801
1115
  }
802
- /**
803
- * Caching only a non-empty value.
804
- *
805
- * Useful for get or create strategy
806
- * @example
807
- * ```javascript
808
- * const cache = new Cache();
809
- * const getItemFunc = () => fetch(url).then((data) => {
810
- * return data.json(); // undefined
811
- * });
812
- * const item = await cache.addFull('foo', getItemFunc);
813
- * if (!item) {
814
- * await createItem(); // 'New item'
815
- * }
816
- *
817
- * // somewhere else in the code
818
- * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
819
- * console.log(resp); // 'New item'
820
- * });
821
- * ```
822
- */
823
- addFull(key, valueToSet, props) {
824
- return this.add(key, valueToSet, props, true);
1116
+ }
1117
+
1118
+ var __defProp$c = Object.defineProperty;
1119
+ var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1120
+ var __publicField$8 = (obj, key, value) => __defNormalProp$c(obj, typeof key !== "symbol" ? key + "" : key, value);
1121
+ let NetworksResponseError$1 = class NetworksResponseError extends NgwError {
1122
+ constructor(obj) {
1123
+ super(obj);
1124
+ __publicField$8(this, "message", "There is no response from the server or problem connecting to server.");
1125
+ __publicField$8(this, "title", "Network error");
1126
+ __publicField$8(this, "detail", "Check network connectivity and try again later.");
1127
+ Object.setPrototypeOf(this, NetworksResponseError.prototype);
825
1128
  }
826
- add(key, valueToSet, props, onlyFull) {
827
- const exist = this._find(key, props);
828
- if (!exist) {
829
- let value;
830
- if (valueToSet instanceof Function) {
831
- value = valueToSet();
832
- } else {
833
- value = valueToSet;
834
- }
835
- const nonEmptyProps = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
836
- const cacheItem = {
837
- key,
838
- value,
839
- props: nonEmptyProps
1129
+ };
1130
+
1131
+ function extractError(error) {
1132
+ if (isObject$1(error)) {
1133
+ if (error.name && error.message && error.title) {
1134
+ return {
1135
+ title: error.title,
1136
+ message: error.message,
1137
+ detail: error.detail || null,
1138
+ data: error.data && error.data.data ? error.data.data : null
840
1139
  };
841
- if (onlyFull && !full(value)) {
842
- return value;
843
- }
844
- this.cache.push(cacheItem);
845
- if (value instanceof Promise) {
846
- value.catch((er) => {
847
- this.delete(key, props);
1140
+ } else if (error.exception) {
1141
+ if (error.status === void 0 || error.status === 0 || error.data === void 0) {
1142
+ return new NetworksResponseError$1({
1143
+ title: error.title,
1144
+ status_code: error.status_code,
1145
+ exception: error.exception
848
1146
  });
849
- if (onlyFull) {
850
- value.then((x) => {
851
- if (!full(x)) {
852
- this.delete(key, props);
853
- }
854
- return x;
855
- });
856
- }
857
- return value;
858
- }
859
- return value;
860
- } else {
861
- return exist.value;
862
- }
863
- }
864
- match(key, props) {
865
- const cacheRecord = this._find(key, props);
866
- return cacheRecord == null ? void 0 : cacheRecord.value;
867
- }
868
- matchAll(key, props) {
869
- if (key) {
870
- return this.cache.filter((x) => this._filter(x, key, props)).map((x) => x.value);
871
- }
872
- return this.cache.map((x) => x.value);
873
- }
874
- delete(keyOrItem, props) {
875
- const itemsToDelete = typeof keyOrItem === "string" ? this.cache.filter((x) => this._filter(x, keyOrItem, props)) : [keyOrItem];
876
- for (const item of itemsToDelete) {
877
- const index = this.cache.indexOf(item);
878
- if (index !== -1) {
879
- this.cache.splice(index, 1);
880
1147
  }
881
1148
  }
1149
+ return {
1150
+ title: typeof error.title === "string" ? error.title : "Unexpected error",
1151
+ message: typeof error.message === "string" ? error.message : "Something went wrong."
1152
+ };
882
1153
  }
883
- _find(key, props) {
884
- return this.cache.find((x) => this._filter(x, key, props));
885
- }
886
- _filter(item, key, props) {
887
- if (item.key !== key) return false;
888
- if (!props) return true;
889
- const itemProps = item.props;
890
- return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
1154
+ }
1155
+
1156
+ function isError(error) {
1157
+ if (isObject$1(error)) {
1158
+ return error.status_code && error.exception && error.title;
891
1159
  }
892
- };
893
- __publicField$8(_Cache, "instance", {});
894
- let Cache = _Cache;
1160
+ return false;
1161
+ }
895
1162
 
896
- var __defProp$a = Object.defineProperty;
897
- var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
898
- var __publicField$7 = (obj, key, value) => __defNormalProp$a(obj, typeof key !== "symbol" ? key + "" : key, value);
899
- class NgwError extends Error {
900
- constructor(er) {
1163
+ var __defProp$b = Object.defineProperty;
1164
+ var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1165
+ var __publicField$7 = (obj, key, value) => __defNormalProp$b(obj, key + "" , value);
1166
+ class NetworkError extends Error {
1167
+ constructor(url) {
901
1168
  super();
902
- __publicField$7(this, "name", "NgwError");
903
- __publicField$7(this, "title");
904
- __publicField$7(this, "message");
905
- __publicField$7(this, "detail");
906
- __publicField$7(this, "exception");
907
- __publicField$7(this, "status_code");
908
- __publicField$7(this, "data");
909
- __publicField$7(this, "guru_meditation");
910
- Object.assign(this, er);
911
- Object.setPrototypeOf(this, NgwError.prototype);
1169
+ __publicField$7(this, "name", "NetworkError");
1170
+ Object.setPrototypeOf(this, NetworkError.prototype);
1171
+ this.message = `Unable to request ${url}.
1172
+ Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`;
912
1173
  }
913
1174
  }
914
1175
 
915
- var __defProp$9 = Object.defineProperty;
916
- var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
917
- var __publicField$6 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
1176
+ var __defProp$a = Object.defineProperty;
1177
+ var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1178
+ var __publicField$6 = (obj, key, value) => __defNormalProp$a(obj, typeof key !== "symbol" ? key + "" : key, value);
918
1179
  class ResourceNotFoundError extends NgwError {
919
1180
  constructor(obj) {
920
1181
  super(obj);
@@ -924,53 +1185,111 @@ var Geocoder = (function (exports) {
924
1185
  }
925
1186
  }
926
1187
 
927
- function isObject(val) {
928
- return Object.prototype.toString.call(val) === "[object Object]";
929
- }
1188
+ var errors = /*#__PURE__*/Object.freeze({
1189
+ __proto__: null,
1190
+ AbortError: AbortError,
1191
+ InsufficientPermissionsError: InsufficientPermissionsError,
1192
+ NetworkError: NetworkError,
1193
+ NetworksResponseError: NetworksResponseError$1,
1194
+ NgwError: NgwError,
1195
+ ResourceNotFoundError: ResourceNotFoundError,
1196
+ extractError: extractError,
1197
+ isError: isError
1198
+ });
930
1199
 
931
- function resourceCompare(res1, res2) {
932
- return objectDeepEqual(res1, res2);
1200
+ var __defProp$9 = Object.defineProperty;
1201
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1202
+ var __publicField$5 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
1203
+ class BaseAPIError extends Error {
1204
+ constructor(message) {
1205
+ super(message || "Something went wrong.");
1206
+ __publicField$5(this, "title");
1207
+ this.name = "BaseAPIError";
1208
+ this.title = "Unknown API error";
1209
+ if (Error.captureStackTrace) {
1210
+ Error.captureStackTrace(this, BaseAPIError);
1211
+ }
1212
+ }
933
1213
  }
934
-
935
- const exclude = ["description"];
936
- function resourceToQuery(resource, prefix = "") {
937
- prefix = prefix ? prefix + "__" : "";
938
- const query = {};
939
- for (const [key, value] of Object.entries(resource)) {
940
- if (exclude.indexOf(key) === -1) {
941
- if (isObject(value)) {
942
- if (key === "owner_user") {
943
- const children = resourceToQuery(value, key);
944
- Object.assign(query, children);
945
- } else if (key === "parent" && "id" in value) {
946
- query.parent_id = value.id;
947
- }
948
- } else if (defined(value)) {
949
- query[prefix + key] = value;
950
- }
1214
+ class NetworksResponseError extends BaseAPIError {
1215
+ // prettier-ignore
1216
+ constructor(message) {
1217
+ super(message || "There is no response from the server or problem connecting to server.");
1218
+ __publicField$5(this, "detail");
1219
+ this.title = "Network error";
1220
+ this.detail = "Check network connectivity and try again later.";
1221
+ }
1222
+ }
1223
+ class InvalidResponseError extends BaseAPIError {
1224
+ constructor(message) {
1225
+ super(message || "Something went wrong.");
1226
+ this.title = "Unexpected server response";
1227
+ }
1228
+ }
1229
+ class ServerResponseError extends BaseAPIError {
1230
+ constructor(data) {
1231
+ super(data.message);
1232
+ __publicField$5(this, "detail");
1233
+ __publicField$5(this, "data");
1234
+ this.title = data.title || this.title;
1235
+ this.detail = data.detail || null;
1236
+ this.data = data;
1237
+ }
1238
+ }
1239
+ class LunkwillError extends Error {
1240
+ // prettier-ignore
1241
+ constructor(message, data = {}) {
1242
+ super(message || "Unexpected error while processing long-running request.");
1243
+ __publicField$5(this, "title");
1244
+ __publicField$5(this, "data");
1245
+ this.name = "LunkwillError";
1246
+ this.title = "Long-running request error";
1247
+ this.data = data;
1248
+ if (Error.captureStackTrace) {
1249
+ Error.captureStackTrace(this, LunkwillError);
951
1250
  }
952
1251
  }
953
- return query;
1252
+ }
1253
+ class LunkwillRequestCancelled extends LunkwillError {
1254
+ constructor(data) {
1255
+ super("Long-running request was cancelled.", data);
1256
+ }
1257
+ }
1258
+ class LunkwillRequestFailed extends LunkwillError {
1259
+ constructor(data) {
1260
+ super(void 0, data);
1261
+ }
954
1262
  }
955
1263
 
956
1264
  var __defProp$8 = Object.defineProperty;
957
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
958
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
959
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
1265
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
1266
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
1267
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
960
1268
  var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
961
- var __spreadValues$5 = (a, b) => {
1269
+ var __spreadValues$6 = (a, b) => {
962
1270
  for (var prop in b || (b = {}))
963
- if (__hasOwnProp$5.call(b, prop))
1271
+ if (__hasOwnProp$6.call(b, prop))
964
1272
  __defNormalProp$8(a, prop, b[prop]);
965
- if (__getOwnPropSymbols$5)
966
- for (var prop of __getOwnPropSymbols$5(b)) {
967
- if (__propIsEnum$5.call(b, prop))
1273
+ if (__getOwnPropSymbols$6)
1274
+ for (var prop of __getOwnPropSymbols$6(b)) {
1275
+ if (__propIsEnum$6.call(b, prop))
968
1276
  __defNormalProp$8(a, prop, b[prop]);
969
1277
  }
970
1278
  return a;
971
1279
  };
972
- var __publicField$5 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
973
- var __async$4 = (__this, __arguments, generator) => {
1280
+ var __objRest$2 = (source, exclude) => {
1281
+ var target = {};
1282
+ for (var prop in source)
1283
+ if (__hasOwnProp$6.call(source, prop) && exclude.indexOf(prop) < 0)
1284
+ target[prop] = source[prop];
1285
+ if (source != null && __getOwnPropSymbols$6)
1286
+ for (var prop of __getOwnPropSymbols$6(source)) {
1287
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$6.call(source, prop))
1288
+ target[prop] = source[prop];
1289
+ }
1290
+ return target;
1291
+ };
1292
+ var __async$5 = (__this, __arguments, generator) => {
974
1293
  return new Promise((resolve, reject) => {
975
1294
  var fulfilled = (value) => {
976
1295
  try {
@@ -990,307 +1309,241 @@ var Geocoder = (function (exports) {
990
1309
  step((generator = generator.apply(__this, __arguments)).next());
991
1310
  });
992
1311
  };
993
- class ResourcesControl {
994
- constructor({
995
- connector,
996
- cacheId
997
- }) {
998
- __publicField$5(this, "cache");
999
- __publicField$5(this, "connector");
1000
- this.connector = connector;
1001
- this.cache = new Cache({ namespace: cacheId });
1002
- }
1003
- // -------------------------------------------------------------------------
1004
- // Resource Methods
1005
- // -------------------------------------------------------------------------
1006
- /**
1007
- * Receive resource from NGW by id, keyname or search-object parameter.
1008
- * @param resource - Resource id, keyname or search-object
1009
- *
1010
- * @remarks
1011
- * Fetching resource would be cached to speed up next call
1012
- */
1013
- getOne(resource, requestOptions) {
1014
- const opt = __spreadValues$5({}, requestOptions);
1015
- if (typeof resource === "string") ; else if (typeof resource === "number") ; else if (isObject(resource)) {
1016
- if (resource.id !== void 0) {
1017
- resource.id;
1018
- } else {
1019
- if (resource.keyname) {
1020
- resource.keyname;
1021
- }
1022
- if (resource.display_name) {
1023
- resource.display_name;
1024
- }
1312
+ function lunkwillCheckResponse(lwResp) {
1313
+ const ct = lwResp.headers.get("content-type");
1314
+ return ct !== void 0 && ct !== null && ct.includes("application/vnd.lunkwill.request-summary+json");
1315
+ }
1316
+ function responseJson(response) {
1317
+ return __async$5(this, null, function* () {
1318
+ try {
1319
+ return response.json();
1320
+ } catch (e) {
1321
+ throw new Error();
1322
+ }
1323
+ });
1324
+ }
1325
+ function lunkwillResponseUrl(lwResp) {
1326
+ return __async$5(this, null, function* () {
1327
+ const lwData = yield responseJson(lwResp);
1328
+ let delay = lwData.delay_ms;
1329
+ const retry = lwData.retry_ms !== void 0 ? lwData.retry_ms : 2e3;
1330
+ const sum = `/api/lunkwill/${lwData.id}/summary`;
1331
+ const res = `/api/lunkwill/${lwData.id}/response`;
1332
+ const sleep = (msec) => new Promise((resolve) => setTimeout(resolve, msec));
1333
+ let failed = false;
1334
+ let ready = false;
1335
+ while (!ready) {
1336
+ yield sleep(failed ? retry : delay);
1337
+ failed = false;
1338
+ let lwResp2;
1339
+ let lwData2;
1340
+ try {
1341
+ lwResp2 = yield fetch(sum, { credentials: "same-origin" });
1342
+ lwData2 = yield lwResp2.json();
1343
+ } catch (e) {
1344
+ failed = true;
1345
+ continue;
1346
+ }
1347
+ switch (lwData2.status) {
1348
+ case void 0:
1349
+ throw new LunkwillError(void 0, lwData2);
1350
+ case "ready":
1351
+ ready = true;
1352
+ break;
1353
+ case "cancelled":
1354
+ throw new LunkwillRequestCancelled(lwData2);
1355
+ case "failed":
1356
+ throw new LunkwillRequestFailed(lwData2);
1357
+ case "spooled":
1358
+ case "processing":
1359
+ case "buffering":
1360
+ delay = lwData2.delay_ms;
1361
+ break;
1362
+ default:
1363
+ throw new LunkwillError(void 0, lwData2);
1025
1364
  }
1026
1365
  }
1027
- if (typeof resource === "string") {
1028
- return this._fetchResourceBy({ keyname: resource }, opt);
1029
- } else if (typeof resource === "number") {
1030
- return this._fetchResourceById(resource, opt);
1031
- } else if (isObject(resource)) {
1032
- return this._fetchResourceBy(resource, opt);
1366
+ return res;
1367
+ });
1368
+ }
1369
+ function lunkwillFetch(lwRespUrl) {
1370
+ return __async$5(this, null, function* () {
1371
+ try {
1372
+ return yield window.fetch(lwRespUrl, { credentials: "same-origin" });
1373
+ } catch (e) {
1374
+ throw new NetworksResponseError();
1033
1375
  }
1034
- return Promise.resolve(void 0);
1035
- }
1036
- getOneOrFail(resource, requestOptions) {
1037
- return this.getOne(resource, requestOptions).then((res) => {
1038
- if (res) {
1039
- return res;
1376
+ });
1377
+ }
1378
+ const mediaContentTypes = [
1379
+ "application/pdf",
1380
+ "image/png",
1381
+ "image/jpeg",
1382
+ "image/tiff",
1383
+ "text/csv"
1384
+ ];
1385
+ const mediaContentTypesRegex = new RegExp(mediaContentTypes.join("|"));
1386
+ function isMediaContentType(contentType) {
1387
+ return mediaContentTypesRegex.test(contentType);
1388
+ }
1389
+ function encodeQueryParams(value) {
1390
+ const result = [];
1391
+ for (const [k, v] of Object.entries(value)) {
1392
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
1393
+ result.push(`${k}=${encodeURIComponent(v)}`);
1394
+ } else if (Array.isArray(v)) {
1395
+ result.push(`${k}=${v.map(encodeURIComponent).join(",")}`);
1396
+ } else {
1397
+ for (const [sk, sv] of Object.entries(v)) {
1398
+ const ske = `${k}[${encodeURIComponent(sk)}]`;
1399
+ if (typeof sv === "string" || typeof sv === "number" || typeof sv === "boolean") {
1400
+ result.push(`${ske}=${encodeURIComponent(sv)}`);
1401
+ } else if (Array.isArray(sv)) {
1402
+ const sve = sv.map(encodeURIComponent);
1403
+ result.push(`${ske}=${sve.join(",")}`);
1404
+ }
1040
1405
  }
1041
- throw new ResourceNotFoundError();
1042
- });
1406
+ }
1043
1407
  }
1044
- /**
1045
- * A fast way to retrieve resource ID for any resource definition.
1046
- * @param resource - Any available resource definition
1047
- *
1048
- * @remarks
1049
- * There are situations when exactly the resource id is needed
1050
- * (for example, to compose the correct request to the api)
1051
- * then this method will come in handy to facilitate the extraction of the identifier
1052
- * if the resource is specified through a keyname or other parameters.
1053
- */
1054
- getId(resource, requestOptions) {
1055
- if (typeof resource === "number") {
1056
- return Promise.resolve(resource);
1057
- } else if (typeof resource === "string" || isObject(resource)) {
1058
- return this.getOne(resource, requestOptions).then((res) => {
1059
- if (res) {
1060
- return res.resource.id;
1061
- }
1062
- });
1063
- }
1064
- return Promise.resolve(void 0);
1065
- }
1066
- /**
1067
- * A fast way to retrieve resource ID for any resource definition.
1068
- * @param resource - Any available resource definition
1069
- *
1070
- * @remarks
1071
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1072
- * To not make one more checks if the resource is definitely exists
1073
- */
1074
- getIdOrFail(resource, requestOptions) {
1075
- return this.getId(resource, requestOptions).then((resp) => {
1076
- if (resp === void 0) {
1077
- throw new Error();
1078
- }
1079
- return resp;
1080
- });
1408
+ return result.join("&");
1409
+ }
1410
+ function generateUrl(path, query) {
1411
+ let urlParams = "";
1412
+ if (query !== void 0) {
1413
+ urlParams = "?" + encodeQueryParams(query);
1081
1414
  }
1082
- getMany(resource, requestOptions) {
1083
- return this._resourceCacheFilter(resource).then((items) => {
1084
- if (!items.length) {
1085
- const query = {};
1086
- if (resource.keyname) {
1087
- query.keyname = resource.keyname;
1088
- } else {
1089
- Object.assign(query, resourceToQuery(resource));
1415
+ return path + urlParams;
1416
+ }
1417
+ function request(path, options, cacheEngine) {
1418
+ return __async$5(this, null, function* () {
1419
+ var _b;
1420
+ const defaults = {
1421
+ method: "GET",
1422
+ credentials: "same-origin",
1423
+ headers: {}
1424
+ };
1425
+ const _a = __spreadValues$6(__spreadValues$6({}, defaults), options), {
1426
+ withCredentials,
1427
+ responseType,
1428
+ cacheProps,
1429
+ cacheName,
1430
+ lunkwill,
1431
+ cache,
1432
+ query,
1433
+ json
1434
+ } = _a, opt = __objRest$2(_a, [
1435
+ "withCredentials",
1436
+ "responseType",
1437
+ "cacheProps",
1438
+ "cacheName",
1439
+ "lunkwill",
1440
+ "cache",
1441
+ "query",
1442
+ "json"
1443
+ ]);
1444
+ if (withCredentials) {
1445
+ opt.credentials = "include";
1446
+ }
1447
+ let useLunkwill = false;
1448
+ if (lunkwill !== void 0) {
1449
+ lunkwill.toHeaders(opt.headers || {});
1450
+ useLunkwill = true;
1451
+ }
1452
+ const lunkwillReturnUrl = !!opt.lunkwillReturnUrl;
1453
+ delete opt.lunkwillReturnUrl;
1454
+ if (json !== void 0) {
1455
+ opt.body = JSON.stringify(json);
1456
+ const headers = opt.headers || {};
1457
+ headers["Content-Type"] = "application/json";
1458
+ opt.headers = headers;
1459
+ }
1460
+ const url = generateUrl(path, query);
1461
+ const makeRequest = () => __async$5(this, null, function* () {
1462
+ let response;
1463
+ try {
1464
+ response = yield fetch(url, opt);
1465
+ } catch (e) {
1466
+ if (opt.signal && opt.signal.aborted) {
1467
+ throw e;
1090
1468
  }
1091
- return this.connector.get("resource.search", requestOptions, __spreadValues$5({
1092
- serialization: "full"
1093
- }, query)).then((resources) => {
1094
- if ((requestOptions == null ? void 0 : requestOptions.cache) && resources) {
1095
- for (const x of resources) {
1096
- this.cache.add("resource.item", Promise.resolve(x), {
1097
- id: x.resource.id
1098
- });
1099
- }
1100
- }
1101
- return resources;
1102
- });
1103
- }
1104
- return items;
1105
- });
1106
- }
1107
- getParent(resource, requestOptions) {
1108
- return this.getOne(resource, requestOptions).then((child) => {
1109
- if (child) {
1110
- return this.getOne(child.resource.parent.id, requestOptions);
1111
- }
1112
- return Promise.resolve(void 0);
1113
- });
1114
- }
1115
- getChildrenOf(resource, requestOptions) {
1116
- return this.getIdOrFail(resource).then(
1117
- (parent) => this._getChildrenOf(parent, requestOptions)
1118
- );
1119
- }
1120
- update(resource, data) {
1121
- return this.getId(resource).then((id) => {
1122
- if (id !== void 0) {
1123
- return this.connector.put("resource.item", { data }, { id });
1469
+ throw new NetworksResponseError();
1124
1470
  }
1125
- });
1126
- }
1127
- /**
1128
- * Fast way to delete resource from NGW and clean cache.
1129
- * @param resource - Resource definition
1130
- */
1131
- delete(resource) {
1132
- return this.getId(resource).then((id) => {
1133
- if (id !== void 0) {
1134
- return this.connector.delete("resource.item", null, { id }).then(() => {
1135
- this._cleanResourceItemCache(id);
1136
- return void 0;
1137
- });
1138
- }
1139
- });
1140
- }
1141
- _getChildrenOf(parent, requestOptions, _items = []) {
1142
- return this.connector.get("resource.collection", requestOptions, {
1143
- parent
1144
- }).then((items) => {
1145
- const recursivePromises = [];
1146
- for (const item of items) {
1147
- if (requestOptions == null ? void 0 : requestOptions.cache) {
1148
- this.cache.add("resource.item", Promise.resolve(item), {
1149
- id: item.resource.id
1150
- });
1151
- }
1152
- _items.push(item);
1153
- if ((requestOptions == null ? void 0 : requestOptions.recursive) && item.resource.children) {
1154
- recursivePromises.push(
1155
- this._getChildrenOf(item.resource.id, requestOptions, _items)
1156
- );
1471
+ if (useLunkwill && lunkwillCheckResponse(response)) {
1472
+ const lwRespUrl = yield lunkwillResponseUrl(response);
1473
+ if (lunkwillReturnUrl) {
1474
+ return lwRespUrl;
1157
1475
  }
1476
+ response = yield lunkwillFetch(lwRespUrl);
1158
1477
  }
1159
- if (recursivePromises.length) {
1160
- return Promise.all(recursivePromises).then(() => {
1161
- return _items;
1162
- });
1163
- }
1164
- return _items;
1165
- });
1166
- }
1167
- _cleanResourceItemCache(id) {
1168
- return __async$4(this, null, function* () {
1169
- var _a;
1170
- const all = this.cache.all();
1171
- const toDelete = [];
1172
- for (const c of all) {
1173
- const cid = (_a = c.props) == null ? void 0 : _a.id;
1174
- if (["resource.item", "resource"].includes(c.key) && cid !== void 0) {
1175
- if (typeof cid === "number") {
1176
- if (cid === id) {
1177
- toDelete.push(c);
1178
- }
1179
- } else {
1180
- const rid = yield this.getId(cid);
1181
- if (rid === id) {
1182
- toDelete.push(c);
1183
- }
1184
- }
1478
+ const respCType = response.headers.get("content-type");
1479
+ const respJSON = respCType && (respCType.includes("application/json") || respCType.includes("application/vnd.lunkwill.request-summary+json"));
1480
+ let body;
1481
+ try {
1482
+ const respMedia = respCType && isMediaContentType(respCType);
1483
+ if (responseType === "blob" || respMedia) {
1484
+ body = yield response.blob();
1485
+ } else if (respJSON) {
1486
+ body = yield response.json();
1487
+ } else {
1488
+ throw new InvalidResponseError();
1489
+ }
1490
+ } catch (e) {
1491
+ if (e.name === "AbortError" || e instanceof InvalidResponseError) {
1492
+ throw e;
1185
1493
  }
1494
+ throw new InvalidResponseError();
1186
1495
  }
1187
- for (const d of toDelete) {
1188
- this.cache.delete(d);
1496
+ if (400 <= response.status && response.status <= 599) {
1497
+ throw new ServerResponseError(body);
1189
1498
  }
1499
+ return body;
1190
1500
  });
1191
- }
1192
- _fetchResourceById(id, requestOptions) {
1193
- return this.connector.get("resource.item", requestOptions, { id });
1194
- }
1195
- _fetchResourceBy(resource, requestOptions) {
1196
- return this.getMany(resource, requestOptions).then((resources) => {
1197
- return resources[0];
1198
- });
1199
- }
1200
- _resourceCacheFilter(resource) {
1201
- return Promise.all(this.cache.matchAll("resource.item")).then(
1202
- (resources) => {
1203
- const items = [];
1204
- resources.filter((x) => {
1205
- if (x) {
1206
- if (resource.keyname && x.resource.keyname) {
1207
- return resource.keyname === x.resource.keyname;
1208
- }
1209
- if (defined(resource.id) && defined(x.resource.id)) {
1210
- return resource.id === x.resource.id;
1211
- }
1212
- return resourceCompare(resource, x.resource);
1213
- }
1214
- });
1215
- return items;
1216
- }
1217
- );
1218
- }
1219
- }
1220
-
1221
- const CONNECTORS = [];
1222
- function addConnector(connector) {
1223
- CONNECTORS.push(connector);
1224
- }
1225
- function findConnector(options) {
1226
- return CONNECTORS.find((x) => {
1227
- if (x.options.baseUrl === options.baseUrl) {
1228
- if (options.auth) {
1229
- if (x.options.auth) {
1230
- return objectDeepEqual(x.options.auth, options.auth);
1231
- }
1232
- } else {
1233
- return true;
1234
- }
1501
+ if (cacheEngine && cache !== false && ((_b = opt.method) == null ? void 0 : _b.toUpperCase()) === "GET") {
1502
+ const props = cacheProps ? cacheProps : __spreadValues$6({}, objectRemoveEmpty({
1503
+ withCredentials,
1504
+ responseType
1505
+ }));
1506
+ return cacheEngine.add(cacheName || url, makeRequest, {
1507
+ props,
1508
+ expirationTime: cache ? void 0 : 500
1509
+ });
1235
1510
  }
1511
+ return makeRequest();
1236
1512
  });
1237
1513
  }
1238
- function removeConnector(connector) {
1239
- const index = CONNECTORS.indexOf(connector);
1240
- if (index !== -1) {
1241
- CONNECTORS.splice(index, 1);
1242
- }
1243
- }
1244
-
1245
- class AbortError extends Error {
1246
- constructor(message = "AbortError") {
1247
- super(message);
1248
- this.name = "AbortError";
1249
- }
1250
- }
1251
1514
 
1252
1515
  var __defProp$7 = Object.defineProperty;
1516
+ var __defProps$4 = Object.defineProperties;
1517
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
1518
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
1519
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
1520
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
1253
1521
  var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1254
- var __publicField$4 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
1255
- class InsufficientPermissionsError extends NgwError {
1256
- constructor(obj) {
1257
- super(obj);
1258
- __publicField$4(this, "name", "InsufficientPermissionsError");
1259
- __publicField$4(this, "exception", "nextgisweb.core.exception.InsufficientPermissions");
1260
- Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1261
- }
1262
- }
1263
-
1264
- const templateRe = /\{ *([\w_-]+) *\}/g;
1265
- function template(str, data) {
1266
- return str.replace(templateRe, (s, key) => {
1267
- let value = data[key];
1268
- if (value === void 0) {
1269
- throw new Error("No value provided for letiable " + s);
1270
- } else if (typeof value === "function") {
1271
- value = value(data);
1272
- }
1273
- return value;
1274
- });
1275
- }
1276
-
1277
- var __defProp$6 = Object.defineProperty;
1278
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
1279
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
1280
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
1281
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1282
- var __spreadValues$4 = (a, b) => {
1522
+ var __spreadValues$5 = (a, b) => {
1283
1523
  for (var prop in b || (b = {}))
1284
- if (__hasOwnProp$4.call(b, prop))
1285
- __defNormalProp$6(a, prop, b[prop]);
1286
- if (__getOwnPropSymbols$4)
1287
- for (var prop of __getOwnPropSymbols$4(b)) {
1288
- if (__propIsEnum$4.call(b, prop))
1289
- __defNormalProp$6(a, prop, b[prop]);
1524
+ if (__hasOwnProp$5.call(b, prop))
1525
+ __defNormalProp$7(a, prop, b[prop]);
1526
+ if (__getOwnPropSymbols$5)
1527
+ for (var prop of __getOwnPropSymbols$5(b)) {
1528
+ if (__propIsEnum$5.call(b, prop))
1529
+ __defNormalProp$7(a, prop, b[prop]);
1290
1530
  }
1291
1531
  return a;
1292
1532
  };
1293
- var __async$3 = (__this, __arguments, generator) => {
1533
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1534
+ var __objRest$1 = (source, exclude) => {
1535
+ var target = {};
1536
+ for (var prop in source)
1537
+ if (__hasOwnProp$5.call(source, prop) && exclude.indexOf(prop) < 0)
1538
+ target[prop] = source[prop];
1539
+ if (source != null && __getOwnPropSymbols$5)
1540
+ for (var prop of __getOwnPropSymbols$5(source)) {
1541
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$5.call(source, prop))
1542
+ target[prop] = source[prop];
1543
+ }
1544
+ return target;
1545
+ };
1546
+ var __async$4 = (__this, __arguments, generator) => {
1294
1547
  return new Promise((resolve, reject) => {
1295
1548
  var fulfilled = (value) => {
1296
1549
  try {
@@ -1310,68 +1563,84 @@ var Geocoder = (function (exports) {
1310
1563
  step((generator = generator.apply(__this, __arguments)).next());
1311
1564
  });
1312
1565
  };
1313
- function apiRequest(opt) {
1314
- return __async$3(this, null, function* () {
1315
- const { params, name, connector, requestOptions } = opt;
1316
- const apiItems = yield connector.connect();
1317
- let apiItem = apiItems && apiItems[name];
1318
- if (apiItem) {
1319
- apiItem = [...apiItem];
1320
- let url = apiItem.shift();
1321
- if (apiItem.length) {
1322
- const replaceParams = {};
1323
- for (let fry = 0; fry < apiItem.length; fry++) {
1324
- const arg = apiItem[fry];
1325
- replaceParams[fry] = `{${arg}}`;
1326
- if (params[arg] === void 0) {
1327
- throw new Error(`\`${arg}\` URL API argument is not specified`);
1328
- }
1329
- }
1330
- if (url) {
1331
- url = template(url, replaceParams);
1332
- }
1333
- }
1334
- if (params) {
1335
- const paramArray = [];
1336
- const paramList = params.paramList;
1337
- if (Array.isArray(paramList)) {
1338
- paramList.forEach(([key, value]) => {
1339
- paramArray.push(`${key}=${value}`);
1340
- });
1341
- }
1342
- for (const p in params) {
1343
- if (apiItem.indexOf(p) === -1) {
1344
- paramArray.push(`${p}=${params[p]}`);
1345
- }
1346
- }
1347
- if (paramArray.length) {
1348
- url = `${url}?${paramArray.join("&")}`;
1349
- }
1350
- }
1351
- if (url) {
1352
- return connector.makeQuery(url, params, __spreadValues$4({
1353
- cacheName: name
1354
- }, requestOptions));
1355
- } else {
1356
- throw new Error("Request URL is not set");
1357
- }
1358
- } else {
1359
- return void 0;
1566
+ function routeURL(name, baseUrl, routeData, ...rest) {
1567
+ const [template, ...params] = routeData[name];
1568
+ const first = rest[0];
1569
+ let sub;
1570
+ if (first === void 0) {
1571
+ sub = [];
1572
+ } else if (typeof first === "object" && first !== null) {
1573
+ if (rest.length > 1) {
1574
+ throw new Error("Too many arguments for route(name, object)!");
1360
1575
  }
1361
- });
1576
+ sub = [];
1577
+ for (const [p, v] of Object.entries(first)) {
1578
+ sub[params.indexOf(p)] = String(v);
1579
+ }
1580
+ } else {
1581
+ sub = rest.map((v) => String(v));
1582
+ }
1583
+ return fixUrlStr(
1584
+ baseUrl + template.replace(/\{(\w+)\}/g, function(m, a) {
1585
+ const idx = parseInt(a);
1586
+ const value = sub[idx];
1587
+ if (value === void 0) {
1588
+ const msg = `Undefined parameter ${idx} in "${template}".`;
1589
+ throw new Error(msg);
1590
+ }
1591
+ return String(value);
1592
+ })
1593
+ );
1362
1594
  }
1363
-
1364
- var __defProp$5 = Object.defineProperty;
1365
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1366
- var __publicField$3 = (obj, key, value) => __defNormalProp$5(obj, key + "" , value);
1367
- class NetworkError extends Error {
1368
- constructor(url) {
1369
- super();
1370
- __publicField$3(this, "name", "NetworkError");
1371
- Object.setPrototypeOf(this, NetworkError.prototype);
1372
- this.message = `Unable to request ${url}.
1373
- Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`;
1595
+ function route(name, connector, ...rest) {
1596
+ const result = {
1597
+ url: (opt) => __async$4(this, null, function* () {
1598
+ var _a;
1599
+ const routeData = yield connector.connect();
1600
+ const template = routeURL(
1601
+ name,
1602
+ (_a = connector.options.baseUrl) != null ? _a : "",
1603
+ routeData,
1604
+ ...rest
1605
+ );
1606
+ return generateUrl(template, opt == null ? void 0 : opt.query);
1607
+ })
1608
+ };
1609
+ const methods = ["get", "post", "put", "delete", "patch"];
1610
+ for (const method of methods) {
1611
+ const methodResp = (requestOptions) => {
1612
+ var _b;
1613
+ const _a = requestOptions || {}, { headers: optHeaders } = _a, restOpt = __objRest$1(_a, ["headers"]);
1614
+ if ((_b = requestOptions == null ? void 0 : requestOptions.signal) == null ? void 0 : _b.aborted) {
1615
+ throw new AbortError();
1616
+ }
1617
+ return connector.connect().then((routeData) => {
1618
+ var _a2;
1619
+ const template = routeURL(
1620
+ name,
1621
+ (_a2 = connector.options.baseUrl) != null ? _a2 : "",
1622
+ routeData,
1623
+ ...rest
1624
+ );
1625
+ const headers = objectRemoveEmpty(__spreadValues$5(__spreadValues$5({}, connector.getAuthorizationHeaders()), optHeaders != null ? optHeaders : {}));
1626
+ return request(
1627
+ template,
1628
+ __spreadProps$4(__spreadValues$5({
1629
+ headers
1630
+ }, restOpt), {
1631
+ method
1632
+ }),
1633
+ connector.cache
1634
+ );
1635
+ });
1636
+ };
1637
+ result[method] = methodResp;
1374
1638
  }
1639
+ return result;
1640
+ }
1641
+
1642
+ function isObject(val) {
1643
+ return Object.prototype.toString.call(val) === "[object Object]";
1375
1644
  }
1376
1645
 
1377
1646
  let loadData;
@@ -1386,7 +1655,7 @@ var Geocoder = (function (exports) {
1386
1655
  const getResponseText = () => {
1387
1656
  try {
1388
1657
  return JSON.parse(xhr.responseText);
1389
- } catch (er) {
1658
+ } catch (e) {
1390
1659
  return xhr.responseText;
1391
1660
  }
1392
1661
  };
@@ -1452,42 +1721,434 @@ var Geocoder = (function (exports) {
1452
1721
  xhr.abort();
1453
1722
  });
1454
1723
  }
1455
- xhr.send(data);
1456
- };
1724
+ xhr.send(data);
1725
+ };
1726
+ }
1727
+
1728
+ const CONNECTORS = [];
1729
+ function addConnector(connector) {
1730
+ CONNECTORS.push(connector);
1731
+ }
1732
+ function findConnector(options) {
1733
+ return CONNECTORS.find((x) => {
1734
+ if (x.options.baseUrl === options.baseUrl) {
1735
+ if (options.auth) {
1736
+ if (x.options.auth) {
1737
+ return objectDeepEqual(x.options.auth, options.auth);
1738
+ }
1739
+ } else {
1740
+ return true;
1741
+ }
1742
+ }
1743
+ });
1744
+ }
1745
+ function removeConnector(connector) {
1746
+ const index = CONNECTORS.indexOf(connector);
1747
+ if (index !== -1) {
1748
+ CONNECTORS.splice(index, 1);
1749
+ }
1750
+ }
1751
+
1752
+ var __defProp$6 = Object.defineProperty;
1753
+ var __defProps$3 = Object.defineProperties;
1754
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
1755
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
1756
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
1757
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
1758
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1759
+ var __spreadValues$4 = (a, b) => {
1760
+ for (var prop in b || (b = {}))
1761
+ if (__hasOwnProp$4.call(b, prop))
1762
+ __defNormalProp$6(a, prop, b[prop]);
1763
+ if (__getOwnPropSymbols$4)
1764
+ for (var prop of __getOwnPropSymbols$4(b)) {
1765
+ if (__propIsEnum$4.call(b, prop))
1766
+ __defNormalProp$6(a, prop, b[prop]);
1767
+ }
1768
+ return a;
1769
+ };
1770
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
1771
+ var __objRest = (source, exclude) => {
1772
+ var target = {};
1773
+ for (var prop in source)
1774
+ if (__hasOwnProp$4.call(source, prop) && exclude.indexOf(prop) < 0)
1775
+ target[prop] = source[prop];
1776
+ if (source != null && __getOwnPropSymbols$4)
1777
+ for (var prop of __getOwnPropSymbols$4(source)) {
1778
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$4.call(source, prop))
1779
+ target[prop] = source[prop];
1780
+ }
1781
+ return target;
1782
+ };
1783
+ var __publicField$4 = (obj, key, value) => __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
1784
+ var __async$3 = (__this, __arguments, generator) => {
1785
+ return new Promise((resolve, reject) => {
1786
+ var fulfilled = (value) => {
1787
+ try {
1788
+ step(generator.next(value));
1789
+ } catch (e) {
1790
+ reject(e);
1791
+ }
1792
+ };
1793
+ var rejected = (value) => {
1794
+ try {
1795
+ step(generator.throw(value));
1796
+ } catch (e) {
1797
+ reject(e);
1798
+ }
1799
+ };
1800
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1801
+ step((generator = generator.apply(__this, __arguments)).next());
1802
+ });
1803
+ };
1804
+ let ID = 0;
1805
+ let REQUEST_ID = 0;
1806
+ class NgwConnector {
1807
+ constructor(options) {
1808
+ this.options = options;
1809
+ __publicField$4(this, "id", ID++);
1810
+ __publicField$4(this, "emitter", new EventEmitter());
1811
+ __publicField$4(this, "user");
1812
+ __publicField$4(this, "cache");
1813
+ __publicField$4(this, "withCredentials");
1814
+ __publicField$4(this, "client", `NextGIS-NGW-Connector/${pkg.version}`);
1815
+ __publicField$4(this, "routeStr", "/api/component/pyramid/route");
1816
+ __publicField$4(this, "activeRequests", {});
1817
+ __publicField$4(this, "requestTransform");
1818
+ const exist = findConnector(options);
1819
+ this.cache = new Cache({ namespace: options.cacheId });
1820
+ if (exist) {
1821
+ return exist;
1822
+ } else {
1823
+ const { route: route2, requestTransform, withCredentials } = this.options;
1824
+ if (route2) {
1825
+ this.routeStr = route2;
1826
+ }
1827
+ if (requestTransform) {
1828
+ this.requestTransform = requestTransform;
1829
+ }
1830
+ if (withCredentials !== void 0) {
1831
+ this.withCredentials = withCredentials;
1832
+ }
1833
+ addConnector(this);
1834
+ }
1835
+ }
1836
+ /**
1837
+ * Clear the cache.
1838
+ */
1839
+ clearCache() {
1840
+ this.cache.clean();
1841
+ }
1842
+ setRequestTransform(requestTransform) {
1843
+ this.requestTransform = requestTransform;
1844
+ }
1845
+ /**
1846
+ * Fast way to specify the connection address to NextGIS Web.
1847
+ * The current connection will be severed.
1848
+ * @param baseUrl - NGW url
1849
+ */
1850
+ setNgw(baseUrl) {
1851
+ this.logout();
1852
+ this.options.baseUrl = baseUrl;
1853
+ addConnector(this);
1854
+ }
1855
+ /**
1856
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
1857
+ * @remarks
1858
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1859
+ * Can be used to check connection.
1860
+ * @example
1861
+ * ```javascript
1862
+ * const connector = new NgwConnector({ baseUrl: 'https://demo.nextgis.com' });
1863
+ * connector.connect()
1864
+ * .then(() => console.log('Ok'))
1865
+ * .catch((er) => console.log('Connection problem', er));
1866
+ * ```
1867
+ */
1868
+ connect() {
1869
+ return __async$3(this, arguments, function* ({
1870
+ signal
1871
+ } = {}) {
1872
+ const auth = this.options.auth;
1873
+ if (auth) {
1874
+ const { login, password } = auth;
1875
+ if (login && password) {
1876
+ yield this._login({ login, password });
1877
+ }
1878
+ }
1879
+ const routeUrl = `${this.routeStr}?client=${this.client}`;
1880
+ return this.makeQuery(
1881
+ routeUrl,
1882
+ {},
1883
+ {
1884
+ cacheName: "route",
1885
+ signal,
1886
+ cache: true,
1887
+ cacheProps: {
1888
+ id: this.id,
1889
+ auth,
1890
+ baseUrl: this.options.baseUrl
1891
+ }
1892
+ }
1893
+ );
1894
+ });
1895
+ }
1896
+ /**
1897
+ * Quick way to change NextGIS Web user.
1898
+ * @param credentials - New user credentials
1899
+ */
1900
+ login(credentials, options) {
1901
+ this.logout();
1902
+ addConnector(this);
1903
+ return this._login(credentials, options);
1904
+ }
1905
+ /**
1906
+ * Disconnecting a user. Aborting all current requests
1907
+ */
1908
+ logout() {
1909
+ this.abort();
1910
+ removeConnector(this);
1911
+ this.options.auth = void 0;
1912
+ this.user = void 0;
1913
+ this.clearCache();
1914
+ this.emitter.emit("logout");
1915
+ }
1916
+ getUserInfo(credentials, options) {
1917
+ return __async$3(this, null, function* () {
1918
+ if (this.user && this.user.id) {
1919
+ return this.user;
1920
+ }
1921
+ if (credentials) {
1922
+ this.options.auth = credentials;
1923
+ }
1924
+ const options_ = __spreadValues$4({
1925
+ headers: this.getAuthorizationHeaders(credentials),
1926
+ cache: true
1927
+ }, options);
1928
+ return this.makeQuery(
1929
+ "/api/component/auth/current_user",
1930
+ {},
1931
+ options_
1932
+ );
1933
+ });
1934
+ }
1935
+ /**
1936
+ * Obtaining the required Headers for authentication of requests in the NGW.
1937
+ */
1938
+ getAuthorizationHeaders(credentials) {
1939
+ const client = this.makeClientId(credentials);
1940
+ if (client) {
1941
+ return {
1942
+ Authorization: `Basic ${client}`
1943
+ };
1944
+ }
1945
+ return {};
1946
+ }
1947
+ makeClientId(credentials) {
1948
+ credentials = credentials || this.options.auth;
1949
+ if (credentials) {
1950
+ const { login, password } = credentials;
1951
+ const encodedStr = [login, password].map(encodeURIComponent).join(":");
1952
+ {
1953
+ return window.btoa(encodedStr);
1954
+ }
1955
+ }
1956
+ }
1957
+ /** Stop all api requests */
1958
+ abort() {
1959
+ for (const abortController of Object.values(this.activeRequests)) {
1960
+ abortController.abort();
1961
+ }
1962
+ this.activeRequests = {};
1963
+ }
1964
+ getActiveApiRequests() {
1965
+ return __spreadValues$4({}, this.activeRequests);
1966
+ }
1967
+ route(name, ...rest) {
1968
+ return route(name, this, ...rest);
1969
+ }
1970
+ /**
1971
+ * Send request to NGW.
1972
+ * @param url - URL address to NGW
1973
+ * @param params - Query params
1974
+ * @param options - Request options
1975
+ */
1976
+ makeQuery(_0, _1) {
1977
+ return __async$3(this, arguments, function* (url, params, options = {}) {
1978
+ var _b;
1979
+ url = (this.options.baseUrl ? this.options.baseUrl : "") + url;
1980
+ if (!url) {
1981
+ throw new Error("Empty `url` not allowed");
1982
+ }
1983
+ if (params) {
1984
+ const _a = params, restParams = __objRest(_a, ["paramList"]);
1985
+ url = template(url, restParams);
1986
+ }
1987
+ url = encodeURI(fixUrlStr(url));
1988
+ options = __spreadValues$4({ withCredentials: this.withCredentials }, options);
1989
+ const {
1990
+ cache,
1991
+ signal: externalSignal,
1992
+ method = "GET",
1993
+ headers,
1994
+ cacheName,
1995
+ cacheProps,
1996
+ responseType,
1997
+ withCredentials
1998
+ } = options;
1999
+ const internalAbortController = new AbortController();
2000
+ const internalSignal = internalAbortController.signal;
2001
+ if (externalSignal) {
2002
+ if (externalSignal.aborted) {
2003
+ throw new AbortError();
2004
+ }
2005
+ externalSignal.addEventListener("abort", () => {
2006
+ internalAbortController.abort();
2007
+ });
2008
+ }
2009
+ options.signal = internalSignal;
2010
+ const createPromise = () => __async$3(this, null, function* () {
2011
+ const id = REQUEST_ID++;
2012
+ this.activeRequests[id] = internalAbortController;
2013
+ try {
2014
+ return this._loadData(url, options);
2015
+ } finally {
2016
+ this._cleanActiveRequest(id);
2017
+ }
2018
+ });
2019
+ if (method === "GET") {
2020
+ const cacheOptions = cacheProps ? cacheProps : __spreadProps$3(__spreadValues$4({}, objectRemoveEmpty({
2021
+ headers,
2022
+ withCredentials,
2023
+ responseType,
2024
+ baseUrl: this.options.baseUrl,
2025
+ userId: (_b = this.user) == null ? void 0 : _b.id
2026
+ })), {
2027
+ params
2028
+ });
2029
+ return this.cache.add(cacheName || url, createPromise, {
2030
+ props: cacheOptions,
2031
+ expirationTime: cache ? void 0 : 500
2032
+ });
2033
+ }
2034
+ return createPromise();
2035
+ });
2036
+ }
2037
+ _loadData(url, options) {
2038
+ options.responseType = options.responseType || "json";
2039
+ return new Promise((resolve, reject) => {
2040
+ var _a;
2041
+ if (this.user) {
2042
+ options = options || {};
2043
+ options.headers = __spreadValues$4(__spreadValues$4({}, this.getAuthorizationHeaders()), options.headers);
2044
+ }
2045
+ if (this.requestTransform) {
2046
+ const [transUrl, transOptions] = this.requestTransform(url, options);
2047
+ url = transUrl;
2048
+ options = transOptions;
2049
+ }
2050
+ let runOnAbort = void 0;
2051
+ loadData(url, resolve, options, reject, (handler) => {
2052
+ runOnAbort = handler;
2053
+ });
2054
+ (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
2055
+ if (runOnAbort !== void 0) {
2056
+ runOnAbort();
2057
+ }
2058
+ reject(new AbortError());
2059
+ });
2060
+ }).catch((httpError) => {
2061
+ if (httpError.name !== "AbortError") {
2062
+ {
2063
+ console.warn("DEV WARN", httpError);
2064
+ }
2065
+ const er = this._handleHttpError(httpError);
2066
+ if (er) {
2067
+ throw er;
2068
+ }
2069
+ }
2070
+ throw httpError;
2071
+ });
2072
+ }
2073
+ _login(credentials, options) {
2074
+ return __async$3(this, null, function* () {
2075
+ try {
2076
+ const data = yield this.getUserInfo(credentials, options);
2077
+ this.user = data;
2078
+ this.emitter.emit("login", data);
2079
+ return data;
2080
+ } catch (er) {
2081
+ this.emitter.emit("login:error", er);
2082
+ throw er;
2083
+ }
2084
+ });
2085
+ }
2086
+ _cleanActiveRequest(requestId) {
2087
+ delete this.activeRequests[requestId];
2088
+ }
2089
+ _handleHttpError(er) {
2090
+ if (er) {
2091
+ if (er instanceof NgwError) {
2092
+ if (er.exception === "nextgisweb.resource.exception.ResourceNotFound") {
2093
+ throw new ResourceNotFoundError(er);
2094
+ } else if (er.exception === "nextgisweb.core.exception.InsufficientPermissions") {
2095
+ throw new InsufficientPermissionsError(er);
2096
+ }
2097
+ }
2098
+ }
2099
+ return er;
2100
+ }
2101
+ }
2102
+ __publicField$4(NgwConnector, "errors", errors);
2103
+
2104
+ function resourceCompare(res1, res2) {
2105
+ return objectDeepEqual(res1, res2);
2106
+ }
2107
+
2108
+ const exclude = ["description"];
2109
+ function resourceToQuery(resource, prefix = "") {
2110
+ prefix = prefix ? prefix + "__" : "";
2111
+ const query = {};
2112
+ for (const [key, value] of Object.entries(resource)) {
2113
+ if (exclude.indexOf(key) === -1) {
2114
+ if (isObject(value)) {
2115
+ if (key === "owner_user") {
2116
+ const children = resourceToQuery(
2117
+ value,
2118
+ key
2119
+ );
2120
+ Object.assign(query, children);
2121
+ } else if (key === "parent" && "id" in value) {
2122
+ query.parent_id = value.id;
2123
+ }
2124
+ } else if (defined(value)) {
2125
+ query[prefix + key] = value;
2126
+ }
2127
+ }
2128
+ }
2129
+ return query;
1457
2130
  }
1458
2131
 
1459
- var __defProp$4 = Object.defineProperty;
2132
+ var __defProp$5 = Object.defineProperty;
1460
2133
  var __defProps$2 = Object.defineProperties;
1461
2134
  var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
1462
2135
  var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
1463
2136
  var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1464
2137
  var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
1465
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2138
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1466
2139
  var __spreadValues$3 = (a, b) => {
1467
2140
  for (var prop in b || (b = {}))
1468
2141
  if (__hasOwnProp$3.call(b, prop))
1469
- __defNormalProp$4(a, prop, b[prop]);
2142
+ __defNormalProp$5(a, prop, b[prop]);
1470
2143
  if (__getOwnPropSymbols$3)
1471
2144
  for (var prop of __getOwnPropSymbols$3(b)) {
1472
2145
  if (__propIsEnum$3.call(b, prop))
1473
- __defNormalProp$4(a, prop, b[prop]);
2146
+ __defNormalProp$5(a, prop, b[prop]);
1474
2147
  }
1475
2148
  return a;
1476
2149
  };
1477
2150
  var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
1478
- var __objRest = (source, exclude) => {
1479
- var target = {};
1480
- for (var prop in source)
1481
- if (__hasOwnProp$3.call(source, prop) && exclude.indexOf(prop) < 0)
1482
- target[prop] = source[prop];
1483
- if (source != null && __getOwnPropSymbols$3)
1484
- for (var prop of __getOwnPropSymbols$3(source)) {
1485
- if (exclude.indexOf(prop) < 0 && __propIsEnum$3.call(source, prop))
1486
- target[prop] = source[prop];
1487
- }
1488
- return target;
1489
- };
1490
- var __publicField$2 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
2151
+ var __publicField$3 = (obj, key, value) => __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
1491
2152
  var __async$2 = (__this, __arguments, generator) => {
1492
2153
  return new Promise((resolve, reject) => {
1493
2154
  var fulfilled = (value) => {
@@ -1508,171 +2169,269 @@ var Geocoder = (function (exports) {
1508
2169
  step((generator = generator.apply(__this, __arguments)).next());
1509
2170
  });
1510
2171
  };
1511
- let ID = 0;
1512
- let REQUEST_ID = 0;
1513
- class NgwConnector {
1514
- constructor(options) {
1515
- this.options = options;
1516
- __publicField$2(this, "id", ID++);
1517
- __publicField$2(this, "emitter", new EventEmitter());
1518
- __publicField$2(this, "user");
1519
- __publicField$2(this, "resources");
1520
- __publicField$2(this, "cache");
1521
- __publicField$2(this, "withCredentials");
1522
- __publicField$2(this, "routeStr", "/api/component/pyramid/route");
1523
- __publicField$2(this, "activeRequests", {});
1524
- __publicField$2(this, "requestTransform");
1525
- const exist = findConnector(options);
1526
- this.cache = new Cache({ namespace: options.cacheId });
1527
- if (exist) {
1528
- return exist;
1529
- } else {
1530
- const { route, requestTransform, withCredentials } = this.options;
1531
- if (route) {
1532
- this.routeStr = route;
1533
- }
1534
- if (requestTransform) {
1535
- this.requestTransform = requestTransform;
1536
- }
1537
- if (withCredentials !== void 0) {
1538
- this.withCredentials = withCredentials;
1539
- }
1540
- this.resources = new ResourcesControl({
1541
- connector: this,
1542
- cacheId: options.cacheId
1543
- });
1544
- addConnector(this);
1545
- }
1546
- }
1547
- static create(options) {
1548
- return new this(options);
2172
+ class ResourcesControl {
2173
+ constructor({
2174
+ connector,
2175
+ cacheId
2176
+ }) {
2177
+ __publicField$3(this, "cache");
2178
+ __publicField$3(this, "connector");
2179
+ this.connector = connector;
2180
+ this.cache = new Cache({ namespace: cacheId });
1549
2181
  }
2182
+ // -------------------------------------------------------------------------
2183
+ // Resource Methods
2184
+ // -------------------------------------------------------------------------
1550
2185
  /**
1551
- * Clear the cache.
2186
+ * Receive resource from NGW by id, keyname or search-object parameter.
2187
+ * @param resource - Resource id, keyname or search-object
2188
+ *
2189
+ * @remarks
2190
+ * Fetching resource would be cached to speed up next call
1552
2191
  */
1553
- clearCache() {
1554
- this.cache.clean();
1555
- this.resources.cache.clean();
2192
+ getOne(resource, requestOptions) {
2193
+ const opt = __spreadValues$3({}, requestOptions);
2194
+ if (typeof resource === "string") ; else if (typeof resource === "number") ; else if (isObject(resource)) {
2195
+ if (resource.id !== void 0) {
2196
+ resource.id;
2197
+ } else {
2198
+ if (resource.keyname) {
2199
+ resource.keyname;
2200
+ }
2201
+ if (resource.display_name) {
2202
+ resource.display_name;
2203
+ }
2204
+ }
2205
+ }
2206
+ if (typeof resource === "string") {
2207
+ return this._fetchResourceBy({ keyname: resource }, opt);
2208
+ } else if (typeof resource === "number") {
2209
+ return this._fetchResourceById(resource, opt);
2210
+ } else if (isObject(resource)) {
2211
+ return this._fetchResourceBy(resource, opt);
2212
+ }
2213
+ return Promise.resolve(void 0);
1556
2214
  }
1557
- setRequestTransform(requestTransform) {
1558
- this.requestTransform = requestTransform;
2215
+ getOneOrFail(resource, requestOptions) {
2216
+ return this.getOne(resource, requestOptions).then((res) => {
2217
+ if (res) {
2218
+ return res;
2219
+ }
2220
+ throw new ResourceNotFoundError();
2221
+ });
1559
2222
  }
1560
2223
  /**
1561
- * Fast way to specify the connection address to NextGIS Web.
1562
- * The current connection will be severed.
1563
- * @param baseUrl - NGW url
2224
+ * A fast way to retrieve resource ID for any resource definition.
2225
+ * @param resource - Any available resource definition
2226
+ *
2227
+ * @remarks
2228
+ * There are situations when exactly the resource id is needed
2229
+ * (for example, to compose the correct request to the api)
2230
+ * then this method will come in handy to facilitate the extraction of the identifier
2231
+ * if the resource is specified through a keyname or other parameters.
1564
2232
  */
1565
- setNgw(baseUrl) {
1566
- this.logout();
1567
- this.options.baseUrl = baseUrl;
1568
- addConnector(this);
2233
+ getId(resource, requestOptions) {
2234
+ if (typeof resource === "number") {
2235
+ return Promise.resolve(resource);
2236
+ } else if (typeof resource === "string" || isObject(resource)) {
2237
+ return this.getOne(resource, requestOptions).then((res) => {
2238
+ if (res) {
2239
+ return res.resource.id;
2240
+ }
2241
+ });
2242
+ }
2243
+ return Promise.resolve(void 0);
1569
2244
  }
1570
2245
  /**
1571
- * Establishing a connection with NextGIS Web to fulfill all other requests.
2246
+ * A fast way to retrieve resource ID for any resource definition.
2247
+ * @param resource - Any available resource definition
2248
+ *
1572
2249
  * @remarks
1573
- * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1574
- * Can be used to check connection.
1575
- * @example
1576
- * ```javascript
1577
- * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1578
- * connector.connect()
1579
- * .then(() => console.log('Ok'))
1580
- * .catch((er) => console.log('Connection problem', er));
1581
- * ```
2250
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
2251
+ * To not make one more checks if the resource is definitely exists
1582
2252
  */
1583
- connect() {
1584
- return __async$2(this, null, function* () {
1585
- const auth = this.options.auth;
1586
- if (auth) {
1587
- const { login, password } = auth;
1588
- if (login && password) {
1589
- yield this._login({ login, password });
1590
- }
2253
+ getIdOrFail(resource, requestOptions) {
2254
+ return this.getId(resource, requestOptions).then((resp) => {
2255
+ if (resp === void 0) {
2256
+ throw new Error();
1591
2257
  }
1592
- return yield this.makeQuery(
1593
- this.routeStr,
1594
- {},
1595
- {
1596
- cacheName: "route",
1597
- cache: true,
1598
- cacheProps: {
1599
- id: this.id,
1600
- auth,
1601
- baseUrl: this.options.baseUrl
1602
- }
2258
+ return resp;
2259
+ });
2260
+ }
2261
+ getMany(resource, requestOptions) {
2262
+ return this._resourceCacheFilter(resource).then((items) => {
2263
+ if (!items.length) {
2264
+ const query = {};
2265
+ if (resource.keyname) {
2266
+ query.keyname = resource.keyname;
2267
+ } else {
2268
+ Object.assign(query, resourceToQuery(resource));
1603
2269
  }
1604
- );
2270
+ return this.connector.route("resource.search").get(__spreadProps$2(__spreadValues$3({}, requestOptions), {
2271
+ query: __spreadValues$3({
2272
+ serialization: "full"
2273
+ }, query)
2274
+ })).then((resources) => {
2275
+ if ((requestOptions == null ? void 0 : requestOptions.cache) && resources) {
2276
+ for (const x of resources) {
2277
+ this.cache.add("resource.item", Promise.resolve(x), {
2278
+ id: x.resource.id
2279
+ });
2280
+ }
2281
+ }
2282
+ return resources;
2283
+ });
2284
+ }
2285
+ return items;
1605
2286
  });
1606
2287
  }
1607
- /**
1608
- * Quick way to change NextGIS Web user.
1609
- * @param credentials - New user credentials
1610
- */
1611
- login(credentials, options) {
1612
- this.logout();
1613
- addConnector(this);
1614
- return this._login(credentials, options);
2288
+ getParent(resource, requestOptions) {
2289
+ return this.getOne(resource, requestOptions).then((child) => {
2290
+ var _a, _b;
2291
+ if ((_b = (_a = child == null ? void 0 : child.resource) == null ? void 0 : _a.parent) == null ? void 0 : _b.id) {
2292
+ return this.getOne(child.resource.parent.id, requestOptions);
2293
+ }
2294
+ return Promise.resolve(void 0);
2295
+ });
2296
+ }
2297
+ getChildrenOf(resource, requestOptions) {
2298
+ return this.getIdOrFail(resource).then(
2299
+ (parent) => this._getChildrenOf(parent, requestOptions)
2300
+ );
2301
+ }
2302
+ update(resource, data) {
2303
+ return this.getId(resource).then((id) => {
2304
+ if (id !== void 0) {
2305
+ return this.connector.put("resource.item", { data }, { id });
2306
+ }
2307
+ });
1615
2308
  }
1616
2309
  /**
1617
- * Disconnecting a user. Aborting all current requests
2310
+ * Fast way to delete resource from NGW and clean cache.
2311
+ * @param resource - Resource definition
1618
2312
  */
1619
- logout() {
1620
- this.abort();
1621
- removeConnector(this);
1622
- this.options.auth = void 0;
1623
- this.user = void 0;
1624
- this.clearCache();
1625
- this.emitter.emit("logout");
2313
+ delete(resource) {
2314
+ return this.getId(resource).then((id) => {
2315
+ if (id !== void 0) {
2316
+ return this.connector.delete("resource.item", null, { id }).then(() => {
2317
+ this._cleanResourceItemCache(id);
2318
+ return void 0;
2319
+ });
2320
+ }
2321
+ });
1626
2322
  }
1627
- getUserInfo(credentials, options) {
2323
+ _getChildrenOf(_0, _1) {
2324
+ return __async$2(this, arguments, function* (parentDef, requestOptions, _items = []) {
2325
+ let parent = void 0;
2326
+ if (typeof parentDef === "string") {
2327
+ parent = yield this.getId(parentDef, requestOptions);
2328
+ } else if (typeof parentDef === "object") {
2329
+ parent = parentDef.id;
2330
+ } else {
2331
+ parent = parentDef;
2332
+ }
2333
+ const items = yield this.connector.route("resource.collection").get(__spreadProps$2(__spreadValues$3({}, requestOptions), {
2334
+ query: {
2335
+ parent
2336
+ }
2337
+ }));
2338
+ const recursivePromises = [];
2339
+ for (const item of items) {
2340
+ if (requestOptions == null ? void 0 : requestOptions.cache) {
2341
+ this.cache.add("resource.item", Promise.resolve(item), {
2342
+ id: item.resource.id
2343
+ });
2344
+ }
2345
+ _items.push(item);
2346
+ if ((requestOptions == null ? void 0 : requestOptions.recursive) && item.resource.children) {
2347
+ recursivePromises.push(
2348
+ this._getChildrenOf(item.resource.id, requestOptions, _items)
2349
+ );
2350
+ }
2351
+ }
2352
+ if (recursivePromises.length) {
2353
+ return Promise.all(recursivePromises).then(() => {
2354
+ return _items;
2355
+ });
2356
+ }
2357
+ return _items;
2358
+ });
2359
+ }
2360
+ _cleanResourceItemCache(id) {
1628
2361
  return __async$2(this, null, function* () {
1629
- if (this.user && this.user.id) {
1630
- return this.user;
2362
+ var _a;
2363
+ const all = this.cache.all();
2364
+ const toDelete = [];
2365
+ for (const c of all) {
2366
+ const cid = (_a = c.props) == null ? void 0 : _a.id;
2367
+ if (["resource.item", "resource"].includes(c.key) && cid !== void 0) {
2368
+ if (typeof cid === "number") {
2369
+ if (cid === id) {
2370
+ toDelete.push(c);
2371
+ }
2372
+ } else {
2373
+ const rid = yield this.getId(cid);
2374
+ if (rid === id) {
2375
+ toDelete.push(c);
2376
+ }
2377
+ }
2378
+ }
1631
2379
  }
1632
- if (credentials) {
1633
- this.options.auth = credentials;
2380
+ for (const d of toDelete) {
2381
+ this.cache.delete(d);
1634
2382
  }
1635
- const options_ = __spreadValues$3({
1636
- headers: this.getAuthorizationHeaders(credentials)
1637
- }, options);
1638
- return this.makeQuery(
1639
- "/api/component/auth/current_user",
1640
- {},
1641
- options_
1642
- );
1643
2383
  });
1644
2384
  }
1645
- /**
1646
- * Obtaining the required Headers for authentication of requests in the NGW.
1647
- */
1648
- getAuthorizationHeaders(credentials) {
1649
- const client = this.makeClientId(credentials);
1650
- if (client) {
1651
- return {
1652
- Authorization: `Basic ${client}`
1653
- };
1654
- }
2385
+ _fetchResourceById(id, requestOptions) {
2386
+ return this.connector.route("resource.item", { id }).get(requestOptions);
1655
2387
  }
1656
- makeClientId(credentials) {
1657
- credentials = credentials || this.options.auth;
1658
- if (credentials) {
1659
- const { login, password } = credentials;
1660
- const str = `${login}:${password}`;
1661
- const encodedStr = encodeURIComponent(str);
1662
- {
1663
- return window.btoa(encodedStr);
2388
+ _fetchResourceBy(resource, requestOptions) {
2389
+ return this.getMany(resource, requestOptions).then((resources) => {
2390
+ return resources[0];
2391
+ });
2392
+ }
2393
+ _resourceCacheFilter(resource) {
2394
+ return Promise.all(this.cache.matchAll("resource.item")).then(
2395
+ (resources) => {
2396
+ const items = [];
2397
+ resources.filter((x) => {
2398
+ if (x) {
2399
+ if (resource.keyname && x.resource.keyname) {
2400
+ return resource.keyname === x.resource.keyname;
2401
+ }
2402
+ if (defined(resource.id) && defined(x.resource.id)) {
2403
+ return resource.id === x.resource.id;
2404
+ }
2405
+ return resourceCompare(resource, x.resource);
2406
+ }
2407
+ });
2408
+ return items;
1664
2409
  }
1665
- }
2410
+ );
1666
2411
  }
1667
- /** Stop all api requests */
1668
- abort() {
1669
- for (const abortController of Object.values(this.activeRequests)) {
1670
- abortController.abort();
1671
- }
1672
- this.activeRequests = {};
2412
+ }
2413
+
2414
+ var __defProp$4 = Object.defineProperty;
2415
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2416
+ var __publicField$2 = (obj, key, value) => __defNormalProp$4(obj, key + "" , value);
2417
+ class NgwConnectorExtended extends NgwConnector {
2418
+ constructor(options) {
2419
+ super(options);
2420
+ __publicField$2(this, "resources");
2421
+ this.resources = new ResourcesControl({
2422
+ connector: this,
2423
+ cacheId: options.cacheId
2424
+ });
1673
2425
  }
1674
- getActiveApiRequests() {
1675
- return __spreadValues$3({}, this.activeRequests);
2426
+ static create(options) {
2427
+ return new this(options);
2428
+ }
2429
+ /**
2430
+ * Clear the cache.
2431
+ */
2432
+ clearCache() {
2433
+ super.clearCache();
2434
+ this.resources.cache.clean();
1676
2435
  }
1677
2436
  /**
1678
2437
  * Send request to NGW api router.
@@ -1791,75 +2550,6 @@ var Geocoder = (function (exports) {
1791
2550
  options
1792
2551
  );
1793
2552
  }
1794
- /**
1795
- * Send request to NGW.
1796
- * @param url - URL address to NGW
1797
- * @param params - Query params
1798
- * @param options - Request options
1799
- */
1800
- makeQuery(_0, _1) {
1801
- return __async$2(this, arguments, function* (url, params, options = {}) {
1802
- var _b;
1803
- url = (this.options.baseUrl ? this.options.baseUrl : "") + url;
1804
- if (!url) {
1805
- throw new Error("Empty `url` not allowed");
1806
- }
1807
- if (params) {
1808
- const _a = params, restParams = __objRest(_a, ["paramList"]);
1809
- url = template(url, restParams);
1810
- }
1811
- url = encodeURI(fixUrlStr(url));
1812
- options = __spreadValues$3({ withCredentials: this.withCredentials }, options);
1813
- const {
1814
- cache,
1815
- signal: externalSignal,
1816
- method = "GET",
1817
- headers,
1818
- cacheName,
1819
- cacheProps,
1820
- responseType,
1821
- withCredentials
1822
- } = options;
1823
- const internalAbortController = new AbortController();
1824
- const internalSignal = internalAbortController.signal;
1825
- if (externalSignal) {
1826
- if (externalSignal.aborted) {
1827
- throw new AbortError();
1828
- }
1829
- externalSignal.addEventListener("abort", () => {
1830
- internalAbortController.abort();
1831
- });
1832
- }
1833
- options.signal = internalSignal;
1834
- const createPromise = () => __async$2(this, null, function* () {
1835
- const id = REQUEST_ID++;
1836
- this.activeRequests[id] = internalAbortController;
1837
- try {
1838
- return this._loadData(url, options);
1839
- } finally {
1840
- this._cleanActiveRequest(id);
1841
- }
1842
- });
1843
- if (cache && method === "GET") {
1844
- const cacheOptions = cacheProps ? cacheProps : __spreadProps$2(__spreadValues$3({}, objectRemoveEmpty({
1845
- headers,
1846
- withCredentials,
1847
- responseType,
1848
- baseUrl: this.options.baseUrl,
1849
- userId: (_b = this.user) == null ? void 0 : _b.id
1850
- })), {
1851
- params
1852
- });
1853
- return this.cache.add(
1854
- cacheName || url,
1855
- createPromise,
1856
- cacheOptions,
1857
- false
1858
- );
1859
- }
1860
- return createPromise();
1861
- });
1862
- }
1863
2553
  // -------------------------------------------------------------------------
1864
2554
  // Resource Methods
1865
2555
  // -------------------------------------------------------------------------
@@ -1935,78 +2625,7 @@ var Geocoder = (function (exports) {
1935
2625
  deleteResource(resource) {
1936
2626
  return this.resources.delete(resource);
1937
2627
  }
1938
- /**
1939
- * @internal
1940
- */
1941
- _loadData(url, options) {
1942
- options.responseType = options.responseType || "json";
1943
- return new Promise((resolve, reject) => {
1944
- var _a;
1945
- if (this.user) {
1946
- options = options || {};
1947
- options.headers = __spreadValues$3(__spreadValues$3({}, this.getAuthorizationHeaders()), options.headers);
1948
- }
1949
- if (this.requestTransform) {
1950
- const [transUrl, transOptions] = this.requestTransform(url, options);
1951
- url = transUrl;
1952
- options = transOptions;
1953
- }
1954
- let runOnAbort = void 0;
1955
- loadData(url, resolve, options, reject, (handler) => {
1956
- runOnAbort = handler;
1957
- });
1958
- (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
1959
- if (runOnAbort !== void 0) {
1960
- runOnAbort();
1961
- }
1962
- reject(new AbortError());
1963
- });
1964
- }).catch((httpError) => {
1965
- if (httpError.name !== "AbortError") {
1966
- {
1967
- console.warn("DEV WARN", httpError);
1968
- }
1969
- const er = this._handleHttpError(httpError);
1970
- if (er) {
1971
- throw er;
1972
- }
1973
- }
1974
- throw httpError;
1975
- });
1976
- }
1977
- _login(credentials, options) {
1978
- return __async$2(this, null, function* () {
1979
- try {
1980
- const data = yield this.getUserInfo(credentials, options);
1981
- this.user = data;
1982
- this.emitter.emit("login", data);
1983
- return data;
1984
- } catch (er) {
1985
- this.emitter.emit("login:error", er);
1986
- throw er;
1987
- }
1988
- });
1989
- }
1990
- _cleanActiveRequest(requestId) {
1991
- delete this.activeRequests[requestId];
1992
- }
1993
- _handleHttpError(er) {
1994
- if (er) {
1995
- if (er instanceof NgwError) {
1996
- if (er.exception === "nextgisweb.resource.exception.ResourceNotFound") {
1997
- throw new ResourceNotFoundError(er);
1998
- } else if (er.exception === "nextgisweb.core.exception.InsufficientPermissions") {
1999
- throw new InsufficientPermissionsError(er);
2000
- }
2001
- }
2002
- }
2003
- return er;
2004
- }
2005
2628
  }
2006
- __publicField$2(NgwConnector, "errors", {
2007
- NgwError,
2008
- ResourceNotFoundError
2009
- });
2010
2629
 
2011
2630
  function reEscape(s) {
2012
2631
  return s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
@@ -2078,6 +2697,10 @@ var Geocoder = (function (exports) {
2078
2697
  return logic === "any" ? filters_.some(filterFunction) : filters_.every(filterFunction);
2079
2698
  }
2080
2699
 
2700
+ const config = {
2701
+ defaultRequestLimit: 7e3
2702
+ };
2703
+
2081
2704
  var __defProp$3 = Object.defineProperty;
2082
2705
  var __defProps$1 = Object.defineProperties;
2083
2706
  var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
@@ -2123,15 +2746,12 @@ var Geocoder = (function (exports) {
2123
2746
  };
2124
2747
  function updateItemRequestParam(params, options) {
2125
2748
  const { extensions, geom, fields, srs, ilike, like } = options;
2126
- const extensionsStr = extensions ? extensions.join(",") : "";
2127
- if (extensionsStr !== "*") {
2128
- params.extensions = extensionsStr;
2129
- }
2130
- if (fields !== void 0) {
2131
- params.fields = Array.isArray(fields) ? fields.join(",") : "";
2749
+ params.extensions = extensions ? extensions : [];
2750
+ if (fields) {
2751
+ params.fields = fields;
2132
2752
  }
2133
2753
  if (geom !== void 0) {
2134
- params.geom = geom ? "yes" : "no";
2754
+ params.geom = geom;
2135
2755
  if (!geom) {
2136
2756
  delete params.srs;
2137
2757
  delete params.geom_format;
@@ -2146,6 +2766,15 @@ var Geocoder = (function (exports) {
2146
2766
  params.srs = srs;
2147
2767
  }
2148
2768
  }
2769
+ function paramListToQuery(paramList) {
2770
+ return paramList.reduce(
2771
+ (acc, [key, value]) => {
2772
+ acc[key] = value;
2773
+ return acc;
2774
+ },
2775
+ {}
2776
+ );
2777
+ }
2149
2778
  function createFeatureFieldFilterQueries(opt) {
2150
2779
  return __async$1(this, null, function* () {
2151
2780
  const queries = getQueries(opt);
@@ -2246,6 +2875,7 @@ var Geocoder = (function (exports) {
2246
2875
  const params = __spreadValues$2({}, FEATURE_REQUEST_PARAMS);
2247
2876
  const {
2248
2877
  limit,
2878
+ query,
2249
2879
  cache,
2250
2880
  signal,
2251
2881
  offset,
@@ -2256,12 +2886,10 @@ var Geocoder = (function (exports) {
2256
2886
  intersects,
2257
2887
  resourceId
2258
2888
  } = options;
2259
- if (limit) {
2260
- if (limit !== Number.POSITIVE_INFINITY) {
2261
- params.limit = limit;
2262
- }
2889
+ if (limit && limit !== Number.POSITIVE_INFINITY) {
2890
+ params.limit = limit;
2263
2891
  } else {
2264
- params.limit = 7e3;
2892
+ params.limit = config.defaultRequestLimit;
2265
2893
  }
2266
2894
  if (offset) {
2267
2895
  params.offset = offset;
@@ -2280,16 +2908,9 @@ var Geocoder = (function (exports) {
2280
2908
  params.intersects = intersects;
2281
2909
  }
2282
2910
  if (paramList) {
2283
- params.paramList = paramList;
2284
- }
2285
- const reqParams = __spreadValues$2({
2286
- id: resourceId
2287
- }, params);
2288
- return connector.get(
2289
- "feature_layer.feature.collection",
2290
- { cache, signal },
2291
- reqParams
2292
- );
2911
+ Object.assign(params, paramListToQuery(paramList));
2912
+ }
2913
+ return connector.route("feature_layer.feature.collection", { id: Number(resourceId) }).get({ query: __spreadValues$2(__spreadValues$2({}, params), query), cache, signal });
2293
2914
  }
2294
2915
 
2295
2916
  function prepareNgwFieldsToPropertiesFilter(fields) {
@@ -2442,7 +3063,7 @@ var Geocoder = (function (exports) {
2442
3063
  "The `searchUrl` of `connectorOptions.baseUrl` are required"
2443
3064
  );
2444
3065
  }
2445
- this.connector = options.connector || new NgwConnector(__spreadValues({
3066
+ this.connector = options.connector || new NgwConnectorExtended(__spreadValues({
2446
3067
  baseUrl: this.searchUrl
2447
3068
  }, options.connectorOptions));
2448
3069
  this.searchResources = options.searchResources;
@@ -2491,7 +3112,7 @@ var Geocoder = (function (exports) {
2491
3112
  yield item;
2492
3113
  }
2493
3114
  } catch (er) {
2494
- if (er && "name" in er && er.name !== "CancelError") {
3115
+ if (er && "name" in er && er.name !== "AbortError") {
2495
3116
  console.warn(er);
2496
3117
  }
2497
3118
  }
@@ -2500,14 +3121,10 @@ var Geocoder = (function (exports) {
2500
3121
  }
2501
3122
  result(item) {
2502
3123
  const signal = this._makeSignal();
2503
- const req = this.connector.get(
2504
- "feature_layer.feature.item_extent",
2505
- { signal },
2506
- {
2507
- id: item.resourceId,
2508
- fid: item.featureId
2509
- }
2510
- ).then((x) => {
3124
+ const req = this.connector.route("feature_layer.feature.item_extent", {
3125
+ id: item.resourceId,
3126
+ fid: item.featureId
3127
+ }).get({ signal }).then((x) => {
2511
3128
  const e = x.extent;
2512
3129
  return {
2513
3130
  text: item.text,
@@ -2594,56 +3211,69 @@ var Geocoder = (function (exports) {
2594
3211
  };
2595
3212
  class NominatimProvider extends BaseProvider {
2596
3213
  constructor(options) {
2597
- super(options);
3214
+ super();
3215
+ this.options = options;
2598
3216
  __publicField(this, "searchUrl", "https://nominatim.openstreetmap.org");
2599
- __publicField(this, "_abort", []);
3217
+ __publicField(this, "_abortControllers", []);
2600
3218
  if (options && options.searchUrl) {
2601
3219
  this.searchUrl = options.searchUrl;
2602
3220
  }
2603
3221
  }
2604
3222
  abort() {
2605
- this._abort.forEach((x) => x());
2606
- this._abort = [];
3223
+ this._abortControllers.forEach((controller) => {
3224
+ controller.abort();
3225
+ });
3226
+ this._abortControllers = [];
2607
3227
  }
2608
3228
  search(val) {
2609
3229
  return __asyncGenerator(this, null, function* () {
2610
- const url = fixUrlStr(
2611
- // `${this.baseUrl}/search?format=geojson&polygon_geojson=1${window.locale === 'ru' ? '&accept-language=ru-RU,en-US' : ''}&q=${val}`
2612
- `${this.searchUrl}/search?format=geojson&polygon_geojson=1&q=${val}`
2613
- );
2614
- const request = new Promise((resolve, reject) => {
2615
- const xhr = new XMLHttpRequest();
2616
- xhr.open("GET", url, true);
2617
- xhr.onload = () => {
2618
- try {
2619
- const geojson = JSON.parse(xhr.responseText);
2620
- const features = geojson.features.map((x) => {
2621
- return {
2622
- geom: x,
2623
- extent: x.bbox,
2624
- text: x.properties && x.properties.display_name,
2625
- query: val
2626
- };
2627
- });
2628
- resolve(features);
2629
- } catch (er) {
2630
- reject(er);
2631
- }
2632
- };
2633
- xhr.onerror = (er) => {
2634
- reject(er);
2635
- };
2636
- this._abort.push(xhr.abort);
2637
- xhr.send();
2638
- }).catch((er) => {
2639
- if (er.name === "CancelError") ;
2640
- throw er;
3230
+ var _a, _b, _c, _d, _e, _f, _g;
3231
+ const params = new URLSearchParams({
3232
+ format: "geojson",
3233
+ polygon_geojson: "1",
3234
+ q: val,
3235
+ limit: ((_b = (_a = this.options) == null ? void 0 : _a.limit) == null ? void 0 : _b.toString()) || "10"
2641
3236
  });
2642
- const items = yield new __await(request);
2643
- if (items) {
2644
- for (const i of items) {
2645
- i.result = () => this.result(i);
2646
- yield i;
3237
+ if ((_c = this.options) == null ? void 0 : _c.countrycodes) {
3238
+ params.append("countrycodes", this.options.countrycodes);
3239
+ }
3240
+ if ((_d = this.options) == null ? void 0 : _d.addressdetails) {
3241
+ params.append("addressdetails", "1");
3242
+ }
3243
+ if ((_e = this.options) == null ? void 0 : _e.language) {
3244
+ params.append("accept-language", this.options.language);
3245
+ }
3246
+ if ((_f = this.options) == null ? void 0 : _f.bounded) {
3247
+ params.append("bounded", "1");
3248
+ }
3249
+ if ((_g = this.options) == null ? void 0 : _g.viewbox) {
3250
+ const [minLon, minLat, maxLon, maxLat] = this.options.viewbox;
3251
+ params.append("viewbox", `${minLon},${minLat},${maxLon},${maxLat}`);
3252
+ }
3253
+ const url = fixUrlStr(`${this.searchUrl}/search?${params.toString()}`);
3254
+ const controller = new AbortController();
3255
+ this._abortControllers.push(controller);
3256
+ try {
3257
+ const response = yield new __await(fetch(url, { signal: controller.signal }));
3258
+ if (!response.ok) {
3259
+ throw new Error(`Network response was not ok: ${response.statusText}`);
3260
+ }
3261
+ const geojson = yield new __await(response.json());
3262
+ const features = geojson.features.map((x) => {
3263
+ return {
3264
+ geom: x,
3265
+ extent: x.bbox,
3266
+ text: x.properties && x.properties.display_name,
3267
+ query: val
3268
+ };
3269
+ });
3270
+ for (const item of features) {
3271
+ item.result = () => this.result(item);
3272
+ yield item;
3273
+ }
3274
+ } catch (error) {
3275
+ if (error.name === "AbortError") ; else {
3276
+ throw error;
2647
3277
  }
2648
3278
  }
2649
3279
  });
@@ -2657,41 +3287,41 @@ var Geocoder = (function (exports) {
2657
3287
  }
2658
3288
  reverse(coordinates) {
2659
3289
  return __asyncGenerator(this, null, function* () {
3290
+ var _a, _b;
2660
3291
  const [lng, lat] = coordinates;
2661
- const url = fixUrlStr(
2662
- `${this.searchUrl}/reverse?format=geojson&lat=${lat}&lon=${lng}`
2663
- );
2664
- const request = new Promise((resolve, reject) => {
2665
- const xhr = new XMLHttpRequest();
2666
- xhr.open("GET", url, true);
2667
- xhr.onload = () => {
2668
- try {
2669
- const geojson = JSON.parse(xhr.responseText);
2670
- const feature = geojson.features[0];
2671
- const result = {
2672
- geom: feature,
2673
- extent: feature.bbox,
2674
- text: feature.properties && feature.properties.display_name,
2675
- query: `${lat}, ${lng}`
2676
- };
2677
- resolve(result);
2678
- } catch (er) {
2679
- reject(er);
2680
- }
2681
- };
2682
- xhr.onerror = (er) => {
2683
- reject(er);
2684
- };
2685
- this._abort.push(xhr.abort);
2686
- xhr.send();
2687
- }).catch((er) => {
2688
- if (er.name === "CancelError") ;
2689
- throw er;
3292
+ const params = new URLSearchParams({
3293
+ format: "geojson",
3294
+ lat: lat.toString(),
3295
+ lon: lng.toString()
2690
3296
  });
2691
- const item = yield new __await(request);
2692
- if (item) {
3297
+ if ((_a = this.options) == null ? void 0 : _a.addressdetails) {
3298
+ params.append("addressdetails", "1");
3299
+ }
3300
+ if ((_b = this.options) == null ? void 0 : _b.language) {
3301
+ params.append("accept-language", this.options.language);
3302
+ }
3303
+ const url = fixUrlStr(`${this.searchUrl}/reverse?${params.toString()}`);
3304
+ const controller = new AbortController();
3305
+ this._abortControllers.push(controller);
3306
+ try {
3307
+ const response = yield new __await(fetch(url, { signal: controller.signal }));
3308
+ if (!response.ok) {
3309
+ throw new Error(`Network response was not ok: ${response.statusText}`);
3310
+ }
3311
+ const geojson = yield new __await(response.json());
3312
+ const feature = geojson.features[0];
3313
+ const item = {
3314
+ geom: feature,
3315
+ extent: feature.bbox,
3316
+ text: feature.properties && feature.properties.display_name,
3317
+ query: `${lat}, ${lng}`
3318
+ };
2693
3319
  item.result = () => this.result(item);
2694
3320
  yield item;
3321
+ } catch (error) {
3322
+ if (error.name === "AbortError") ; else {
3323
+ throw error;
3324
+ }
2695
3325
  }
2696
3326
  });
2697
3327
  }