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