@nextgis/ngw-connector 1.19.0 → 2.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,76 +1,39 @@
1
- /** Bundle of @nextgis/ngw-connector; version: 1.19.0; author: NextGIS */
2
- var events = {exports: {}};
3
-
4
- var R = typeof Reflect === 'object' ? Reflect : null;
5
- var ReflectApply = R && typeof R.apply === 'function'
6
- ? R.apply
7
- : function ReflectApply(target, receiver, args) {
8
- return Function.prototype.apply.call(target, receiver, args);
9
- };
10
-
11
- var ReflectOwnKeys;
12
- if (R && typeof R.ownKeys === 'function') {
13
- ReflectOwnKeys = R.ownKeys;
14
- } else if (Object.getOwnPropertySymbols) {
15
- ReflectOwnKeys = function ReflectOwnKeys(target) {
16
- return Object.getOwnPropertyNames(target)
17
- .concat(Object.getOwnPropertySymbols(target));
18
- };
19
- } else {
20
- ReflectOwnKeys = function ReflectOwnKeys(target) {
21
- return Object.getOwnPropertyNames(target);
22
- };
23
- }
24
-
25
- function ProcessEmitWarning(warning) {
26
- if (console && console.warn) console.warn(warning);
27
- }
1
+ /** Bundle of @nextgis/ngw-connector; version: 2.0.0-alpha.0; author: NextGIS */
2
+ var domain;
28
3
 
29
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
30
- return value !== value;
31
- };
4
+ // This constructor is used to store event handlers. Instantiating this is
5
+ // faster than explicitly calling `Object.create(null)` to get a "clean" empty
6
+ // object (tested with v8 v4.9).
7
+ function EventHandlers() {}
8
+ EventHandlers.prototype = Object.create(null);
32
9
 
33
10
  function EventEmitter() {
34
11
  EventEmitter.init.call(this);
35
12
  }
36
- events.exports = EventEmitter;
37
- events.exports.once = once;
38
13
 
39
- // Backwards-compat with node 0.10.x
14
+ // nodejs oddity
15
+ // require('events') === require('events').EventEmitter
40
16
  EventEmitter.EventEmitter = EventEmitter;
41
17
 
18
+ EventEmitter.usingDomains = false;
19
+
20
+ EventEmitter.prototype.domain = undefined;
42
21
  EventEmitter.prototype._events = undefined;
43
- EventEmitter.prototype._eventsCount = 0;
44
22
  EventEmitter.prototype._maxListeners = undefined;
45
23
 
46
24
  // By default EventEmitters will print a warning if more than 10 listeners are
47
25
  // added to it. This is a useful default which helps finding memory leaks.
48
- var defaultMaxListeners = 10;
49
-
50
- function checkListener(listener) {
51
- if (typeof listener !== 'function') {
52
- throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
53
- }
54
- }
55
-
56
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
57
- enumerable: true,
58
- get: function() {
59
- return defaultMaxListeners;
60
- },
61
- set: function(arg) {
62
- if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
63
- throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
64
- }
65
- defaultMaxListeners = arg;
66
- }
67
- });
26
+ EventEmitter.defaultMaxListeners = 10;
68
27
 
69
28
  EventEmitter.init = function() {
29
+ this.domain = null;
30
+ if (EventEmitter.usingDomains) {
31
+ // if there is an active domain, then attach to it.
32
+ if (domain.active ) ;
33
+ }
70
34
 
71
- if (this._events === undefined ||
72
- this._events === Object.getPrototypeOf(this)._events) {
73
- this._events = Object.create(null);
35
+ if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
36
+ this._events = new EventHandlers();
74
37
  this._eventsCount = 0;
75
38
  }
76
39
 
@@ -80,62 +43,139 @@ EventEmitter.init = function() {
80
43
  // Obviously not all Emitters should be limited to 10. This function allows
81
44
  // that to be increased. Set to zero for unlimited.
82
45
  EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
83
- if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
84
- throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
85
- }
46
+ if (typeof n !== 'number' || n < 0 || isNaN(n))
47
+ throw new TypeError('"n" argument must be a positive number');
86
48
  this._maxListeners = n;
87
49
  return this;
88
50
  };
89
51
 
90
- function _getMaxListeners(that) {
52
+ function $getMaxListeners(that) {
91
53
  if (that._maxListeners === undefined)
92
54
  return EventEmitter.defaultMaxListeners;
93
55
  return that._maxListeners;
94
56
  }
95
57
 
96
58
  EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
97
- return _getMaxListeners(this);
59
+ return $getMaxListeners(this);
98
60
  };
99
61
 
