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