62
+ // These standalone emit* functions are used to optimize calling of event
63
+ // handlers for fast cases because emit() itself often has a variable number of
64
+ // arguments and can be deoptimized because of that. These functions always have
65
+ // the same number of arguments and thus do not get deoptimized, so the code
66
+ // inside them can execute faster.
67
+ function emitNone(handler, isFn, self) {
68
+ if (isFn)
69
+ handler.call(self);
70
+ else {
71
+ var len = handler.length;
72
+ var listeners = arrayClone(handler, len);
73
+ for (var i = 0; i < len; ++i)
74
+ listeners[i].call(self);
75
+ }
76
+ }
77
+ function emitOne(handler, isFn, self, arg1) {
78
+ if (isFn)
79
+ handler.call(self, arg1);
80
+ else {
81
+ var len = handler.length;
82
+ var listeners = arrayClone(handler, len);
83
+ for (var i = 0; i < len; ++i)
84
+ listeners[i].call(self, arg1);
85
+ }
86
+ }
87
+ function emitTwo(handler, isFn, self, arg1, arg2) {
88
+ if (isFn)
89
+ handler.call(self, arg1, arg2);
90
+ else {
91
+ var len = handler.length;
92
+ var listeners = arrayClone(handler, len);
93
+ for (var i = 0; i < len; ++i)
94
+ listeners[i].call(self, arg1, arg2);
95
+ }
96
+ }
97
+ function emitThree(handler, isFn, self, arg1, arg2, arg3) {
98
+ if (isFn)
99
+ handler.call(self, arg1, arg2, arg3);
100
+ else {
101
+ var len = handler.length;
102
+ var listeners = arrayClone(handler, len);
103
+ for (var i = 0; i < len; ++i)
104
+ listeners[i].call(self, arg1, arg2, arg3);
105
+ }
106
+ }
107
+
108
+ function emitMany(handler, isFn, self, args) {
109
+ if (isFn)
110
+ handler.apply(self, args);
111
+ else {
112
+ var len = handler.length;
113
+ var listeners = arrayClone(handler, len);
114
+ for (var i = 0; i < len; ++i)
115
+ listeners[i].apply(self, args);
116
+ }
117
+ }
118
+
100
119
  EventEmitter.prototype.emit = function emit(type) {
101
- var args = [];
102
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
120
+ var er, handler, len, args, i, events, domain;
103
121
  var doError = (type === 'error');
104
122
 
105
- var events = this._events;
106
- if (events !== undefined)
107
- doError = (doError && events.error === undefined);
123
+ events = this._events;
124
+ if (events)
125
+ doError = (doError && events.error == null);
108
126
  else if (!doError)
109
127
  return false;
110
128
 
129
+ domain = this.domain;
130
+
111
131
  // If there is no 'error' event listener then throw.
112
132
  if (doError) {
113
- var er;
114
- if (args.length > 0)
115
- er = args[0];
116
- if (er instanceof Error) {
117
- // Note: The comments on the `throw` lines are intentional, they show
118
- // up in Node's output if this results in an unhandled exception.
133
+ er = arguments[1];
134
+ if (domain) {
135
+ if (!er)
136
+ er = new Error('Uncaught, unspecified "error" event');
137
+ er.domainEmitter = this;
138
+ er.domain = domain;
139
+ er.domainThrown = false;
140
+ domain.emit('error', er);
141
+ } else if (er instanceof Error) {
119
142
  throw er; // Unhandled 'error' event
143
+ } else {
144
+ // At least give some kind of context to the user
145
+ var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
146
+ err.context = er;
147
+ throw err;
120
148
  }
121
- // At least give some kind of context to the user
122
- var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
123
- err.context = er;
124
- throw err; // Unhandled 'error' event
149
+ return false;
125
150
  }
126
151
 
127
- var handler = events[type];
152
+ handler = events[type];
128
153
 
129
- if (handler === undefined)
154
+ if (!handler)
130
155
  return false;
131
156
 
132
- if (typeof handler === 'function') {
133
- ReflectApply(handler, this, args);
134
- } else {
135
- var len = handler.length;
136
- var listeners = arrayClone(handler, len);
137
- for (var i = 0; i < len; ++i)
138
- ReflectApply(listeners[i], this, args);
157
+ var isFn = typeof handler === 'function';
158
+ len = arguments.length;
159
+ switch (len) {
160
+ // fast cases
161
+ case 1:
162
+ emitNone(handler, isFn, this);
163
+ break;
164
+ case 2:
165
+ emitOne(handler, isFn, this, arguments[1]);
166
+ break;
167
+ case 3:
168
+ emitTwo(handler, isFn, this, arguments[1], arguments[2]);
169
+ break;
170
+ case 4:
171
+ emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
172
+ break;
173
+ // slower
174
+ default:
175
+ args = new Array(len - 1);
176
+ for (i = 1; i < len; i++)
177
+ args[i - 1] = arguments[i];
178
+ emitMany(handler, isFn, this, args);
139
179
  }
140
180
 
141
181
  return true;
@@ -146,16 +186,17 @@ function _addListener(target, type, listener, prepend) {
146
186
  var events;
147
187
  var existing;
148
188
 
149
- checkListener(listener);
189
+ if (typeof listener !== 'function')
190
+ throw new TypeError('"listener" argument must be a function');
150
191
 
151
192
  events = target._events;
152
- if (events === undefined) {
153
- events = target._events = Object.create(null);
193
+ if (!events) {
194
+ events = target._events = new EventHandlers();
154
195
  target._eventsCount = 0;
155
196
  } else {
156
197
  // To avoid recursion in the case that type === "newListener"! Before
157
198
  // adding it to the listeners, first emit "newListener".
158
- if (events.newListener !== undefined) {
199
+ if (events.newListener) {
159
200
  target.emit('newListener', type,
160
201
  listener.listener ? listener.listener : listener);
161
202
 
@@ -166,43 +207,46 @@ function _addListener(target, type, listener, prepend) {
166
207
  existing = events[type];
167
208
  }
168
209
 
169
- if (existing === undefined) {
210
+ if (!existing) {
170
211
  // Optimize the case of one listener. Don't need the extra array object.
171
212
  existing = events[type] = listener;
172
213
  ++target._eventsCount;
173
214
  } else {
174
215
  if (typeof existing === 'function') {
175
216
  // Adding the second element, need to change to array.
176
- existing = events[type] =
177
- prepend ? [listener, existing] : [existing, listener];
178
- // If we've already got an array, just append.
179
- } else if (prepend) {
180
- existing.unshift(listener);
217
+ existing = events[type] = prepend ? [listener, existing] :
218
+ [existing, listener];
181
219
  } else {
182
- existing.push(listener);
220
+ // If we've already got an array, just append.
221
+ if (prepend) {
222
+ existing.unshift(listener);
223
+ } else {
224
+ existing.push(listener);
225
+ }
183
226
  }
184
227
 
185
228
  // Check for listener leak
186
- m = _getMaxListeners(target);
187
- if (m > 0 && existing.length > m && !existing.warned) {
188
- existing.warned = true;
189
- // No error code for this since it is a Warning
190
- // eslint-disable-next-line no-restricted-syntax
191
- var w = new Error('Possible EventEmitter memory leak detected. ' +
192
- existing.length + ' ' + String(type) + ' listeners ' +
193
- 'added. Use emitter.setMaxListeners() to ' +
194
- 'increase limit');
195
- w.name = 'MaxListenersExceededWarning';
196
- w.emitter = target;
197
- w.type = type;
198
- w.count = existing.length;
199
- ProcessEmitWarning(w);
229
+ if (!existing.warned) {
230
+ m = $getMaxListeners(target);
231
+ if (m && m > 0 && existing.length > m) {
232
+ existing.warned = true;
233
+ var w = new Error('Possible EventEmitter memory leak detected. ' +
234
+ existing.length + ' ' + type + ' listeners added. ' +
235
+ 'Use emitter.setMaxListeners() to increase limit');
236
+ w.name = 'MaxListenersExceededWarning';
237
+ w.emitter = target;
238
+ w.type = type;
239
+ w.count = existing.length;
240
+ emitWarning(w);
241
+ }
200
242
  }
201
243
  }
202
244
 
203
245
  return target;
204
246
  }
205
-
247
+ function emitWarning(e) {
248
+ typeof console.warn === 'function' ? console.warn(e) : console.log(e);
249
+ }
206
250
  EventEmitter.prototype.addListener = function addListener(type, listener) {
207
251
  return _addListener(this, type, listener, false);
208
252
  };
@@ -214,55 +258,53 @@ EventEmitter.prototype.prependListener =
214
258
  return _addListener(this, type, listener, true);
215
259
  };
216
260
 
217
- function onceWrapper() {
218
- if (!this.fired) {
219
- this.target.removeListener(this.type, this.wrapFn);
220
- this.fired = true;
221
- if (arguments.length === 0)
222
- return this.listener.call(this.target);
223
- return this.listener.apply(this.target, arguments);
224
- }
225
- }
226
-
227
261
  function _onceWrap(target, type, listener) {
228
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
229
- var wrapped = onceWrapper.bind(state);
230
- wrapped.listener = listener;
231
- state.wrapFn = wrapped;
232
- return wrapped;
262
+ var fired = false;
263
+ function g() {
264
+ target.removeListener(type, g);
265
+ if (!fired) {
266
+ fired = true;
267
+ listener.apply(target, arguments);
268
+ }
269
+ }
270
+ g.listener = listener;
271
+ return g;
233
272
  }
234
273
 
235
274
  EventEmitter.prototype.once = function once(type, listener) {
236
- checkListener(listener);
275
+ if (typeof listener !== 'function')
276
+ throw new TypeError('"listener" argument must be a function');
237
277
  this.on(type, _onceWrap(this, type, listener));
238
278
  return this;
239
279
  };
240
280
 
241
281
  EventEmitter.prototype.prependOnceListener =
242
282
  function prependOnceListener(type, listener) {
243
- checkListener(listener);
283
+ if (typeof listener !== 'function')
284
+ throw new TypeError('"listener" argument must be a function');
244
285
  this.prependListener(type, _onceWrap(this, type, listener));
245
286
  return this;
246
287
  };
247
288
 
248
- // Emits a 'removeListener' event if and only if the listener was removed.
289
+ // emits a 'removeListener' event iff the listener was removed
249
290
  EventEmitter.prototype.removeListener =
250
291
  function removeListener(type, listener) {
251
292
  var list, events, position, i, originalListener;
252
293
 
253
- checkListener(listener);
294
+ if (typeof listener !== 'function')
295
+ throw new TypeError('"listener" argument must be a function');
254
296
 
255
297
  events = this._events;
256
- if (events === undefined)
298
+ if (!events)
257
299
  return this;
258
300
 
259
301
  list = events[type];
260
- if (list === undefined)
302
+ if (!list)
261
303
  return this;
262
304
 
263
- if (list === listener || list.listener === listener) {
305
+ if (list === listener || (list.listener && list.listener === listener)) {
264
306
  if (--this._eventsCount === 0)
265
- this._events = Object.create(null);
307
+ this._events = new EventHandlers();
266
308
  else {
267
309
  delete events[type];
268
310
  if (events.removeListener)
@@ -271,8 +313,9 @@ EventEmitter.prototype.removeListener =
271
313
  } else if (typeof list !== 'function') {
272
314
  position = -1;
273
315
 
274
- for (i = list.length - 1; i >= 0; i--) {
275
- if (list[i] === listener || list[i].listener === listener) {
316
+ for (i = list.length; i-- > 0;) {
317
+ if (list[i] === listener ||
318
+ (list[i].listener && list[i].listener === listener)) {
276
319
  originalListener = list[i].listener;
277
320
  position = i;
278
321
  break;
@@ -282,40 +325,47 @@ EventEmitter.prototype.removeListener =
282
325
  if (position < 0)
283
326
  return this;
284
327
 
285
- if (position === 0)
286
- list.shift();
287
- else {
328
+ if (list.length === 1) {
329
+ list[0] = undefined;
330
+ if (--this._eventsCount === 0) {
331
+ this._events = new EventHandlers();
332
+ return this;
333
+ } else {
334
+ delete events[type];
335
+ }
336
+ } else {
288
337
  spliceOne(list, position);
289
338
  }
290
339
 
291
- if (list.length === 1)
292
- events[type] = list[0];
293
-
294
- if (events.removeListener !== undefined)
340
+ if (events.removeListener)
295
341
  this.emit('removeListener', type, originalListener || listener);
296
342
  }
297
343
 
298
344
  return this;
299
345
  };
300
-
301
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
346
+
347
+ // Alias for removeListener added in NodeJS 10.0
348
+ // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener
349
+ EventEmitter.prototype.off = function(type, listener){
350
+ return this.removeListener(type, listener);
351
+ };
302
352
 
303
353
  EventEmitter.prototype.removeAllListeners =
304
354
  function removeAllListeners(type) {
305
- var listeners, events, i;
355
+ var listeners, events;
306
356
 
307
357
  events = this._events;
308
- if (events === undefined)
358
+ if (!events)
309
359
  return this;
310
360
 
311
361
  // not listening for removeListener, no need to emit
312
- if (events.removeListener === undefined) {
362
+ if (!events.removeListener) {
313
363
  if (arguments.length === 0) {
314
- this._events = Object.create(null);
364
+ this._events = new EventHandlers();
315
365
  this._eventsCount = 0;
316
- } else if (events[type] !== undefined) {
366
+ } else if (events[type]) {
317
367
  if (--this._eventsCount === 0)
318
- this._events = Object.create(null);
368
+ this._events = new EventHandlers();
319
369
  else
320
370
  delete events[type];
321
371
  }
@@ -325,14 +375,13 @@ EventEmitter.prototype.removeAllListeners =
325
375
  // emit removeListener for all listeners on all events
326
376
  if (arguments.length === 0) {
327
377
  var keys = Object.keys(events);
328
- var key;
329
- for (i = 0; i < keys.length; ++i) {
378
+ for (var i = 0, key; i < keys.length; ++i) {
330
379
  key = keys[i];
331
380
  if (key === 'removeListener') continue;
332
381
  this.removeAllListeners(key);
333
382
  }
334
383
  this.removeAllListeners('removeListener');
335
- this._events = Object.create(null);
384
+ this._events = new EventHandlers();
336
385
  this._eventsCount = 0;
337
386
  return this;
338
387
  }
@@ -341,39 +390,34 @@ EventEmitter.prototype.removeAllListeners =
341
390
 
342
391
  if (typeof listeners === 'function') {
343
392
  this.removeListener(type, listeners);
344
- } else if (listeners !== undefined) {
393
+ } else if (listeners) {
345
394
  // LIFO order
346
- for (i = listeners.length - 1; i >= 0; i--) {
347
- this.removeListener(type, listeners[i]);
348
- }
395
+ do {
396
+ this.removeListener(type, listeners[listeners.length - 1]);
397
+ } while (listeners[0]);
349
398
  }
350
399
 
351
400
  return this;
352
401
  };
353
402
 
354
- function _listeners(target, type, unwrap) {
355
- var events = target._events;
356
-
357
- if (events === undefined)
358
- return [];
359
-
360
- var evlistener = events[type];
361
- if (evlistener === undefined)
362
- return [];
363
-
364
- if (typeof evlistener === 'function')
365
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
366
-
367
- return unwrap ?
368
- unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
369
- }
370
-
371
403
  EventEmitter.prototype.listeners = function listeners(type) {
372
- return _listeners(this, type, true);
373
- };
404
+ var evlistener;
405
+ var ret;
406
+ var events = this._events;
374
407
 
375
- EventEmitter.prototype.rawListeners = function rawListeners(type) {
376
- return _listeners(this, type, false);
408
+ if (!events)
409
+ ret = [];
410
+ else {
411
+ evlistener = events[type];
412
+ if (!evlistener)
413
+ ret = [];
414
+ else if (typeof evlistener === 'function')
415
+ ret = [evlistener.listener || evlistener];
416
+ else
417
+ ret = unwrapListeners(evlistener);
418
+ }
419
+
420
+ return ret;
377
421
  };
378
422
 
379
423
  EventEmitter.listenerCount = function(emitter, type) {
@@ -388,12 +432,12 @@ EventEmitter.prototype.listenerCount = listenerCount;
388
432
  function listenerCount(type) {
389
433
  var events = this._events;
390
434
 
391
- if (events !== undefined) {
435
+ if (events) {
392
436
  var evlistener = events[type];
393
437
 
394
438
  if (typeof evlistener === 'function') {
395
439
  return 1;
396
- } else if (evlistener !== undefined) {
440
+ } else if (evlistener) {
397
441
  return evlistener.length;
398
442
  }
399
443
  }
@@ -402,22 +446,23 @@ function listenerCount(type) {
402
446
  }
403
447
 
404
448
  EventEmitter.prototype.eventNames = function eventNames() {
405
- return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
449
+ return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
406
450
  };
407
451
 
408
- function arrayClone(arr, n) {
409
- var copy = new Array(n);
410
- for (var i = 0; i < n; ++i)
411
- copy[i] = arr[i];
412
- return copy;
413
- }
414
-
452
+ // About 1.5x faster than the two-arg version of Array#splice().
415
453
  function spliceOne(list, index) {
416
- for (; index + 1 < list.length; index++)
417
- list[index] = list[index + 1];
454
+ for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
455
+ list[i] = list[k];
418
456
  list.pop();
419
457
  }
420
458
 
459
+ function arrayClone(arr, i) {
460
+ var copy = new Array(i);
461
+ while (i--)
462
+ copy[i] = arr[i];
463
+ return copy;
464
+ }
465
+
421
466
  function unwrapListeners(arr) {
422
467
  var ret = new Array(arr.length);
423
468
  for (var i = 0; i < ret.length; ++i) {
@@ -426,1656 +471,1536 @@ function unwrapListeners(arr) {
426
471
  return ret;
427
472
  }
428
473
 
429
- function once(emitter, name) {
430
- return new Promise(function (resolve, reject) {
431
- function errorListener(err) {
432
- emitter.removeListener(name, resolver);
433
- reject(err);
434
- }
435
-
436
- function resolver() {
437
- if (typeof emitter.removeListener === 'function') {
438
- emitter.removeListener('error', errorListener);
439
- }
440
- resolve([].slice.call(arguments));
441
- }
442
- eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
443
- if (name !== 'error') {
444
- addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
445
- }
446
- });
447
- }
448
-
449
- function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
450
- if (typeof emitter.on === 'function') {
451
- eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
452
- }
453
- }
454
-
455
- function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
456
- if (typeof emitter.on === 'function') {
457
- if (flags.once) {
458
- emitter.once(name, listener);
459
- } else {
460
- emitter.on(name, listener);
461
- }
462
- } else if (typeof emitter.addEventListener === 'function') {
463
- // EventTarget does not have `error` event semantics like Node
464
- // EventEmitters, we do not listen for `error` events here.
465
- emitter.addEventListener(name, function wrapListener(arg) {
466
- // IE does not have builtin `{ once: true }` support so we
467
- // have to do it manually.
468
- if (flags.once) {
469
- emitter.removeEventListener(name, wrapListener);
470
- }
471
- listener(arg);
472
- });
473
- } else {
474
- throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
475
- }
476
- }
477
-
478
- /**
479
- * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
480
- *
481
- * @param val - The object.
482
- * @returns Returns true if the object is defined, returns false otherwise.
483
- *
484
- * @example
485
- * ```javascript
486
- * if (defined(positions)) {
487
- * doSomething();
488
- * } else {
489
- * doSomethingElse();
490
- * }
491
- * ```
492
- */
493
474
  function defined(val) {
494
- return val !== undefined && val !== null;
475
+ return val !== void 0 && val !== null;
495
476
  }
496
- /**
497
- * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
498
- *
499
- * @param val - The object.
500
- * @returns Returns true if the object is defined and not empty string, returns false otherwise.
501
- *
502
- * @example
503
- * ```javascript
504
- * full('foo') // true
505
- * full('') // false
506
- * full(undefined) // false
507
- * full(0) // true
508
- * ```
509
- */
510
477
  function full(val) {
511
- return typeof val === 'string' ? !!val : defined(val);
478
+ return typeof val === "string" ? !!val : defined(val);
512
479
  }
513
480
 
514
481
  function isEqual(a, b, o, p) {
515
- if (a instanceof Array) {
516
- if (!(b instanceof Array))
517
- return false;
518
- //if (compareObjects(oVal, pVal === false) return false
519
- //would work, too, and perhaps is a better fit, still, this is easy, too
520
- return b.sort().join('') === a.sort().join('');
521
- }
522
- else if (a instanceof Date) {
523
- if (!(b instanceof Date))
524
- return false;
525
- return '' + a === '' + b;
526
- }
527
- else if (a instanceof Function) {
528
- if (!(b instanceof Function))
529
- return false;
530
- //ignore functions, or check them regardless?
531
- }
532
- else if (a instanceof Object) {
533
- if (!(b instanceof Object))
534
- return false;
535
- if (a === o) {
536
- return b === p;
537
- }
538
- else {
539
- return objectDeepEqual(a, b);
540
- }
482
+ if (a instanceof Array) {
483
+ if (!(b instanceof Array))
484
+ return false;
485
+ return b.sort().join("") === a.sort().join("");
486
+ } else if (a instanceof Date) {
487
+ if (!(b instanceof Date))
488
+ return false;
489
+ return "" + a === "" + b;
490
+ } else if (a instanceof Function) {
491
+ if (!(b instanceof Function))
492
+ return false;
493
+ } else if (a instanceof Object) {
494
+ if (!(b instanceof Object))
495
+ return false;
496
+ if (a === o) {
497
+ return b === p;
498
+ } else {
499
+ return objectDeepEqual(a, b);
541
500
  }
542
- return a === b;
501
+ }
502
+ return a === b;
543
503
  }
544
- // based on https://stackoverflow.com/a/13143059
545
504
  function objectDeepEqual(o, p) {
546
- const keysO = Object.keys(o).sort();
547
- const keysP = Object.keys(p).sort();
548
- if (keysO.length !== keysP.length)
549
- return false;
550
- if (keysO.join('') !== keysP.join(''))
551
- return false;
552
- for (let i = 0; i < keysO.length; i++) {
553
- const oVal = o[keysO[i]];
554
- const pVal = p[keysP[i]];
555
- if (!isEqual(oVal, pVal, o, p)) {
556
- return false;
557
- }
505
+ const keysO = Object.keys(o).sort();
506
+ const keysP = Object.keys(p).sort();
507
+ if (keysO.length !== keysP.length)
508
+ return false;
509
+ if (keysO.join("") !== keysP.join(""))
510
+ return false;
511
+ for (let i = 0; i < keysO.length; i++) {
512
+ const oVal = o[keysO[i]];
513
+ const pVal = p[keysP[i]];
514
+ if (!isEqual(oVal, pVal, o, p)) {
515
+ return false;
558
516
  }
559
- return true;
517
+ }
518
+ return true;
560
519
  }
561
520
 
562
521
  function objectRemoveEmpty(obj) {
563
- const newObj = {};
564
- Object.keys(obj).forEach((key) => {
565
- if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
566
- newObj[key] = objectRemoveEmpty(obj[key]);
567
- }
568
- else if (obj[key] !== undefined) {
569
- newObj[key] = obj[key];
570
- }
571
- });
572
- return newObj;
522
+ const newObj = {};
523
+ Object.keys(obj).forEach((key) => {
524
+ if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
525
+ newObj[key] = objectRemoveEmpty(obj[key]);
526
+ } else if (obj[key] !== void 0) {
527
+ newObj[key] = obj[key];
528
+ }
529
+ });
530
+ return newObj;
573
531
  }
574
532
 
575
533
  function fixUrlStr(url) {
576
- // remove double slash
577
- return url.replace(/([^:]\/)\/+/g, '$1');
534
+ return url.replace(/([^:]\/)\/+/g, "$1");
578
535
  }
579
536
 
580
- /**
581
- * @example
582
- * ```javascript
583
- * const cache1 = new Cache();
584
- * cache1.add('foo', 'value');
585
- *
586
- * const cache2 = new Cache();
587
- * cache2.match('foo'); // value
588
- *
589
- * const cache3 = new Cache({ namespace: 'foo' });
590
- * cache3.match('foo'); // undefined
591
- * ```
592
- *
593
- * @example
594
- * ```javascript
595
- * let COUNTER = 0;
596
- * const createPromise = () => new Promise((res) => {
597
- * COUNTER++
598
- * setTimeout(() => res('Ok'), 300)
599
- * });
600
- *
601
- * const cache = new Cache();
602
- * for (let i = 0; i < 10; i++) {
603
- * cache.add('foo', createPromise).then((data) => {
604
- * console.log(data); // 'Ok'
605
- * });
606
- * }
607
- * console.log(COUNTER); // 1
608
- * ```
609
- */
610
- class Cache$1 {
611
- constructor(options = {}) {
612
- var _a;
613
- this.cache = [];
614
- const namespace = (_a = options.namespace) !== null && _a !== void 0 ? _a : 'default';
615
- if (Cache$1.instance[namespace]) {
616
- return Cache$1.instance[namespace];
617
- }
618
- Cache$1.instance[namespace] = this;
619
- return this;
620
- }
621
- clean() {
622
- this.cache.length = 0;
623
- }
624
- all() {
625
- return this.cache;
626
- }
627
- /**
628
- * Caching only a non-empty value.
629
- *
630
- * Useful for get or create strategy
631
- * @example
632
- * ```javascript
633
- * const cache = new Cache();
634
- * const getItemFunc = () => fetch(url).then((data) => {
635
- * return data.json(); // undefined
636
- * });
637
- * const item = await cache.addFull('foo', getItemFunc);
638
- * if (!item) {
639
- * await createItem(); // 'New item'
640
- * }
641
- *
642
- * // somewhere else in the code
643
- * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
644
- * console.log(resp); // 'New item'
645
- * })
646
- *
647
- * ```
648
- */
649
- addFull(key, valueToSet, props) {
650
- return this.add(key, valueToSet, props, true);
651
- }
652
- add(key, valueToSet, props, onlyFull) {
653
- const exist = this._find(key, props);
654
- if (!exist) {
655
- let value;
656
- if (valueToSet instanceof Function) {
657
- value = valueToSet();
658
- }
659
- else {
660
- value = valueToSet;
661
- }
662
- const props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
663
- const cacheItem = {
664
- key,
665
- value,
666
- props: props_,
667
- // TODO: remove backward compatibility use only props
668
- options: props_,
669
- };
670
- if (onlyFull && !full(value)) {
671
- return value;
672
- }
673
- this.cache.push(cacheItem);
674
- if (value instanceof Promise) {
675
- value.catch((er) => {
676
- this.delete(key, props);
677
- throw er;
678
- });
679
- if (onlyFull) {
680
- value.then((x) => {
681
- if (!full(x)) {
682
- this.delete(key, props);
683
- }
684
- return x;
685
- });
686
- }
687
- return value;
537
+ var __defProp$a = Object.defineProperty;
538
+ var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
539
+ var __publicField$a = (obj, key, value) => {
540
+ __defNormalProp$a(obj, typeof key !== "symbol" ? key + "" : key, value);
541
+ return value;
542
+ };
543
+ const _Cache = class _Cache {
544
+ constructor(options = {}) {
545
+ __publicField$a(this, "cache", []);
546
+ var _a;
547
+ const namespace = (_a = options.namespace) != null ? _a : "default";
548
+ if (_Cache.instance[namespace]) {
549
+ return _Cache.instance[namespace];
550
+ }
551
+ _Cache.instance[namespace] = this;
552
+ return this;
553
+ }
554
+ clean() {
555
+ this.cache.length = 0;
556
+ }
557
+ all() {
558
+ return this.cache;
559
+ }
560
+ /**
561
+ * Caching only a non-empty value.
562
+ *
563
+ * Useful for get or create strategy
564
+ * @example
565
+ * ```javascript
566
+ * const cache = new Cache();
567
+ * const getItemFunc = () => fetch(url).then((data) => {
568
+ * return data.json(); // undefined
569
+ * });
570
+ * const item = await cache.addFull('foo', getItemFunc);
571
+ * if (!item) {
572
+ * await createItem(); // 'New item'
573
+ * }
574
+ *
575
+ * // somewhere else in the code
576
+ * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
577
+ * console.log(resp); // 'New item'
578
+ * })
579
+ *
580
+ * ```
581
+ */
582
+ addFull(key, valueToSet, props) {
583
+ return this.add(key, valueToSet, props, true);
584
+ }
585
+ add(key, valueToSet, props, onlyFull) {
586
+ const exist = this._find(key, props);
587
+ if (!exist) {
588
+ let value;
589
+ if (valueToSet instanceof Function) {
590
+ value = valueToSet();
591
+ } else {
592
+ value = valueToSet;
593
+ }
594
+ const props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
595
+ const cacheItem = {
596
+ key,
597
+ value,
598
+ props: props_,
599
+ // TODO: remove backward compatibility use only props
600
+ options: props_
601
+ };
602
+ if (onlyFull && !full(value)) {
603
+ return value;
604
+ }
605
+ this.cache.push(cacheItem);
606
+ if (value instanceof Promise) {
607
+ value.catch((er) => {
608
+ this.delete(key, props);
609
+ throw er;
610
+ });
611
+ if (onlyFull) {
612
+ value.then((x) => {
613
+ if (!full(x)) {
614
+ this.delete(key, props);
688
615
  }
689
- return value;
690
- }
691
- else {
692
- return exist.value;
616
+ return x;
617
+ });
693
618
  }
619
+ return value;
620
+ }
621
+ return value;
622
+ } else {
623
+ return exist.value;
694
624
  }
695
- match(key, props) {
696
- const cacheRecord = this._find(key, props);
697
- if (cacheRecord) {
698
- return cacheRecord.value;
699
- }
625
+ }
626
+ match(key, props) {
627
+ const cacheRecord = this._find(key, props);
628
+ if (cacheRecord) {
629
+ return cacheRecord.value;
700
630
  }
701
- matchAll(key, props) {
702
- if (key) {
703
- return this.cache
704
- .filter((x) => this._filter(x, key, props))
705
- .map((x) => x.value);
706
- }
707
- return this.cache.map((x) => x.value);
631
+ }
632
+ matchAll(key, props) {
633
+ if (key) {
634
+ return this.cache.filter((x) => this._filter(x, key, props)).map((x) => x.value);
708
635
  }
709
- delete(keyOrItem, props) {
710
- let exist = [];
711
- if (typeof keyOrItem === 'string') {
712
- exist = this.cache.filter((x) => this._filter(x, keyOrItem, props));
713
- }
714
- else {
715
- exist.push(keyOrItem);
716
- }
717
- for (const e of exist) {
718
- const index = this.cache.indexOf(e);
719
- this.cache.splice(index, 1);
720
- }
636
+ return this.cache.map((x) => x.value);
637
+ }
638
+ delete(keyOrItem, props) {
639
+ let exist = [];
640
+ if (typeof keyOrItem === "string") {
641
+ exist = this.cache.filter((x) => this._filter(x, keyOrItem, props));
642
+ } else {
643
+ exist.push(keyOrItem);
721
644
  }
722
- _find(key, props) {
723
- return this.cache.find((x) => this._filter(x, key, props));
645
+ for (const e of exist) {
646
+ const index = this.cache.indexOf(e);
647
+ this.cache.splice(index, 1);
724
648
  }
725
- _filter(item, key, props) {
726
- if (item.key === key) {
727
- if (props) {
728
- // TODO: remove backward compatibility
729
- const itemProps = item.props || item.options;
730
- return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
731
- }
732
- return true;
733
- }
734
- return false;
649
+ }
650
+ _find(key, props) {
651
+ return this.cache.find((x) => this._filter(x, key, props));
652
+ }
653
+ _filter(item, key, props) {
654
+ if (item.key === key) {
655
+ if (props) {
656
+ const itemProps = item.props || item.options;
657
+ return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
658
+ }
659
+ return true;
735
660
  }
736
- }
737
- Cache$1.instance = {};
738
-
739
- /**
740
- * Caching for asynchronous functions
741
- *
742
- * @packageDocumentation
743
- * @module cache
744
- */
745
- var Cache = Cache$1;
746
-
661
+ return false;
662
+ }
663
+ };
664
+ __publicField$a(_Cache, "instance", {});
665
+ let Cache = _Cache;
666
+
667
+ var __defProp$9 = Object.defineProperty;
668
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
669
+ var __publicField$9 = (obj, key, value) => {
670
+ __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
671
+ return value;
672
+ };
747
673
  class CancelError extends Error {
748
- constructor() {
749
- super();
750
- this.name = 'CancelError';
751
- Object.setPrototypeOf(this, CancelError.prototype);
752
- }
674
+ constructor() {
675
+ super();
676
+ __publicField$9(this, "name", "CancelError");
677
+ Object.setPrototypeOf(this, CancelError.prototype);
678
+ }
753
679
  }
754
680
 
681
+ var __defProp$8 = Object.defineProperty;
682
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
683
+ var __publicField$8 = (obj, key, value) => {
684
+ __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
685
+ return value;
686
+ };
755
687
  class PromiseControl {
756
- constructor(options = {}) {
757
- this.options = options;
758
- this._promises = new Map();
759
- }
760
- get isLoaded() {
761
- return this._promises.size > 0;
762
- }
763
- remove(promise) {
764
- if (this._promises.has(promise)) {
765
- this._promises.delete(promise);
766
- this._onStop();
767
- }
768
- }
769
- get(promise) {
770
- return this._promises.get(promise);
688
+ constructor(options = {}) {
689
+ this.options = options;
690
+ __publicField$8(this, "_promises", /* @__PURE__ */ new Map());
691
+ }
692
+ get isLoaded() {
693
+ return this._promises.size > 0;
694
+ }
695
+ remove(promise) {
696
+ if (this._promises.has(promise)) {
697
+ this._promises.delete(promise);
698
+ this._onStop();
771
699
  }
772
- add(promise, name) {
773
- const key = name ? name : promise;
774
- const exist = this._promises.get(key);
775
- if (this.options.onStart && !this.isLoaded) {
776
- this.options.onStart();
777
- }
778
- if (exist) {
779
- return exist;
700
+ }
701
+ get(promise) {
702
+ return this._promises.get(promise);
703
+ }
704
+ add(promise, name) {
705
+ const key = name ? name : promise;
706
+ const exist = this._promises.get(key);
707
+ if (this.options.onStart && !this.isLoaded) {
708
+ this.options.onStart();
709
+ }
710
+ if (exist) {
711
+ return exist;
712
+ }
713
+ this._promises.set(key, promise);
714
+ promise.finally(() => {
715
+ this.remove(key);
716
+ });
717
+ return promise;
718
+ }
719
+ abort() {
720
+ if (this.isLoaded) {
721
+ this._promises.forEach((x) => {
722
+ if (x.cancel) {
723
+ x.cancel();
780
724
  }
781
- this._promises.set(key, promise);
782
- promise.finally(() => {
783
- this.remove(key);
784
- });
785
- return promise;
725
+ });
726
+ this._promises.clear();
727
+ this._onStop();
786
728
  }
787
- abort() {
788
- if (this.isLoaded) {
789
- this._promises.forEach((x) => {
790
- if (x.cancel) {
791
- x.cancel();
792
- }
793
- });
794
- this._promises.clear();
795
- this._onStop();
796
- }
729
+ }
730
+ waitFunc(func, name = "") {
731
+ name = name || func.name;
732
+ const exist = this.get(name);
733
+ if (exist) {
734
+ return exist;
797
735
  }
798
- waitFunc(func, name = '') {
799
- name = name || func.name;
800
- const exist = this.get(name);
736
+ return this.add(func(), name);
737
+ }
738
+ WaitForMe(name = "") {
739
+ const get = this.get.bind(this);
740
+ const add = this.add.bind(this);
741
+ return function(target, key, descriptor) {
742
+ const originalMethod = descriptor.value;
743
+ name = name || key;
744
+ descriptor.value = function(...args) {
745
+ const exist = get(name);
801
746
  if (exist) {
802
- return exist;
803
- }
804
- return this.add(func(), name);
805
- }
806
- WaitForMe(name = '') {
807
- const get = this.get.bind(this);
808
- const add = this.add.bind(this);
809
- return function (target, key, descriptor) {
810
- const originalMethod = descriptor.value;
811
- name = name || key;
812
- descriptor.value = function (...args) {
813
- const exist = get(name);
814
- if (exist) {
815
- return exist;
816
- }
817
- const result = add(originalMethod.apply(this, args), name);
818
- return result;
819
- };
820
- return descriptor;
821
- };
822
- }
823
- /** @deprecated use {@link PromiseControl.WaitForMe } instead */
824
- GetOrCreateDecorator(name = '') {
825
- return this.WaitForMe(name);
826
- }
827
- _onStop() {
828
- if (this.options.onStop && !this.isLoaded) {
829
- this.options.onStop();
747
+ return exist;
830
748
  }
749
+ const result = add(originalMethod.apply(this, args), name);
750
+ return result;
751
+ };
752
+ return descriptor;
753
+ };
754
+ }
755
+ /** @deprecated use {@link PromiseControl.WaitForMe } instead */
756
+ GetOrCreateDecorator(name = "") {
757
+ return this.WaitForMe(name);
758
+ }
759
+ _onStop() {
760
+ if (this.options.onStop && !this.isLoaded) {
761
+ this.options.onStop();
831
762
  }
763
+ }
832
764
  }
833
765
 
766
+ var __defProp$7 = Object.defineProperty;
767
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
768
+ var __publicField$7 = (obj, key, value) => {
769
+ __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
770
+ return value;
771
+ };
834
772
  class TimeoutError extends Error {
835
- constructor() {
836
- super();
837
- this.name = 'TimeoutError';
838
- Object.setPrototypeOf(this, TimeoutError.prototype);
839
- }
773
+ constructor() {
774
+ super();
775
+ __publicField$7(this, "name", "TimeoutError");
776
+ Object.setPrototypeOf(this, TimeoutError.prototype);
777
+ }
840
778
  }
841
779
 
780
+ var __defProp$6 = Object.defineProperty;
781
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
782
+ var __publicField$6 = (obj, key, value) => {
783
+ __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
784
+ return value;
785
+ };
786
+ var _a;
842
787
  const handleCallback = (resolve, reject, callback, r) => {
843
- try {
844
- resolve(callback(r));
845
- }
846
- catch (e) {
847
- reject(e);
848
- }
788
+ try {
789
+ resolve(callback(r));
790
+ } catch (e) {
791
+ reject(e);
792
+ }
849
793
  };
850
794
  let ID$1 = 0;
851
- /**
852
- * Promise that can be canceled
853
- *
854
- * @example
855
- * Catch `CancelError`
856
- * ```javascript
857
- * import CancelablePromise from "@nextgis/cancelable-promise";
858
- *
859
- * const promise = new CancelablePromise((resolve, reject) => {
860
- * setTimeout(() => resolve(), 100);
861
- * }).catch((er) => {
862
- * if (er.name === "CancelError") {
863
- * // handle cancel error
864
- * }
865
- * throw er;
866
- * });
867
- *
868
- * promise.cancel();
869
- * ```
870
- * @example
871
- * Handle `onCancel` callback
872
- * ```javascript
873
- * import CancelablePromise from "@nextgis/cancelable-promise";
874
- *
875
- * const promise = new CancelablePromise((resolve, reject, onCancel) => {
876
- * const xhr = new XMLHttpRequest();
877
- * xhr.open("GET", url, true);
878
- * xhr.onload = () => {
879
- * resolve(xhr.responseText);
880
- * };
881
- * xhr.onerror = (er) => {
882
- * reject(er);
883
- * };
884
- *
885
- * onCancel(() => {
886
- * xhr.abort();
887
- * });
888
- *
889
- * xhr.send();
890
- * });
891
- *
892
- * promise.cancel();
893
- * ```
894
- */
895
- class CancelablePromise$1 {
896
- constructor(executor, timeout) {
897
- this.id = ID$1++;
898
- this._isCanceled = false;
899
- this._isPending = true;
900
- this._cancelHandlers = [];
901
- this._children = [];
902
- this._cancelPromise = new Promise((resolve_, reject_) => {
903
- this._setCanceledCallback = (er) => resolve_(er || new CancelError());
904
- });
905
- const promises = [
906
- this._cancelPromise,
907
- new Promise((resolve, reject) => {
908
- const onResolve = (value) => {
909
- if (value instanceof CancelablePromise$1) {
910
- this.attach(value);
911
- }
912
- else {
913
- this._isPending = false;
914
- }
915
- // TODO: fix types, `undefined` not allowed since 19.12.2020
916
- resolve(value);
917
- };
918
- const onReject = (error) => {
919
- this._isPending = false;
920
- reject(error);
921
- };
922
- const onCancel = (handler) => {
923
- if (!this._isPending) {
924
- throw new Error('The `onCancel` handler was attached after the promise settled.');
925
- }
926
- this._cancelHandlers.push(handler);
927
- };
928
- return executor(onResolve, onReject, onCancel);
929
- }),
930
- ];
931
- if (timeout) {
932
- promises.push(new Promise((resolve, reject) => {
933
- setTimeout(() => {
934
- if (this._isPending) {
935
- try {
936
- this.cancel();
937
- }
938
- finally {
939
- reject(new TimeoutError());
940
- }
941
- }
942
- }, timeout);
943
- }));
795
+ const _CancelablePromise = class _CancelablePromise {
796
+ constructor(executor, timeout) {
797
+ // @ts-ignore
798
+ __publicField$6(this, _a);
799
+ __publicField$6(this, "id", ID$1++);
800
+ __publicField$6(this, "_isCanceled", false);
801
+ __publicField$6(this, "_isPending", true);
802
+ __publicField$6(this, "_promise");
803
+ __publicField$6(this, "_cancelPromise");
804
+ __publicField$6(this, "_cancelHandlers", []);
805
+ __publicField$6(this, "_setCanceledCallback");
806
+ __publicField$6(this, "_parentPromise");
807
+ __publicField$6(this, "_children", []);
808
+ this._cancelPromise = new Promise((resolve_, reject_) => {
809
+ this._setCanceledCallback = (er) => resolve_(er || new CancelError());
810
+ });
811
+ const promises = [
812
+ this._cancelPromise,
813
+ new Promise((resolve, reject) => {
814
+ const onResolve = (value) => {
815
+ if (value instanceof _CancelablePromise) {
816
+ this.attach(value);
817
+ } else {
818
+ this._isPending = false;
819
+ }
820
+ resolve(value);
821
+ };
822
+ const onReject = (error) => {
823
+ this._isPending = false;
824
+ reject(error);
825
+ };
826
+ const onCancel = (handler) => {
827
+ if (!this._isPending) {
828
+ throw new Error(
829
+ "The `onCancel` handler was attached after the promise settled."
830
+ );
831
+ }
832
+ this._cancelHandlers.push(handler);
833
+ };
834
+ return executor(onResolve, onReject, onCancel);
835
+ })
836
+ ];
837
+ if (timeout) {
838
+ promises.push(
839
+ new Promise((resolve, reject) => {
840
+ setTimeout(() => {
841
+ if (this._isPending) {
842
+ try {
843
+ this.cancel();
844
+ } finally {
845
+ reject(new TimeoutError());
846
+ }
847
+ }
848
+ }, timeout);
849
+ })
850
+ );
851
+ }
852
+ this._promise = Promise.race(promises);
853
+ }
854
+ static createControl(opt) {
855
+ return new PromiseControl(opt);
856
+ }
857
+ static resolve(value) {
858
+ return new _CancelablePromise((resolve) => resolve(value));
859
+ }
860
+ static reject(value) {
861
+ return new _CancelablePromise((resolve, reject) => reject(value));
862
+ }
863
+ static all(values) {
864
+ return new _CancelablePromise((resolve, reject) => {
865
+ Promise.all(values).then(resolve).catch(reject);
866
+ }).catch((er) => {
867
+ if (er instanceof this.CancelError) {
868
+ for (const v of values) {
869
+ const v_ = v;
870
+ if ("cancel" in v_) {
871
+ v_.cancel();
872
+ }
944
873
  }
945
- this._promise = Promise.race(promises);
874
+ }
875
+ throw er;
876
+ });
877
+ }
878
+ attach(p) {
879
+ if (this._isCanceled) {
880
+ p.cancel();
881
+ } else {
882
+ this._children.push(p);
946
883
  }
947
- static createControl(opt) {
948
- return new PromiseControl(opt);
884
+ }
885
+ then(onfulfilled, onrejected) {
886
+ const p = new _CancelablePromise((resolve, reject) => {
887
+ if (this._promise) {
888
+ const reject_ = (r) => {
889
+ if (onrejected) {
890
+ handleCallback(resolve, reject, onrejected, r);
891
+ } else {
892
+ reject(r);
893
+ }
894
+ };
895
+ this._promise.then((r) => {
896
+ if (this._isCanceled) {
897
+ reject_(r);
898
+ } else {
899
+ if (onfulfilled) {
900
+ handleCallback(resolve, reject, onfulfilled, r);
901
+ } else {
902
+ resolve(r);
903
+ }
904
+ }
905
+ }, reject_);
906
+ }
907
+ });
908
+ p._parentPromise = this;
909
+ this._children.push(p);
910
+ return p;
911
+ }
912
+ catch(onrejected) {
913
+ if (this._isCanceled && onrejected) {
914
+ onrejected(new CancelError());
949
915
  }
950
- static resolve(value) {
951
- return new CancelablePromise$1((resolve) => resolve(value));
916
+ return this.then(void 0, onrejected);
917
+ }
918
+ finally(onfinally) {
919
+ if (this._promise) {
920
+ return this._promise.finally(onfinally);
952
921
  }
953
- static reject(value) {
954
- return new CancelablePromise$1((resolve, reject) => reject(value));
922
+ if (this._isCanceled) {
923
+ return Promise.reject(new CancelError());
955
924
  }
956
- static all(values) {
957
- return new CancelablePromise$1((resolve, reject) => {
958
- Promise.all(values).then(resolve).catch(reject);
959
- }).catch((er) => {
960
- if (er instanceof this.CancelError) {
961
- for (const v of values) {
962
- const v_ = v;
963
- if ('cancel' in v_) {
964
- v_.cancel();
965
- }
966
- }
967
- }
968
- throw er;
969
- });
925
+ return Promise.reject(onfinally);
926
+ }
927
+ cancel() {
928
+ if (this._isCanceled || !this._isPending) {
929
+ return this;
970
930
  }
971
- attach(p) {
972
- if (this._isCanceled) {
973
- p.cancel();
974
- }
975
- else {
976
- this._children.push(p);
977
- }
931
+ this._isCanceled = true;
932
+ const parent = this._getTopParent();
933
+ if (parent) {
934
+ parent.cancel();
978
935
  }
979
- then(onfulfilled, onrejected) {
980
- const p = new CancelablePromise$1((resolve, reject) => {
981
- if (this._promise) {
982
- const reject_ = (r) => {
983
- if (onrejected) {
984
- handleCallback(resolve, reject, onrejected, r);
985
- }
986
- else {
987
- reject(r);
988
- }
989
- };
990
- this._promise.then((r) => {
991
- if (this._isCanceled) {
992
- reject_(r);
993
- }
994
- else {
995
- if (onfulfilled) {
996
- handleCallback(resolve, reject, onfulfilled, r);
997
- }
998
- else {
999
- resolve(r);
1000
- }
1001
- }
1002
- }, reject_);
1003
- }
1004
- });
1005
- p._parentPromise = this;
1006
- this._children.push(p);
1007
- return p;
936
+ if (this._children) {
937
+ this._children.forEach((x) => x.cancel());
1008
938
  }
1009
- catch(onrejected) {
1010
- if (this._isCanceled && onrejected) {
1011
- onrejected(new CancelError());
939
+ if (this._isPending) {
940
+ if (this._cancelHandlers.length) {
941
+ try {
942
+ for (const handler of this._cancelHandlers) {
943
+ handler();
944
+ }
945
+ } catch (error) {
1012
946
  }
1013
- return this.then(undefined, onrejected);
947
+ }
948
+ if (this._setCanceledCallback) {
949
+ this._setCanceledCallback();
950
+ }
1014
951
  }
1015
- finally(onfinally) {
1016
- if (this._promise) {
1017
- return this._promise.finally(onfinally);
1018
- }
1019
- if (this._isCanceled) {
1020
- return Promise.reject(new CancelError());
1021
- }
1022
- return Promise.reject(onfinally);
952
+ this._destroy();
953
+ return this;
954
+ }
955
+ _getTopParent() {
956
+ let parent = this._parentPromise;
957
+ let hasParent = !!parent;
958
+ while (hasParent) {
959
+ if (parent && parent._parentPromise) {
960
+ parent = parent._parentPromise;
961
+ hasParent = !!parent;
962
+ } else {
963
+ hasParent = false;
964
+ }
1023
965
  }
1024
- cancel() {
1025
- // No reason to run cancel action if promise is already complete
1026
- if (this._isCanceled || !this._isPending) {
1027
- return this;
1028
- }
1029
- this._isCanceled = true;
1030
- const parent = this._getTopParent();
1031
- if (parent) {
1032
- parent.cancel();
1033
- }
1034
- if (this._children) {
1035
- this._children.forEach((x) => x.cancel());
1036
- }
1037
- if (this._isPending) {
1038
- if (this._cancelHandlers.length) {
1039
- try {
1040
- for (const handler of this._cancelHandlers) {
1041
- handler();
1042
- }
1043
- }
1044
- catch (error) {
1045
- // this._setCanceledCallback(error);
1046
- }
1047
- }
1048
- if (this._setCanceledCallback) {
1049
- this._setCanceledCallback();
1050
- }
1051
- }
1052
- this._destroy();
1053
- return this;
1054
- }
1055
- _getTopParent() {
1056
- let parent = this._parentPromise;
1057
- let hasParent = !!parent;
1058
- while (hasParent) {
1059
- if (parent && parent._parentPromise) {
1060
- parent = parent._parentPromise;
1061
- hasParent = !!parent;
1062
- }
1063
- else {
1064
- hasParent = false;
1065
- }
1066
- }
1067
- return parent;
1068
- }
1069
- _destroy() {
1070
- this._setCanceledCallback = undefined;
1071
- this._cancelPromise = undefined;
1072
- this._promise = undefined;
1073
- }
1074
- }
1075
- CancelablePromise$1.CancelError = CancelError;
1076
- CancelablePromise$1.TimeoutError = TimeoutError;
1077
- CancelablePromise$1.PromiseControl = PromiseControl;
1078
- Object.setPrototypeOf(CancelablePromise$1.prototype, Promise.prototype);
1079
-
1080
- /**
1081
- * A promise you can stop
1082
- *
1083
- * @packageDocumentation
1084
- * @module cancelable-promise
1085
- */
1086
- var CancelablePromise = CancelablePromise$1;
1087
-
1088
- /**
1089
- * Thrown when...
1090
- */
966
+ return parent;
967
+ }
968
+ _destroy() {
969
+ this._setCanceledCallback = void 0;
970
+ this._cancelPromise = void 0;
971
+ this._promise = void 0;
972
+ }
973
+ };
974
+ _a = Symbol.toStringTag;
975
+ __publicField$6(_CancelablePromise, "CancelError", CancelError);
976
+ __publicField$6(_CancelablePromise, "TimeoutError", TimeoutError);
977
+ __publicField$6(_CancelablePromise, "PromiseControl", PromiseControl);
978
+ let CancelablePromise = _CancelablePromise;
979
+ Object.setPrototypeOf(CancelablePromise.prototype, Promise.prototype);
980
+
981
+ var __defProp$5 = Object.defineProperty;
982
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
983
+ var __publicField$5 = (obj, key, value) => {
984
+ __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
985
+ return value;
986
+ };
1091
987
  class NgwError extends Error {
1092
- constructor(er) {
1093
- super();
1094
- this.name = 'NgwError';
1095
- Object.assign(this, er);
1096
- Object.setPrototypeOf(this, NgwError.prototype);
1097
- }
988
+ constructor(er) {
989
+ super();
990
+ __publicField$5(this, "name", "NgwError");
991
+ __publicField$5(this, "title");
992
+ __publicField$5(this, "message");
993
+ __publicField$5(this, "detail");
994
+ __publicField$5(this, "exception");
995
+ __publicField$5(this, "status_code");
996
+ __publicField$5(this, "data");
997
+ __publicField$5(this, "guru_meditation");
998
+ Object.assign(this, er);
999
+ Object.setPrototypeOf(this, NgwError.prototype);
1000
+ }
1098
1001
  }
1099
1002
 
1100
- /**
1101
- * Thrown when ...
1102
- */
1003
+ var __defProp$4 = Object.defineProperty;
1004
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1005
+ var __publicField$4 = (obj, key, value) => {
1006
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
1007
+ return value;
1008
+ };
1103
1009
  class ResourceNotFoundError extends NgwError {
1104
- constructor(obj) {
1105
- super(obj);
1106
- this.name = 'ResourceNotFoundError';
1107
- this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
1108
- Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
1109
- }
1010
+ constructor(obj) {
1011
+ super(obj);
1012
+ __publicField$4(this, "name", "ResourceNotFoundError");
1013
+ __publicField$4(this, "exception", "nextgisweb.resource.exception.ResourceNotFound");
1014
+ Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
1015
+ }
1110
1016
  }
1111
1017
 
1112
1018
  function isObject(val) {
1113
- return Object.prototype.toString.call(val) === '[object Object]';
1019
+ return Object.prototype.toString.call(val) === "[object Object]";
1114
1020
  }
1115
1021
 
1116
1022
  function resourceCompare(res1, res2) {
1117
- return objectDeepEqual(res1, res2);
1023
+ return objectDeepEqual(res1, res2);
1118
1024
  }
1119
1025
 
1120
- const exclude = ['description'];
1121
- /**
1122
- * @remarks
1123
- * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
1124
- *
1125
- * ```
1126
- * { keyname, owner_user: { id }} > { keyname, owner_user__id }
1127
- * ```
1128
- *
1129
- * @param resource - Any property from NGW resource item
1130
- */
1131
- function resourceToQuery(resource, prefix = '') {
1132
- prefix = prefix ? prefix + '__' : '';
1133
- const query = {};
1134
- for (const [key, value] of Object.entries(resource)) {
1135
- if (exclude.indexOf(key) === -1) {
1136
- if (isObject(value)) {
1137
- if (key === 'owner_user') {
1138
- const children = resourceToQuery(value, key);
1139
- Object.assign(query, children);
1140
- }
1141
- else if (key === 'parent' && 'id' in value) {
1142
- query.parent_id = value.id;
1143
- }
1144
- }
1145
- else if (defined(value)) {
1146
- query[prefix + key] = value;
1147
- }
1148
- }
1026
+ const exclude = ["description"];
1027
+ function resourceToQuery(resource, prefix = "") {
1028
+ prefix = prefix ? prefix + "__" : "";
1029
+ const query = {};
1030
+ for (const [key, value] of Object.entries(resource)) {
1031
+ if (exclude.indexOf(key) === -1) {
1032
+ if (isObject(value)) {
1033
+ if (key === "owner_user") {
1034
+ const children = resourceToQuery(value, key);
1035
+ Object.assign(query, children);
1036
+ } else if (key === "parent" && "id" in value) {
1037
+ query.parent_id = value.id;
1038
+ }
1039
+ } else if (defined(value)) {
1040
+ query[prefix + key] = value;
1041
+ }
1149
1042
  }
1150
- return query;
1043
+ }
1044
+ return query;
1151
1045
  }
1152
1046
 
1047
+ var __defProp$3 = Object.defineProperty;
1048
+ var __defProps = Object.defineProperties;
1049
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1050
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1051
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1052
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1053
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1054
+ var __spreadValues$1 = (a, b) => {
1055
+ for (var prop in b || (b = {}))
1056
+ if (__hasOwnProp$1.call(b, prop))
1057
+ __defNormalProp$3(a, prop, b[prop]);
1058
+ if (__getOwnPropSymbols$1)
1059
+ for (var prop of __getOwnPropSymbols$1(b)) {
1060
+ if (__propIsEnum$1.call(b, prop))
1061
+ __defNormalProp$3(a, prop, b[prop]);
1062
+ }
1063
+ return a;
1064
+ };
1065
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1066
+ var __publicField$3 = (obj, key, value) => {
1067
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
1068
+ return value;
1069
+ };
1070
+ var __async = (__this, __arguments, generator) => {
1071
+ return new Promise((resolve, reject) => {
1072
+ var fulfilled = (value) => {
1073
+ try {
1074
+ step(generator.next(value));
1075
+ } catch (e) {
1076
+ reject(e);
1077
+ }
1078
+ };
1079
+ var rejected = (value) => {
1080
+ try {
1081
+ step(generator.throw(value));
1082
+ } catch (e) {
1083
+ reject(e);
1084
+ }
1085
+ };
1086
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1087
+ step((generator = generator.apply(__this, __arguments)).next());
1088
+ });
1089
+ };
1153
1090
  class ResourcesControl {
1154
- constructor(connector) {
1155
- this.connector = connector;
1156
- this.cache = new Cache();
1157
- }
1158
- // -------------------------------------------------------------------------
1159
- // Resource Methods
1160
- // -------------------------------------------------------------------------
1161
- /**
1162
- * Receive resource from NGW by id, keyname or search-object parameter.
1163
- * @param resource - Resource id, keyname or search-object
1164
- *
1165
- * @remarks
1166
- * Fetching resource would be cached to speed up next call
1167
- */
1168
- getOne(resource, requestOptions) {
1169
- const cache = new Cache();
1170
- const forCache = {};
1171
- const opt = { ...requestOptions, cache: false };
1172
- if (typeof resource === 'string') {
1173
- forCache.keyname = resource;
1174
- }
1175
- else if (typeof resource === 'number') {
1176
- forCache.id = resource;
1177
- }
1178
- else if (isObject(resource)) {
1179
- if (resource.id !== undefined) {
1180
- forCache.id = resource.id;
1181
- }
1182
- else if (resource.keyname) {
1183
- forCache.keyname = resource.keyname;
1184
- }
1185
- }
1186
- const makeRequest = () => {
1187
- if (typeof resource === 'string') {
1188
- return this._fetchResourceBy({ keyname: resource }, opt);
1189
- }
1190
- else if (typeof resource === 'number') {
1191
- return this._fetchResourceById(resource, opt);
1192
- }
1193
- else if (isObject(resource)) {
1194
- return this._fetchResourceBy(resource, opt);
1195
- }
1196
- return CancelablePromise.resolve(undefined);
1197
- };
1198
- return cache.addFull('resource', makeRequest, forCache);
1199
- }
1200
- getOneOrFail(resource, requestOptions) {
1201
- return this.getOne(resource, requestOptions).then((res) => {
1202
- if (res) {
1203
- return res;
1204
- }
1205
- throw new ResourceNotFoundError();
1206
- });
1207
- }
1208
- /**
1209
- * A fast way to retrieve resource ID for any resource definition.
1210
- * @param resource - Any available resource definition
1211
- *
1212
- * @remarks
1213
- * There are situations when exactly the resource id is needed
1214
- * (for example, to compose the correct request to the api)
1215
- * then this method will come in handy to facilitate the extraction of the identifier
1216
- * if the resource is specified through a keyname or other parameters.
1217
- */
1218
- getId(resource, requestOptions) {
1219
- if (typeof resource === 'number') {
1220
- return CancelablePromise.resolve(resource);
1221
- }
1222
- else if (typeof resource === 'string' || isObject(resource)) {
1223
- return this.getOne(resource, requestOptions).then((res) => {
1224
- if (res) {
1225
- return res.resource.id;
1226
- }
1227
- });
1091
+ constructor(connector) {
1092
+ this.connector = connector;
1093
+ __publicField$3(this, "cache", new Cache());
1094
+ }
1095
+ // -------------------------------------------------------------------------
1096
+ // Resource Methods
1097
+ // -------------------------------------------------------------------------
1098
+ /**
1099
+ * Receive resource from NGW by id, keyname or search-object parameter.
1100
+ * @param resource - Resource id, keyname or search-object
1101
+ *
1102
+ * @remarks
1103
+ * Fetching resource would be cached to speed up next call
1104
+ */
1105
+ getOne(resource, requestOptions) {
1106
+ const cache = new Cache();
1107
+ const forCache = {};
1108
+ const opt = __spreadProps(__spreadValues$1({}, requestOptions), { cache: false });
1109
+ if (typeof resource === "string") {
1110
+ forCache.keyname = resource;
1111
+ } else if (typeof resource === "number") {
1112
+ forCache.id = resource;
1113
+ } else if (isObject(resource)) {
1114
+ if (resource.id !== void 0) {
1115
+ forCache.id = resource.id;
1116
+ } else {
1117
+ if (resource.keyname) {
1118
+ forCache.keyname = resource.keyname;
1119
+ }
1120
+ if (resource.display_name) {
1121
+ forCache.display_name = resource.display_name;
1228
1122
  }
1229
- return CancelablePromise.resolve(undefined);
1230
- }
1231
- /**
1232
- * A fast way to retrieve resource ID for any resource definition.
1233
- * @param resource - Any available resource definition
1234
- *
1235
- * @remarks
1236
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1237
- * To not make one more checks if the resource is definitely exists
1238
- */
1239
- getIdOrFail(resource, requestOptions) {
1240
- return this.getId(resource, requestOptions).then((resp) => {
1241
- if (resp === undefined) {
1242
- throw new Error();
1243
- }
1244
- return resp;
1245
- });
1123
+ }
1246
1124
  }
1247
- getMany(resource, requestOptions) {
1248
- return this._resourceCacheFilter(resource).then((items) => {
1249
- if (!items.length) {
1250
- const query = {};
1251
- if (resource.keyname) {
1252
- query.keyname = resource.keyname;
1253
- }
1254
- else {
1255
- Object.assign(query, resourceToQuery(resource));
1256
- }
1257
- return this.connector
1258
- .get('resource.search', requestOptions, {
1259
- serialization: 'full',
1260
- ...query,
1261
- })
1262
- .then((resources) => {
1263
- if (resources) {
1264
- for (const x of resources) {
1265
- this.cache.add('resource.item', CancelablePromise.resolve(x), {
1266
- id: x.resource.id,
1267
- });
1268
- }
1269
- }
1270
- return resources;
1271
- });
1125
+ const makeRequest = () => {
1126
+ if (typeof resource === "string") {
1127
+ return this._fetchResourceBy({ keyname: resource }, opt);
1128
+ } else if (typeof resource === "number") {
1129
+ return this._fetchResourceById(resource, opt);
1130
+ } else if (isObject(resource)) {
1131
+ return this._fetchResourceBy(resource, opt);
1132
+ }
1133
+ return CancelablePromise.resolve(void 0);
1134
+ };
1135
+ return cache.addFull("resource", makeRequest, forCache);
1136
+ }
1137
+ getOneOrFail(resource, requestOptions) {
1138
+ return this.getOne(resource, requestOptions).then((res) => {
1139
+ if (res) {
1140
+ return res;
1141
+ }
1142
+ throw new ResourceNotFoundError();
1143
+ });
1144
+ }
1145
+ /**
1146
+ * A fast way to retrieve resource ID for any resource definition.
1147
+ * @param resource - Any available resource definition
1148
+ *
1149
+ * @remarks
1150
+ * There are situations when exactly the resource id is needed
1151
+ * (for example, to compose the correct request to the api)
1152
+ * then this method will come in handy to facilitate the extraction of the identifier
1153
+ * if the resource is specified through a keyname or other parameters.
1154
+ */
1155
+ getId(resource, requestOptions) {
1156
+ if (typeof resource === "number") {
1157
+ return CancelablePromise.resolve(resource);
1158
+ } else if (typeof resource === "string" || isObject(resource)) {
1159
+ return this.getOne(resource, requestOptions).then((res) => {
1160
+ if (res) {
1161
+ return res.resource.id;
1162
+ }
1163
+ });
1164
+ }
1165
+ return CancelablePromise.resolve(void 0);
1166
+ }
1167
+ /**
1168
+ * A fast way to retrieve resource ID for any resource definition.
1169
+ * @param resource - Any available resource definition
1170
+ *
1171
+ * @remarks
1172
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1173
+ * To not make one more checks if the resource is definitely exists
1174
+ */
1175
+ getIdOrFail(resource, requestOptions) {
1176
+ return this.getId(resource, requestOptions).then((resp) => {
1177
+ if (resp === void 0) {
1178
+ throw new Error();
1179
+ }
1180
+ return resp;
1181
+ });
1182
+ }
1183
+ getMany(resource, requestOptions) {
1184
+ return this._resourceCacheFilter(resource).then((items) => {
1185
+ if (!items.length) {
1186
+ const query = {};
1187
+ if (resource.keyname) {
1188
+ query.keyname = resource.keyname;
1189
+ } else {
1190
+ Object.assign(query, resourceToQuery(resource));
1191
+ }
1192
+ return this.connector.get("resource.search", requestOptions, __spreadValues$1({
1193
+ serialization: "full"
1194
+ }, query)).then((resources) => {
1195
+ if (resources) {
1196
+ for (const x of resources) {
1197
+ this.cache.add("resource.item", CancelablePromise.resolve(x), {
1198
+ id: x.resource.id
1199
+ });
1272
1200
  }
1273
- return items;
1201
+ }
1202
+ return resources;
1274
1203
  });
1275
- }
1276
- getParent(resource, requestOptions) {
1277
- return this.getOne(resource, requestOptions).then((child) => {
1278
- if (child) {
1279
- return this.getOne(child.resource.parent.id, requestOptions);
1280
- }
1281
- return CancelablePromise.resolve(undefined);
1204
+ }
1205
+ return items;
1206
+ });
1207
+ }
1208
+ getParent(resource, requestOptions) {
1209
+ return this.getOne(resource, requestOptions).then((child) => {
1210
+ if (child) {
1211
+ return this.getOne(child.resource.parent.id, requestOptions);
1212
+ }
1213
+ return CancelablePromise.resolve(void 0);
1214
+ });
1215
+ }
1216
+ getChildrenOf(resource, requestOptions) {
1217
+ return this.getIdOrFail(resource).then(
1218
+ (parent) => this._getChildrenOf(parent, requestOptions)
1219
+ );
1220
+ }
1221
+ update(resource, data) {
1222
+ return this.getId(resource).then((id) => {
1223
+ if (id !== void 0) {
1224
+ return this.connector.put("resource.item", { data }, { id });
1225
+ }
1226
+ });
1227
+ }
1228
+ /**
1229
+ * Fast way to delete resource from NGW and clean cache.
1230
+ * @param resource - Resource definition
1231
+ */
1232
+ delete(resource) {
1233
+ return this.getId(resource).then((id) => {
1234
+ if (id !== void 0) {
1235
+ return this.connector.delete("resource.item", null, { id }).then(() => {
1236
+ this._cleanResourceItemCache(id);
1237
+ return void 0;
1282
1238
  });
1283
- }
1284
- getChildrenOf(resource, requestOptions) {
1285
- return this.getIdOrFail(resource).then((parent) => this._getChildrenOf(parent, requestOptions));
1286
- }
1287
- update(resource, data) {
1288
- return this.getId(resource).then((id) => {
1289
- if (id !== undefined) {
1290
- return this.connector.put('resource.item', { data }, { id });
1291
- }
1239
+ }
1240
+ });
1241
+ }
1242
+ _getChildrenOf(parent, requestOptions, _items = []) {
1243
+ return this.connector.get(
1244
+ "resource.collection",
1245
+ __spreadValues$1({ cache: true }, requestOptions),
1246
+ {
1247
+ parent
1248
+ }
1249
+ ).then((items) => {
1250
+ const recursivePromises = [];
1251
+ for (const item of items) {
1252
+ this.cache.add("resource.item", CancelablePromise.resolve(item), {
1253
+ id: item.resource.id
1292
1254
  });
1293
- }
1294
- /**
1295
- * Fast way to delete resource from NGW and clean cache.
1296
- * @param resource - Resource definition
1297
- */
1298
- delete(resource) {
1299
- return this.getId(resource).then((id) => {
1300
- if (id !== undefined) {
1301
- return this.connector.delete('resource.item', null, { id }).then(() => {
1302
- this._cleanResourceItemCache(id);
1303
- return undefined;
1304
- });
1305
- }
1255
+ _items.push(item);
1256
+ if ((requestOptions == null ? void 0 : requestOptions.recursive) && item.resource.children) {
1257
+ recursivePromises.push(
1258
+ this._getChildrenOf(item.resource.id, requestOptions, _items)
1259
+ );
1260
+ }
1261
+ }
1262
+ if (recursivePromises.length) {
1263
+ return CancelablePromise.all(recursivePromises).then(() => {
1264
+ return _items;
1306
1265
  });
1307
- }
1308
- _getChildrenOf(parent, requestOptions, _items = []) {
1309
- return this.connector
1310
- .get('resource.collection', { cache: true, ...requestOptions }, {
1311
- parent,
1312
- })
1313
- .then((items) => {
1314
- const recursivePromises = [];
1315
- for (const item of items) {
1316
- this.cache.add('resource.item', CancelablePromise.resolve(item), {
1317
- id: item.resource.id,
1318
- });
1319
- _items.push(item);
1320
- if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
1321
- recursivePromises.push(this._getChildrenOf(item.resource.id, requestOptions, _items));
1322
- }
1323
- }
1324
- if (recursivePromises.length) {
1325
- return CancelablePromise.all(recursivePromises).then(() => {
1326
- return _items;
1327
- });
1266
+ }
1267
+ return _items;
1268
+ });
1269
+ }
1270
+ _cleanResourceItemCache(id) {
1271
+ return __async(this, null, function* () {
1272
+ const all = this.cache.all();
1273
+ const toDelete = [];
1274
+ for (const c of all) {
1275
+ const cid = c.options && c.options.id;
1276
+ if (["resource.item", "resource"].includes(c.key) && cid !== void 0) {
1277
+ if (typeof cid === "number") {
1278
+ if (cid === id) {
1279
+ toDelete.push(c);
1328
1280
  }
1329
- return _items;
1330
- });
1331
- }
1332
- async _cleanResourceItemCache(id) {
1333
- const all = this.cache.all();
1334
- const toDelete = [];
1335
- for (const c of all) {
1336
- const cid = c.options && c.options.id;
1337
- if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {
1338
- if (typeof cid === 'number') {
1339
- if (cid === id) {
1340
- toDelete.push(c);
1341
- }
1342
- }
1343
- else {
1344
- const rid = await this.getId(cid);
1345
- if (rid === id) {
1346
- toDelete.push(c);
1347
- }
1348
- }
1281
+ } else {
1282
+ const rid = yield this.getId(cid);
1283
+ if (rid === id) {
1284
+ toDelete.push(c);
1349
1285
  }
1286
+ }
1350
1287
  }
1351
- for (const d of toDelete) {
1352
- this.cache.delete(d);
1353
- }
1354
- }
1355
- _fetchResourceById(id, requestOptions) {
1356
- const promise = () => this.connector.get('resource.item', requestOptions, { id });
1357
- return this.cache
1358
- .add('resource.item', promise, {
1359
- id,
1360
- })
1361
- .catch((er) => {
1362
- if (!(er instanceof ResourceNotFoundError)) {
1363
- throw er;
1288
+ }
1289
+ for (const d of toDelete) {
1290
+ this.cache.delete(d);
1291
+ }
1292
+ });
1293
+ }
1294
+ _fetchResourceById(id, requestOptions) {
1295
+ const promise = () => this.connector.get("resource.item", requestOptions, { id });
1296
+ return this.cache.add("resource.item", promise, {
1297
+ id
1298
+ }).catch((er) => {
1299
+ if (!(er instanceof ResourceNotFoundError)) {
1300
+ throw er;
1301
+ }
1302
+ return void 0;
1303
+ });
1304
+ }
1305
+ _fetchResourceBy(resource, requestOptions) {
1306
+ return this.getMany(resource, requestOptions).then((resources) => {
1307
+ return resources[0];
1308
+ });
1309
+ }
1310
+ _resourceCacheFilter(resource) {
1311
+ return CancelablePromise.all(this.cache.matchAll("resource.item")).then(
1312
+ (resources) => {
1313
+ const items = [];
1314
+ resources.filter((x) => {
1315
+ if (x) {
1316
+ if (resource.keyname && x.resource.keyname) {
1317
+ return resource.keyname === x.resource.keyname;
1364
1318
  }
1365
- return undefined;
1366
- });
1367
- }
1368
- _fetchResourceBy(resource, requestOptions) {
1369
- return this.getMany(resource, requestOptions).then((resources) => {
1370
- return resources[0];
1371
- });
1372
- }
1373
- _resourceCacheFilter(resource) {
1374
- return CancelablePromise.all(this.cache.matchAll('resource.item')).then((resources) => {
1375
- const items = [];
1376
- resources.filter((x) => {
1377
- if (x) {
1378
- // identical by uniq props
1379
- if (resource.keyname && x.resource.keyname) {
1380
- return resource.keyname === x.resource.keyname;
1381
- }
1382
- if (defined(resource.id) && defined(x.resource.id)) {
1383
- return resource.id === x.resource.id;
1384
- }
1385
- return resourceCompare(resource, x.resource);
1386
- }
1387
- });
1388
- return items;
1319
+ if (defined(resource.id) && defined(x.resource.id)) {
1320
+ return resource.id === x.resource.id;
1321
+ }
1322
+ return resourceCompare(resource, x.resource);
1323
+ }
1389
1324
  });
1390
- }
1325
+ return items;
1326
+ }
1327
+ );
1328
+ }
1391
1329
  }
1392
1330
 
1393
1331
  const CONNECTORS = [];
1394
1332
  function addConnector(connector) {
1395
- CONNECTORS.push(connector);
1333
+ CONNECTORS.push(connector);
1396
1334
  }
1397
1335
  function findConnector(options) {
1398
- return CONNECTORS.find((x) => {
1399
- if (x.options.baseUrl === options.baseUrl) {
1400
- if (options.auth) {
1401
- if (x.options.auth) {
1402
- return objectDeepEqual(x.options.auth, options.auth);
1403
- }
1404
- }
1405
- else {
1406
- // if auth not in find options; use first connector with same url
1407
- return true;
1408
- }
1409
- }
1410
- });
1336
+ return CONNECTORS.find((x) => {
1337
+ if (x.options.baseUrl === options.baseUrl) {
1338
+ if (options.auth) {
1339
+ if (x.options.auth) {
1340
+ return objectDeepEqual(x.options.auth, options.auth);
1341
+ }
1342
+ } else {
1343
+ return true;
1344
+ }
1345
+ }
1346
+ });
1411
1347
  }
1412
1348
  function removeConnector(connector) {
1413
- const index = CONNECTORS.indexOf(connector);
1414
- if (index !== -1) {
1415
- CONNECTORS.splice(index, 1);
1416
- }
1349
+ const index = CONNECTORS.indexOf(connector);
1350
+ if (index !== -1) {
1351
+ CONNECTORS.splice(index, 1);
1352
+ }
1417
1353
  }
1418
1354
 
1419
- /**
1420
- * Thrown when ...
1421
- */
1355
+ var __defProp$2 = Object.defineProperty;
1356
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1357
+ var __publicField$2 = (obj, key, value) => {
1358
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1359
+ return value;
1360
+ };
1422
1361
  class InsufficientPermissionsError extends NgwError {
1423
- constructor(obj) {
1424
- super(obj);
1425
- this.name = 'InsufficientPermissionsError';
1426
- this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
1427
- Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1428
- }
1362
+ constructor(obj) {
1363
+ super(obj);
1364
+ __publicField$2(this, "name", "InsufficientPermissionsError");
1365
+ __publicField$2(this, "exception", "nextgisweb.core.exception.InsufficientPermissions");
1366
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1367
+ }
1429
1368
  }
1430
1369
 
1431
- // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
1432
1370
  const templateRe = /\{ *([\w_-]+) *\}/g;
1433
1371
  function template(str, data) {
1434
- return str.replace(templateRe, (s, key) => {
1435
- let value = data[key];
1436
- if (value === undefined) {
1437
- throw new Error('No value provided for letiable ' + s);
1438
- }
1439
- else if (typeof value === 'function') {
1440
- value = value(data);
1441
- }
1442
- return value;
1443
- });
1372
+ return str.replace(templateRe, (s, key) => {
1373
+ let value = data[key];
1374
+ if (value === void 0) {
1375
+ throw new Error("No value provided for letiable " + s);
1376
+ } else if (typeof value === "function") {
1377
+ value = value(data);
1378
+ }
1379
+ return value;
1380
+ });
1444
1381
  }
1445
1382
 
1446
1383
  function apiRequest(opt) {
1447
- const params = opt.params;
1448
- return new CancelablePromise((resolve, reject) => {
1449
- opt.connector
1450
- .connect()
1451
- .then((apiItems) => {
1452
- let apiItem = apiItems && apiItems[opt.name];
1453
- if (apiItem) {
1454
- apiItem = [...apiItem];
1455
- let url = apiItem.shift();
1456
- if (apiItem.length) {
1457
- const replaceParams = {};
1458
- for (let fry = 0; fry < apiItem.length; fry++) {
1459
- const arg = apiItem[fry];
1460
- replaceParams[fry] = '{' + arg + '}';
1461
- if (params[arg] === undefined) {
1462
- throw new Error('`' + arg + '`' + ' url api argument is not specified');
1463
- }
1464
- }
1465
- if (url) {
1466
- url = template(url, replaceParams);
1467
- }
1468
- }
1469
- // Transfer part of the parameters from `params` to the URL string
1470
- if (params) {
1471
- const paramArray = [];
1472
- const paramList = params.paramList;
1473
- if (Array.isArray(paramList)) {
1474
- delete params.paramList;
1475
- paramList.forEach((x) => {
1476
- paramArray.push(`${x[0]}=${x[1]}`);
1477
- });
1478
- }
1479
- for (const p in params) {
1480
- if (apiItem.indexOf(p) === -1) {
1481
- paramArray.push(`${p}=${params[p]}`);
1482
- }
1483
- }
1484
- if (paramArray.length) {
1485
- url = url + '?' + paramArray.join('&');
1486
- }
1487
- }
1488
- if (url) {
1489
- resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
1490
- }
1491
- else {
1492
- reject(new Error('request url is not set'));
1493
- }
1384
+ const params = opt.params;
1385
+ return new CancelablePromise((resolve, reject) => {
1386
+ opt.connector.connect().then((apiItems) => {
1387
+ let apiItem = apiItems && apiItems[opt.name];
1388
+ if (apiItem) {
1389
+ apiItem = [...apiItem];
1390
+ let url = apiItem.shift();
1391
+ if (apiItem.length) {
1392
+ const replaceParams = {};
1393
+ for (let fry = 0; fry < apiItem.length; fry++) {
1394
+ const arg = apiItem[fry];
1395
+ replaceParams[fry] = "{" + arg + "}";
1396
+ if (params[arg] === void 0) {
1397
+ throw new Error(
1398
+ "`" + arg + "` url api argument is not specified"
1399
+ );
1494
1400
  }
1495
- else {
1496
- resolve(undefined);
1401
+ }
1402
+ if (url) {
1403
+ url = template(url, replaceParams);
1404
+ }
1405
+ }
1406
+ if (params) {
1407
+ const paramArray = [];
1408
+ const paramList = params.paramList;
1409
+ if (Array.isArray(paramList)) {
1410
+ delete params.paramList;
1411
+ paramList.forEach((x) => {
1412
+ paramArray.push(`${x[0]}=${x[1]}`);
1413
+ });
1414
+ }
1415
+ for (const p in params) {
1416
+ if (apiItem.indexOf(p) === -1) {
1417
+ paramArray.push(`${p}=${params[p]}`);
1497
1418
  }
1498
- })
1499
- .catch((er) => {
1500
- reject(er);
1501
- });
1419
+ }
1420
+ if (paramArray.length) {
1421
+ url = url + "?" + paramArray.join("&");
1422
+ }
1423
+ }
1424
+ if (url) {
1425
+ resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
1426
+ } else {
1427
+ reject(new Error("request url is not set"));
1428
+ }
1429
+ } else {
1430
+ resolve(void 0);
1431
+ }
1432
+ }).catch((er) => {
1433
+ reject(er);
1502
1434
  });
1435
+ });
1503
1436
  }
1504
1437
 
1505
- /**
1506
- * Thrown when...
1507
- */
1438
+ var __defProp$1 = Object.defineProperty;
1439
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1440
+ var __publicField$1 = (obj, key, value) => {
1441
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1442
+ return value;
1443
+ };
1508
1444
  class NetworkError extends Error {
1509
- constructor(url) {
1510
- super();
1511
- this.name = 'NetworkError';
1512
- Object.setPrototypeOf(this, NetworkError.prototype);
1513
- this.message = `Unable to request ${url}.
1514
- Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`; // /control-panel/cors
1515
- }
1445
+ constructor(url) {
1446
+ super();
1447
+ __publicField$1(this, "name", "NetworkError");
1448
+ Object.setPrototypeOf(this, NetworkError.prototype);
1449
+ this.message = `Unable to request ${url}.
1450
+ Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`;
1451
+ }
1516
1452
  }
1517
1453
 
1518
1454
  let loadData;
1519
- // @ts-ignore
1520
1455
  {
1521
- loadData = (url, callback, options = {}, error, onCancel) => {
1522
- options.method = options.method || 'GET';
1523
- const xhr = new XMLHttpRequest();
1524
- xhr.open(options.method || 'GET', url, true); // true for asynchronous
1525
- if (options.responseType === 'blob') {
1526
- xhr.responseType = options.responseType;
1527
- }
1528
- const getResponseText = () => {
1529
- try {
1530
- return JSON.parse(xhr.responseText);
1531
- }
1532
- catch (er) {
1533
- return xhr.responseText;
1534
- }
1535
- };
1536
- const processingResponse = (forError = false) => {
1537
- const cb = forError ? error : callback;
1538
- if (options.responseType === 'blob') {
1539
- cb(xhr.response);
1540
- }
1541
- else {
1542
- if (xhr.responseText) {
1543
- cb(getResponseText());
1544
- }
1545
- else {
1546
- error({ message: '' });
1547
- }
1548
- }
1549
- };
1550
- xhr.onload = () => {
1551
- if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1552
- error(new NgwError(getResponseText()));
1553
- }
1554
- processingResponse();
1555
- };
1556
- // xhr.onreadystatechange = () => {
1557
- // if (
1558
- // (xhr.readyState === 4 && xhr.status === 200) ||
1559
- // (xhr.readyState === 3 && xhr.status === 201)
1560
- // ) {
1561
- // processingResponse();
1562
- // } else if (xhr.readyState === 3 && xhr.status === 400) {
1563
- // processingResponse();
1564
- // } else if (xhr.readyState === 4 && xhr.status === 500) {
1565
- // processingResponse();
1566
- // } else if (xhr.readyState === 4 && xhr.status === 401) {
1567
- // error(xhr.statusText);
1568
- // } else if (xhr.readyState === 4) {
1569
- // error('request error');
1570
- // }
1571
- // };
1572
- xhr.onerror = (er) => {
1573
- if (xhr.status === 0) {
1574
- error(new NetworkError(url));
1575
- }
1576
- else {
1577
- error(er);
1578
- }
1579
- };
1580
- xhr.upload.onprogress = function (e) {
1581
- if (e.lengthComputable) {
1582
- const percentComplete = (e.loaded / e.total) * 100;
1583
- if (options.onProgress) {
1584
- options.onProgress(percentComplete, e);
1585
- }
1586
- // console.log(percentComplete + '% uploaded');
1587
- }
1588
- };
1589
- const headers = options.headers;
1590
- if (headers) {
1591
- for (const h in headers) {
1592
- const header = headers[h];
1593
- if (typeof header === 'string') {
1594
- xhr.setRequestHeader(h, header);
1595
- }
1596
- }
1597
- }
1598
- if (options.withCredentials !== undefined) {
1599
- xhr.withCredentials = options.withCredentials;
1600
- }
1601
- let data;
1602
- if (options.file) {
1603
- data = new FormData();
1604
- data.append('file', options.file);
1605
- if (options.data) {
1606
- for (const d in options.data) {
1607
- data.append(d, data[d]);
1608
- }
1609
- }
1610
- }
1611
- else {
1612
- data = options.data
1613
- ? typeof options.data === 'string'
1614
- ? options.data
1615
- : JSON.stringify(options.data)
1616
- : null;
1617
- }
1618
- if (onCancel) {
1619
- onCancel(() => {
1620
- xhr.abort();
1621
- });
1622
- }
1623
- xhr.send(data);
1456
+ loadData = (url, callback, options = {}, error, onCancel) => {
1457
+ options.method = options.method || "GET";
1458
+ const xhr = new XMLHttpRequest();
1459
+ xhr.open(options.method || "GET", url, true);
1460
+ if (options.responseType === "blob") {
1461
+ xhr.responseType = options.responseType;
1462
+ }
1463
+ const getResponseText = () => {
1464
+ try {
1465
+ return JSON.parse(xhr.responseText);
1466
+ } catch (er) {
1467
+ return xhr.responseText;
1468
+ }
1624
1469
  };
1625
- }
1626
-
1627
- let ID = 0;
1628
- class NgwConnector$1 {
1629
- constructor(options) {
1630
- this.options = options;
1631
- this.id = ID++;
1632
- this.emitter = new events.exports.EventEmitter();
1633
- this.routeStr = '/api/component/pyramid/route';
1634
- this.activeRequests = [];
1635
- const exist = findConnector(options);
1636
- if (exist) {
1637
- return exist;
1638
- }
1639
- else {
1640
- if (this.options.route) {
1641
- this.routeStr = this.options.route;
1642
- }
1643
- if (this.options.requestTransform) {
1644
- this.requestTransform = this.options.requestTransform;
1645
- }
1646
- this.resources = new ResourcesControl(this);
1647
- addConnector(this);
1470
+ const processingResponse = (forError = false) => {
1471
+ const cb = forError ? error : callback;
1472
+ if (options.responseType === "blob") {
1473
+ cb(xhr.response);
1474
+ } else {
1475
+ if (xhr.responseText) {
1476
+ cb(getResponseText());
1477
+ } else {
1478
+ error({ message: "" });
1648
1479
  }
1649
- }
1650
- static create(options) {
1651
- return new this(options);
1652
- }
1653
- setRequestTransform(requestTransform) {
1654
- this.requestTransform = requestTransform;
1655
- }
1656
- /**
1657
- * Fast way to specify the connection address to NextGIS Web.
1658
- * The current connection will be severed.
1659
- * @param baseUrl - NGW url
1660
- */
1661
- setNgw(baseUrl) {
1662
- this.logout();
1663
- this.options.baseUrl = baseUrl;
1664
- addConnector(this);
1665
- }
1666
- /**
1667
- * Establishing a connection with NextGIS Web to fulfill all other requests.
1668
- * @remarks
1669
- * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1670
- * Can be used to check connection.
1671
- * @example
1672
- * ```javascript
1673
- * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1674
- * connector.connect()
1675
- * .then(() => console.log('Ok'))
1676
- * .catch((er) => console.log('Connection problem', er));
1677
- * ```
1678
- */
1679
- connect() {
1680
- const cache = new Cache();
1681
- const auth = this.options.auth;
1682
- const makeConnect = () => new CancelablePromise((resolve, reject) => {
1683
- const makeQuery = () => {
1684
- return this.makeQuery(this.routeStr, {}, {})
1685
- .then((route) => {
1686
- resolve(route);
1687
- })
1688
- .catch((er) => {
1689
- reject(er);
1690
- });
1691
- };
1692
- if (auth) {
1693
- const { login, password } = auth;
1694
- if (login && password) {
1695
- return this._login({ login, password })
1696
- .then(() => {
1697
- return makeQuery();
1698
- })
1699
- .catch((er) => reject(er));
1700
- }
1701
- }
1702
- return makeQuery();
1703
- });
1704
- return cache.add('route', makeConnect, {
1705
- id: this.id,
1706
- auth,
1707
- baseUrl: this.options.baseUrl,
1708
- });
1709
- }
1710
- /**
1711
- * Quick way to change NextGIS Web user.
1712
- * @param credentials - New user credentials
1713
- */
1714
- login(credentials, options) {
1715
- this.logout();
1716
- addConnector(this);
1717
- return this._login(credentials, options);
1718
- }
1719
- /**
1720
- * Disconnecting a user. Aborting all current requests
1721
- */
1722
- logout() {
1723
- this.abort();
1724
- removeConnector(this);
1725
- this.options.auth = undefined;
1726
- this.user = undefined;
1727
- this.emitter.emit('logout');
1728
- this.resources.cache.clean();
1729
- }
1730
- getUserInfo(credentials, options) {
1731
- if (this.user && this.user.id) {
1732
- return CancelablePromise.resolve(this.user);
1480
+ }
1481
+ };
1482
+ xhr.onload = () => {
1483
+ if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1484
+ error(new NgwError(getResponseText()));
1485
+ }
1486
+ processingResponse();
1487
+ };
1488
+ xhr.onerror = (er) => {
1489
+ if (xhr.status === 0) {
1490
+ error(new NetworkError(url));
1491
+ } else {
1492
+ error(er);
1493
+ }
1494
+ };
1495
+ xhr.upload.onprogress = function(e) {
1496
+ if (e.lengthComputable) {
1497
+ const percentComplete = e.loaded / e.total * 100;
1498
+ if (options.onProgress) {
1499
+ options.onProgress(percentComplete, e);
1733
1500
  }
1734
- if (credentials) {
1735
- this.options.auth = credentials;
1501
+ }
1502
+ };
1503
+ const headers = options.headers;
1504
+ if (headers) {
1505
+ for (const h in headers) {
1506
+ const header = headers[h];
1507
+ if (typeof header === "string") {
1508
+ xhr.setRequestHeader(h, header);
1736
1509
  }
1737
- const options_ = {
1738
- headers: this.getAuthorizationHeaders(credentials),
1739
- // withCredentials: true
1740
- ...options,
1741
- };
1742
- // Do not use apiRequest('auth.current_user') to avoid circular-references
1743
- return this.makeQuery('/api/component/auth/current_user', {}, options_);
1510
+ }
1744
1511
  }
1745
- /**
1746
- * Obtaining the required Headers for authentication of requests in the NGW.
1747
- */
1748
- getAuthorizationHeaders(credentials) {
1749
- const client = this.makeClientId(credentials);
1750
- if (client) {
1751
- return {
1752
- Authorization: 'Basic ' + client,
1753
- };
1754
- }
1512
+ if (options.withCredentials !== void 0) {
1513
+ xhr.withCredentials = options.withCredentials;
1755
1514
  }
1756
- makeClientId(credentials) {
1757
- credentials = credentials || this.options.auth;
1758
- if (credentials) {
1759
- const { login, password } = credentials;
1760
- const str = unescape(encodeURIComponent(`${login}:${password}`));
1761
- // @ts-ignore
1762
- {
1763
- return window.btoa(str);
1764
- }
1515
+ let data;
1516
+ if (options.file) {
1517
+ data = new FormData();
1518
+ data.append("file", options.file);
1519
+ if (options.data) {
1520
+ for (const d in options.data) {
1521
+ data.append(d, data[d]);
1765
1522
  }
1523
+ }
1524
+ } else {
1525
+ data = options.data ? typeof options.data === "string" ? options.data : JSON.stringify(options.data) : null;
1766
1526
  }
1767
- /** Stop all api requests */
1768
- abort() {
1769
- for (const req of this.activeRequests) {
1770
- req.cancel();
1771
- }
1772
- this.activeRequests = [];
1527
+ if (onCancel) {
1528
+ onCancel(() => {
1529
+ xhr.abort();
1530
+ });
1773
1531
  }
1774
- getActiveApiRequests() {
1775
- return [...this.activeRequests];
1532
+ xhr.send(data);
1533
+ };
1534
+ }
1535
+
1536
+ var __defProp = Object.defineProperty;
1537
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1538
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1539
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1540
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1541
+ var __spreadValues = (a, b) => {
1542
+ for (var prop in b || (b = {}))
1543
+ if (__hasOwnProp.call(b, prop))
1544
+ __defNormalProp(a, prop, b[prop]);
1545
+ if (__getOwnPropSymbols)
1546
+ for (var prop of __getOwnPropSymbols(b)) {
1547
+ if (__propIsEnum.call(b, prop))
1548
+ __defNormalProp(a, prop, b[prop]);
1549
+ }
1550
+ return a;
1551
+ };
1552
+ var __publicField = (obj, key, value) => {
1553
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1554
+ return value;
1555
+ };
1556
+ let ID = 0;
1557
+ class NgwConnector {
1558
+ constructor(options) {
1559
+ this.options = options;
1560
+ __publicField(this, "id", ID++);
1561
+ __publicField(this, "emitter", new EventEmitter());
1562
+ __publicField(this, "user");
1563
+ __publicField(this, "resources");
1564
+ __publicField(this, "routeStr", "/api/component/pyramid/route");
1565
+ __publicField(this, "activeRequests", []);
1566
+ __publicField(this, "requestTransform");
1567
+ const exist = findConnector(options);
1568
+ if (exist) {
1569
+ return exist;
1570
+ } else {
1571
+ if (this.options.route) {
1572
+ this.routeStr = this.options.route;
1573
+ }
1574
+ if (this.options.requestTransform) {
1575
+ this.requestTransform = this.options.requestTransform;
1576
+ }
1577
+ this.resources = new ResourcesControl(this);
1578
+ addConnector(this);
1776
1579
  }
1777
- /**
1778
- * Send request to NGW api router.
1779
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1780
- * @param params - Request item params or query params
1781
- * @param requestOptions - Request options
1782
- *
1783
- * @example
1784
- * ```javascript
1785
- *
1786
- * // there is such an NGW route item
1787
- * // "feature_layer.feature.item": [
1788
- * // "/api/resource/{0}/feature/{1}",
1789
- * // "id",
1790
- * // "fid"
1791
- * // ],
1792
- *
1793
- * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
1794
- * connector.apiRequest('feature_layer.feature.item', {
1795
- * // request params for {0} and {1}
1796
- * 'id': 2011,
1797
- * 'fid': 101,
1798
- * // query params
1799
- * 'srs': 4326,
1800
- * 'geom_format': 'geojson',
1801
- * }, { method: 'GET' });
1802
- * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
1803
- *
1804
- * ```
1805
- */
1806
- apiRequest(name, params_ = {}, requestOptions = {}) {
1807
- var _a, _b;
1808
- const { method, headers, withCredentials, responseType } = requestOptions;
1809
- params_ = (_a = requestOptions.params) !== null && _a !== void 0 ? _a : params_;
1810
- const params = objectRemoveEmpty(params_);
1811
- const makeApiRequest = () => apiRequest({ name, params, requestOptions, connector: this });
1812
- if (requestOptions.cache && method === 'GET') {
1813
- const cache = new Cache();
1814
- return cache.add(name, makeApiRequest, {
1815
- params,
1816
- ...objectRemoveEmpty({
1817
- headers,
1818
- withCredentials,
1819
- responseType,
1820
- baseUrl: this.options.baseUrl,
1821
- userId: (_b = this.user) === null || _b === void 0 ? void 0 : _b.id,
1822
- }),
1823
- });
1580
+ }
1581
+ static create(options) {
1582
+ return new this(options);
1583
+ }
1584
+ setRequestTransform(requestTransform) {
1585
+ this.requestTransform = requestTransform;
1586
+ }
1587
+ /**
1588
+ * Fast way to specify the connection address to NextGIS Web.
1589
+ * The current connection will be severed.
1590
+ * @param baseUrl - NGW url
1591
+ */
1592
+ setNgw(baseUrl) {
1593
+ this.logout();
1594
+ this.options.baseUrl = baseUrl;
1595
+ addConnector(this);
1596
+ }
1597
+ /**
1598
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
1599
+ * @remarks
1600
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1601
+ * Can be used to check connection.
1602
+ * @example
1603
+ * ```javascript
1604
+ * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1605
+ * connector.connect()
1606
+ * .then(() => console.log('Ok'))
1607
+ * .catch((er) => console.log('Connection problem', er));
1608
+ * ```
1609
+ */
1610
+ connect() {
1611
+ const cache = new Cache();
1612
+ const auth = this.options.auth;
1613
+ const makeConnect = () => new CancelablePromise((resolve, reject) => {
1614
+ const makeQuery = () => {
1615
+ return this.makeQuery(this.routeStr, {}, {}).then((route) => {
1616
+ resolve(route);
1617
+ }).catch((er) => {
1618
+ reject(er);
1619
+ });
1620
+ };
1621
+ if (auth) {
1622
+ const { login, password } = auth;
1623
+ if (login && password) {
1624
+ return this._login({ login, password }).then(() => {
1625
+ return makeQuery();
1626
+ }).catch((er) => reject(er));
1824
1627
  }
1825
- return makeApiRequest();
1826
- }
1827
- /**
1828
- * Shortcut method for send POST request to NGW.
1829
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1830
- * @param options - Request options
1831
- * @param params - Request item params or query params
1832
- *
1833
- * @example
1834
- * ```javascript
1835
- * connector.post('resource.collection', { data: POST_PAYLOAD })
1836
- * .then((newResource) => console.log(newResource))
1837
- * .catch((error) => console.warn(error));
1838
- * ```
1839
- */
1840
- post(name, options, params) {
1841
- options = options || {};
1842
- options.method = 'POST';
1843
- return this.apiRequest(name, params, options);
1628
+ }
1629
+ return makeQuery();
1630
+ });
1631
+ return cache.add("route", makeConnect, {
1632
+ id: this.id,
1633
+ auth,
1634
+ baseUrl: this.options.baseUrl
1635
+ });
1636
+ }
1637
+ /**
1638
+ * Quick way to change NextGIS Web user.
1639
+ * @param credentials - New user credentials
1640
+ */
1641
+ login(credentials, options) {
1642
+ this.logout();
1643
+ addConnector(this);
1644
+ return this._login(credentials, options);
1645
+ }
1646
+ /**
1647
+ * Disconnecting a user. Aborting all current requests
1648
+ */
1649
+ logout() {
1650
+ this.abort();
1651
+ removeConnector(this);
1652
+ this.options.auth = void 0;
1653
+ this.user = void 0;
1654
+ this.emitter.emit("logout");
1655
+ this.resources.cache.clean();
1656
+ }
1657
+ getUserInfo(credentials, options) {
1658
+ if (this.user && this.user.id) {
1659
+ return CancelablePromise.resolve(this.user);
1660
+ }
1661
+ if (credentials) {
1662
+ this.options.auth = credentials;
1663
+ }
1664
+ const options_ = __spreadValues({
1665
+ headers: this.getAuthorizationHeaders(credentials)
1666
+ }, options);
1667
+ return this.makeQuery(
1668
+ "/api/component/auth/current_user",
1669
+ {},
1670
+ options_
1671
+ );
1672
+ }
1673
+ /**
1674
+ * Obtaining the required Headers for authentication of requests in the NGW.
1675
+ */
1676
+ getAuthorizationHeaders(credentials) {
1677
+ const client = this.makeClientId(credentials);
1678
+ if (client) {
1679
+ return {
1680
+ Authorization: "Basic " + client
1681
+ };
1844
1682
  }
1845
- /**
1846
- * Shortcut method for send GET request to NGW.
1847
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1848
- * @param options - Request options
1849
- * @param params - Request item params or query params
1850
- */
1851
- get(name, options, params) {
1852
- options = options || {};
1853
- options.method = 'GET';
1854
- return this.apiRequest(name, params, options);
1683
+ }
1684
+ makeClientId(credentials) {
1685
+ credentials = credentials || this.options.auth;
1686
+ if (credentials) {
1687
+ const { login, password } = credentials;
1688
+ const str = unescape(encodeURIComponent(`${login}:${password}`));
1689
+ {
1690
+ return window.btoa(str);
1691
+ }
1855
1692
  }
1856
- /**
1857
- * Shortcut method for send PATCH request to NGW.
1858
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1859
- * @param options - Request options
1860
- * @param params - Request item params or query params
1861
- */
1862
- patch(name, options, params) {
1863
- options = options || {};
1864
- options.method = 'PATCH';
1865
- return this.apiRequest(name, params, options);
1693
+ }
1694
+ /** Stop all api requests */
1695
+ abort() {
1696
+ for (const req of this.activeRequests) {
1697
+ req.cancel();
1866
1698
  }
1867
- /**
1868
- * Shortcut method for send PUT request to NGW.
1869
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1870
- * @param options - Request options
1871
- * @param params - Request item params or query params
1872
- */
1873
- put(name, options, params) {
1874
- options = options || {};
1875
- options.method = 'PUT';
1876
- return this.apiRequest(name, params, options);
1699
+ this.activeRequests = [];
1700
+ }
1701
+ getActiveApiRequests() {
1702
+ return [...this.activeRequests];
1703
+ }
1704
+ /**
1705
+ * Send request to NGW api router.
1706
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1707
+ * @param params - Request item params or query params
1708
+ * @param requestOptions - Request options
1709
+ *
1710
+ * @example
1711
+ * ```javascript
1712
+ *
1713
+ * // there is such an NGW route item
1714
+ * // "feature_layer.feature.item": [
1715
+ * // "/api/resource/{0}/feature/{1}",
1716
+ * // "id",
1717
+ * // "fid"
1718
+ * // ],
1719
+ *
1720
+ * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
1721
+ * connector.apiRequest('feature_layer.feature.item', {
1722
+ * // request params for {0} and {1}
1723
+ * 'id': 2011,
1724
+ * 'fid': 101,
1725
+ * // query params
1726
+ * 'srs': 4326,
1727
+ * 'geom_format': 'geojson',
1728
+ * }, { method: 'GET' });
1729
+ * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
1730
+ *
1731
+ * ```
1732
+ */
1733
+ apiRequest(name, params_ = {}, requestOptions = {}) {
1734
+ var _a, _b;
1735
+ const { method, headers, withCredentials, responseType } = requestOptions;
1736
+ params_ = (_a = requestOptions.params) != null ? _a : params_;
1737
+ const params = objectRemoveEmpty(params_);
1738
+ const makeApiRequest = () => apiRequest({ name, params, requestOptions, connector: this });
1739
+ if (requestOptions.cache && method === "GET") {
1740
+ const cache = new Cache();
1741
+ return cache.add(name, makeApiRequest, __spreadValues({
1742
+ params
1743
+ }, objectRemoveEmpty({
1744
+ headers,
1745
+ withCredentials,
1746
+ responseType,
1747
+ baseUrl: this.options.baseUrl,
1748
+ userId: (_b = this.user) == null ? void 0 : _b.id
1749
+ })));
1750
+ }
1751
+ return makeApiRequest();
1752
+ }
1753
+ /**
1754
+ * Shortcut method for send POST request to NGW.
1755
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1756
+ * @param options - Request options
1757
+ * @param params - Request item params or query params
1758
+ *
1759
+ * @example
1760
+ * ```javascript
1761
+ * connector.post('resource.collection', { data: POST_PAYLOAD })
1762
+ * .then((newResource) => console.log(newResource))
1763
+ * .catch((error) => console.warn(error));
1764
+ * ```
1765
+ */
1766
+ post(name, options, params) {
1767
+ options = options || {};
1768
+ options.method = "POST";
1769
+ return this.apiRequest(
1770
+ name,
1771
+ params,
1772
+ options
1773
+ );
1774
+ }
1775
+ /**
1776
+ * Shortcut method for send GET request to NGW.
1777
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1778
+ * @param options - Request options
1779
+ * @param params - Request item params or query params
1780
+ */
1781
+ get(name, options, params) {
1782
+ options = options || {};
1783
+ options.method = "GET";
1784
+ return this.apiRequest(
1785
+ name,
1786
+ params,
1787
+ options
1788
+ );
1789
+ }
1790
+ /**
1791
+ * Shortcut method for send PATCH request to NGW.
1792
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1793
+ * @param options - Request options
1794
+ * @param params - Request item params or query params
1795
+ */
1796
+ patch(name, options, params) {
1797
+ options = options || {};
1798
+ options.method = "PATCH";
1799
+ return this.apiRequest(
1800
+ name,
1801
+ params,
1802
+ options
1803
+ );
1804
+ }
1805
+ /**
1806
+ * Shortcut method for send PUT request to NGW.
1807
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1808
+ * @param options - Request options
1809
+ * @param params - Request item params or query params
1810
+ */
1811
+ put(name, options, params) {
1812
+ options = options || {};
1813
+ options.method = "PUT";
1814
+ return this.apiRequest(
1815
+ name,
1816
+ params,
1817
+ options
1818
+ );
1819
+ }
1820
+ /**
1821
+ * Shortcut method for send DELETE request to NGW.
1822
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1823
+ * @param options - Request options
1824
+ * @param params - Request item params or query params
1825
+ */
1826
+ delete(name, options, params) {
1827
+ options = options || {};
1828
+ options.method = "DELETE";
1829
+ return this.apiRequest(
1830
+ name,
1831
+ params,
1832
+ options
1833
+ );
1834
+ }
1835
+ /**
1836
+ * Send request to NGW.
1837
+ * @param url - URL address to NGW
1838
+ * @param params - Query params
1839
+ * @param options - Request options
1840
+ */
1841
+ makeQuery(url, params, options = {}) {
1842
+ url = (this.options.baseUrl ? this.options.baseUrl : "") + url;
1843
+ if (url) {
1844
+ if (params) {
1845
+ url = template(url, params);
1846
+ }
1847
+ url = encodeURI(fixUrlStr(url));
1848
+ return this._loadData(url, options);
1849
+ } else {
1850
+ throw new Error("Empty `url` not allowed");
1877
1851
  }
1878
- /**
1879
- * Shortcut method for send DELETE request to NGW.
1880
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1881
- * @param options - Request options
1882
- * @param params - Request item params or query params
1883
- */
1884
- delete(name, options, params) {
1852
+ }
1853
+ // -------------------------------------------------------------------------
1854
+ // Resource Methods
1855
+ // -------------------------------------------------------------------------
1856
+ /**
1857
+ * {@link ResourcesControl.getOne}
1858
+ */
1859
+ getResource(resource, requestOptions) {
1860
+ return this.resources.getOne(resource, requestOptions);
1861
+ }
1862
+ /**
1863
+ * {@link ResourcesControl.getOneOrFail}
1864
+ */
1865
+ getResourceOrFail(resource, requestOptions) {
1866
+ return this.resources.getOneOrFail(resource, requestOptions);
1867
+ }
1868
+ /**
1869
+ * @deprecated - use {@link getResource}
1870
+ */
1871
+ getResourceBy(resource) {
1872
+ return this.resources.getOne(resource);
1873
+ }
1874
+ /**
1875
+ * @deprecated - use {@link getResource}
1876
+ */
1877
+ getResourceByKeyname(keyname) {
1878
+ return this.resources.getOne(keyname);
1879
+ }
1880
+ /**
1881
+ * @deprecated - use {@link getResource}
1882
+ */
1883
+ getResourceById(id) {
1884
+ return this.resources.getOne(id);
1885
+ }
1886
+ /**
1887
+ * {@link ResourcesControl.getId}
1888
+ */
1889
+ getResourceId(resource, requestOptions) {
1890
+ return this.resources.getId(resource, requestOptions);
1891
+ }
1892
+ /**
1893
+ * {@link ResourcesControl.getIdOrFail}
1894
+ */
1895
+ getResourceIdOrFail(resource, requestOptions) {
1896
+ return this.resources.getIdOrFail(resource, requestOptions);
1897
+ }
1898
+ /**
1899
+ * {@link ResourcesControl.getMany}
1900
+ */
1901
+ getResourcesBy(resource, requestOptions) {
1902
+ return this.resources.getMany(resource, requestOptions);
1903
+ }
1904
+ /**
1905
+ * {@link ResourcesControl.getParent}
1906
+ */
1907
+ getResourceParent(resource, requestOptions) {
1908
+ return this.resources.getParent(resource, requestOptions);
1909
+ }
1910
+ /**
1911
+ * {@link ResourcesControl.getChildrenOf}
1912
+ */
1913
+ getResourceChildren(resource, requestOptions) {
1914
+ return this.resources.getChildrenOf(resource, requestOptions);
1915
+ }
1916
+ /**
1917
+ * {@link ResourcesControl.update}
1918
+ */
1919
+ updateResource(resource, data) {
1920
+ return this.resources.update(resource, data);
1921
+ }
1922
+ /**
1923
+ * {@link ResourcesControl.delete}
1924
+ */
1925
+ deleteResource(resource) {
1926
+ return this.resources.delete(resource);
1927
+ }
1928
+ /**
1929
+ * @internal
1930
+ */
1931
+ _loadData(url, options) {
1932
+ options.responseType = options.responseType || "json";
1933
+ if (options.signal && options.signal.aborted) {
1934
+ return CancelablePromise.reject(new CancelablePromise.CancelError());
1935
+ }
1936
+ const request = new CancelablePromise((resolve, reject, onCancel) => {
1937
+ if (this.user) {
1885
1938
  options = options || {};
1886
- options.method = 'DELETE';
1887
- return this.apiRequest(name, params, options);
1888
- }
1889
- /**
1890
- * Send request to NGW.
1891
- * @param url - URL address to NGW
1892
- * @param params - Query params
1893
- * @param options - Request options
1894
- */
1895
- makeQuery(url, params, options = {}) {
1896
- url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
1897
- if (url) {
1898
- if (params) {
1899
- url = template(url, params);
1900
- }
1901
- url = encodeURI(fixUrlStr(url));
1902
- return this._loadData(url, options);
1903
- }
1904
- else {
1905
- throw new Error('Empty `url` not allowed');
1906
- }
1907
- }
1908
- // -------------------------------------------------------------------------
1909
- // Resource Methods
1910
- // -------------------------------------------------------------------------
1911
- /**
1912
- * {@link ResourcesControl.getOne}
1913
- */
1914
- getResource(resource, requestOptions) {
1915
- return this.resources.getOne(resource, requestOptions);
1916
- }
1917
- /**
1918
- * {@link ResourcesControl.getOneOrFail}
1919
- */
1920
- getResourceOrFail(resource, requestOptions) {
1921
- return this.resources.getOneOrFail(resource, requestOptions);
1922
- }
1923
- /**
1924
- * @deprecated - use {@link getResource}
1925
- */
1926
- getResourceBy(resource) {
1927
- return this.resources.getOne(resource);
1928
- }
1929
- /**
1930
- * @deprecated - use {@link getResource}
1931
- */
1932
- getResourceByKeyname(keyname) {
1933
- return this.resources.getOne(keyname);
1934
- }
1935
- /**
1936
- * @deprecated - use {@link getResource}
1937
- */
1938
- getResourceById(id) {
1939
- return this.resources.getOne(id);
1940
- }
1941
- /**
1942
- * {@link ResourcesControl.getId}
1943
- */
1944
- getResourceId(resource, requestOptions) {
1945
- return this.resources.getId(resource, requestOptions);
1946
- }
1947
- /**
1948
- * {@link ResourcesControl.getIdOrFail}
1949
- */
1950
- getResourceIdOrFail(resource, requestOptions) {
1951
- return this.resources.getIdOrFail(resource, requestOptions);
1952
- }
1953
- /**
1954
- * {@link ResourcesControl.getMany}
1955
- */
1956
- getResourcesBy(resource, requestOptions) {
1957
- return this.resources.getMany(resource, requestOptions);
1958
- }
1959
- /**
1960
- * {@link ResourcesControl.getParent}
1961
- */
1962
- getResourceParent(resource, requestOptions) {
1963
- return this.resources.getParent(resource, requestOptions);
1964
- }
1965
- /**
1966
- * {@link ResourcesControl.getChildrenOf}
1967
- */
1968
- getResourceChildren(resource, requestOptions) {
1969
- return this.resources.getChildrenOf(resource, requestOptions);
1970
- }
1971
- /**
1972
- * {@link ResourcesControl.update}
1973
- */
1974
- updateResource(resource, data) {
1975
- return this.resources.update(resource, data);
1976
- }
1977
- /**
1978
- * {@link ResourcesControl.delete}
1979
- */
1980
- deleteResource(resource) {
1981
- return this.resources.delete(resource);
1982
- }
1983
- /**
1984
- * @internal
1985
- */
1986
- _loadData(url, options) {
1987
- options.responseType = options.responseType || 'json';
1988
- const request = new CancelablePromise((resolve, reject, onCancel) => {
1989
- if (this.user) {
1990
- options = options || {};
1991
- // options.withCredentials = true;
1992
- options.headers = {
1993
- ...this.getAuthorizationHeaders(),
1994
- ...options.headers,
1995
- };
1996
- }
1997
- if (this.requestTransform) {
1998
- const [transUrl, transOptions] = this.requestTransform(url, options);
1999
- url = transUrl;
2000
- options = transOptions;
2001
- }
2002
- loadData(url, resolve, options, reject, onCancel);
2003
- })
2004
- .then((resp) => {
2005
- this._cleanActiveRequests(request);
2006
- return resp;
2007
- })
2008
- .catch((httpError) => {
2009
- this._cleanActiveRequests(request);
2010
- if (httpError instanceof CancelablePromise.CancelError) ;
2011
- else {
2012
- // @ts-ignore
2013
- {
2014
- console.warn('DEV WARN', httpError);
2015
- }
2016
- const er = this._handleHttpError(httpError);
2017
- if (er) {
2018
- throw er;
2019
- }
2020
- }
2021
- });
2022
- if (options.signal &&
2023
- typeof options.signal.addEventListener === 'function') {
2024
- options.signal.addEventListener('abort', () => {
2025
- request.cancel();
2026
- this._cleanActiveRequests(request);
2027
- });
2028
- }
2029
- this.activeRequests.push(request);
2030
- return request;
2031
- }
2032
- _login(credentials, options) {
2033
- return this.getUserInfo(credentials, options)
2034
- .then((data) => {
2035
- this.user = data;
2036
- this.emitter.emit('login', data);
2037
- return data;
2038
- })
2039
- .catch((er) => {
2040
- this.emitter.emit('login:error', er);
2041
- throw er;
2042
- });
2043
- }
2044
- _cleanActiveRequests(request) {
2045
- const activeRequestIndex = this.activeRequests.indexOf(request);
2046
- if (activeRequestIndex !== -1) {
2047
- this.activeRequests.splice(activeRequestIndex, 1);
1939
+ options.headers = __spreadValues(__spreadValues({}, this.getAuthorizationHeaders()), options.headers);
1940
+ }
1941
+ if (this.requestTransform) {
1942
+ const [transUrl, transOptions] = this.requestTransform(url, options);
1943
+ url = transUrl;
1944
+ options = transOptions;
1945
+ }
1946
+ loadData(url, resolve, options, reject, onCancel);
1947
+ }).then((resp) => {
1948
+ this._cleanActiveRequests(request);
1949
+ return resp;
1950
+ }).catch((httpError) => {
1951
+ this._cleanActiveRequests(request);
1952
+ if (httpError instanceof CancelablePromise.CancelError) ; else {
1953
+ {
1954
+ console.warn("DEV WARN", httpError);
1955
+ }
1956
+ const er = this._handleHttpError(httpError);
1957
+ if (er) {
1958
+ throw er;
2048
1959
  }
1960
+ }
1961
+ });
1962
+ if (options.signal && typeof options.signal.addEventListener === "function") {
1963
+ options.signal.addEventListener("abort", () => {
1964
+ request.cancel();
1965
+ this._cleanActiveRequests(request);
1966
+ });
1967
+ }
1968
+ this.activeRequests.push(request);
1969
+ return request;
1970
+ }
1971
+ _login(credentials, options) {
1972
+ return this.getUserInfo(credentials, options).then((data) => {
1973
+ this.user = data;
1974
+ this.emitter.emit("login", data);
1975
+ return data;
1976
+ }).catch((er) => {
1977
+ this.emitter.emit("login:error", er);
1978
+ throw er;
1979
+ });
1980
+ }
1981
+ _cleanActiveRequests(request) {
1982
+ const activeRequestIndex = this.activeRequests.indexOf(request);
1983
+ if (activeRequestIndex !== -1) {
1984
+ this.activeRequests.splice(activeRequestIndex, 1);
2049
1985
  }
2050
- _handleHttpError(er) {
2051
- if (er) {
2052
- if (er instanceof NgwError) {
2053
- if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
2054
- throw new ResourceNotFoundError(er);
2055
- }
2056
- else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
2057
- throw new InsufficientPermissionsError(er);
2058
- }
2059
- }
1986
+ }
1987
+ _handleHttpError(er) {
1988
+ if (er) {
1989
+ if (er instanceof NgwError) {
1990
+ if (er.exception === "nextgisweb.resource.exception.ResourceNotFound") {
1991
+ throw new ResourceNotFoundError(er);
1992
+ } else if (er.exception === "nextgisweb.core.exception.InsufficientPermissions") {
1993
+ throw new InsufficientPermissionsError(er);
2060
1994
  }
2061
- return er;
1995
+ }
2062
1996
  }
1997
+ return er;
1998
+ }
2063
1999
  }
2064
- NgwConnector$1.errors = {
2065
- NgwError,
2066
- ResourceNotFoundError,
2067
- };
2068
-
2069
- /**
2070
- * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
2071
- *
2072
- * @remarks
2073
- * Make sure CORS is registered in the {@link https://docs.nextgis.com/docs_ngcom/source/CORS.html | NextGIS Web settings } to be able to send requests.
2074
- *
2075
- * @packageDocumentation
2076
- * @module ngw-connector
2077
- */
2078
- var NgwConnector = NgwConnector$1;
2000
+ __publicField(NgwConnector, "errors", {
2001
+ NgwError,
2002
+ ResourceNotFoundError
2003
+ });
2079
2004
 
2080
2005
  export { NgwConnector as default };
2081
2006
  //# sourceMappingURL=ngw-connector.esm-browser.js.map