@nextgis/ngw-connector 1.16.8 → 1.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /** Bundle of @nextgis/ngw-connector; version: 1.16.8; author: NextGIS */
1
+ /** Bundle of @nextgis/ngw-connector; version: 1.18.3; author: NextGIS */
2
2
  'use strict';
3
3
 
4
4
  var events = require('events');
@@ -11,1152 +11,1008 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
11
11
  var CancelablePromise__default = /*#__PURE__*/_interopDefaultLegacy(CancelablePromise);
12
12
  var Cache__default = /*#__PURE__*/_interopDefaultLegacy(Cache);
13
13
 
14
- /******************************************************************************
15
- Copyright (c) Microsoft Corporation.
16
-
17
- Permission to use, copy, modify, and/or distribute this software for any
18
- purpose with or without fee is hereby granted.
19
-
20
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
21
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
22
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
23
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
24
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
25
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
26
- PERFORMANCE OF THIS SOFTWARE.
27
- ***************************************************************************** */
28
- /* global Reflect, Promise */
29
-
30
- var extendStatics = function(d, b) {
31
- extendStatics = Object.setPrototypeOf ||
32
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
34
- return extendStatics(d, b);
35
- };
36
-
37
- function __extends(d, b) {
38
- if (typeof b !== "function" && b !== null)
39
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
40
- extendStatics(d, b);
41
- function __() { this.constructor = d; }
42
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43
- }
44
-
45
- var __assign = function() {
46
- __assign = Object.assign || function __assign(t) {
47
- for (var s, i = 1, n = arguments.length; i < n; i++) {
48
- s = arguments[i];
49
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
50
- }
51
- return t;
52
- };
53
- return __assign.apply(this, arguments);
54
- };
55
-
56
- function __rest(s, e) {
57
- var t = {};
58
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
59
- t[p] = s[p];
60
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
61
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
62
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
63
- t[p[i]] = s[p[i]];
64
- }
65
- return t;
66
- }
67
-
68
- function __awaiter(thisArg, _arguments, P, generator) {
69
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
70
- return new (P || (P = Promise))(function (resolve, reject) {
71
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
72
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
73
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
74
- step((generator = generator.apply(thisArg, _arguments || [])).next());
75
- });
76
- }
77
-
78
- function __generator(thisArg, body) {
79
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
80
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
81
- function verb(n) { return function (v) { return step([n, v]); }; }
82
- function step(op) {
83
- if (f) throw new TypeError("Generator is already executing.");
84
- while (_) try {
85
- 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;
86
- if (y = 0, t) op = [op[0] & 2, t.value];
87
- switch (op[0]) {
88
- case 0: case 1: t = op; break;
89
- case 4: _.label++; return { value: op[1], done: false };
90
- case 5: _.label++; y = op[1]; op = [0]; continue;
91
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
92
- default:
93
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
94
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
95
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
96
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
97
- if (t[2]) _.ops.pop();
98
- _.trys.pop(); continue;
99
- }
100
- op = body.call(thisArg, _);
101
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
102
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
103
- }
104
- }
105
-
106
- function __spreadArray(to, from, pack) {
107
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
108
- if (ar || !(i in from)) {
109
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
110
- ar[i] = from[i];
111
- }
112
- }
113
- return to.concat(ar || Array.prototype.slice.call(from));
14
+ /**
15
+ * Thrown when...
16
+ */
17
+ class NgwError extends Error {
18
+ constructor(er) {
19
+ super();
20
+ this.name = 'NgwError';
21
+ Object.assign(this, er);
22
+ Object.setPrototypeOf(this, NgwError.prototype);
23
+ }
114
24
  }
115
25
 
116
- /**
117
- * Thrown when...
118
- */
119
- var NgwError = /** @class */ (function (_super) {
120
- __extends(NgwError, _super);
121
- function NgwError(er) {
122
- var _this = _super.call(this) || this;
123
- _this.name = 'NgwError';
124
- Object.assign(_this, er);
125
- Object.setPrototypeOf(_this, NgwError.prototype);
126
- return _this;
127
- }
128
- return NgwError;
129
- }(Error));
130
-
131
- function isError(error) {
132
- if (utils.isObject(error)) {
133
- return error.status_code && error.exception && error.title;
134
- }
135
- return false;
26
+ function isError(error) {
27
+ if (utils.isObject(error)) {
28
+ return error.status_code && error.exception && error.title;
29
+ }
30
+ return false;
136
31
  }
137
32
 
138
- function isObject(val) {
139
- return Object.prototype.toString.call(val) === '[object Object]';
33
+ function isObject(val) {
34
+ return Object.prototype.toString.call(val) === '[object Object]';
140
35
  }
141
36
 
142
- var loadData;
143
- // @ts-ignore
144
- {
145
- var url_1 = require('url');
146
- var http_1 = require('http');
147
- var https_1 = require('https');
148
- var FormData_1 = require('form-data');
149
- var adapterFor_1 = function (inputUrl) {
150
- var adapters = {
151
- 'http:': http_1,
152
- 'https:': https_1,
153
- };
154
- var protocol = url_1.parse(inputUrl).protocol || 'https:';
155
- return adapters[protocol];
156
- };
157
- loadData = function (url, callback, options, error, onCancel) {
158
- if (options === void 0) { options = {}; }
159
- var file = options.file, headers = options.headers, method = options.method, data = options.data, responseType = options.responseType;
160
- var request = new Promise(function (resolve, reject) {
161
- var adapter = adapterFor_1(url);
162
- if (adapter) {
163
- var requestOpt = {
164
- headers: headers || {},
165
- method: method,
166
- };
167
- var body = typeof data === 'string' ? data : JSON.stringify(data);
168
- // https://stackoverflow.com/questions/35589109/node-http-delete-request-no-longer-works-after-upgrading-from-0-10-40
169
- var form = void 0;
170
- var uploadedFile = file;
171
- if (file) {
172
- var fileMeta = {};
173
- if (isObject(file) &&
174
- 'file' in file &&
175
- ('filename' in file || 'name' in file)) {
176
- var _a = file, file_ = _a.file, name_1 = _a.name, fileMeta_ = __rest(_a, ["file", "name"]);
177
- if (name_1 && !fileMeta_.filename) {
178
- fileMeta_.filename = name_1;
179
- }
180
- Object.assign(fileMeta, fileMeta_);
181
- uploadedFile = file_;
182
- }
183
- form = new FormData_1();
184
- form.append('file', uploadedFile, fileMeta);
185
- if (data) {
186
- for (var d in data) {
187
- form.append(d, data[d]);
188
- }
189
- }
190
- Object.assign(requestOpt.headers, __assign({}, form.getHeaders()));
191
- }
192
- if (body !== undefined) {
193
- Object.assign(requestOpt.headers, {
194
- 'content-type': 'application/json',
195
- 'content-length': Buffer.byteLength(body),
196
- });
197
- }
198
- var req_1 = adapter.request(url, requestOpt, function (resp) {
199
- var data = '';
200
- resp.on('data', function (chunk) {
201
- data += chunk;
202
- });
203
- resp.on('end', function () {
204
- if (data) {
205
- if (responseType === 'blob') {
206
- resolve(data);
207
- }
208
- else {
209
- var json = void 0;
210
- try {
211
- json = JSON.parse(data);
212
- if (json && json.status_code && json.status_code) {
213
- reject(json.message);
214
- }
215
- }
216
- catch (er) {
217
- reject(er);
218
- }
219
- if (json !== undefined) {
220
- if (isError(json)) {
221
- reject('extractError(json)');
222
- }
223
- else {
224
- resolve(json);
225
- }
226
- }
227
- }
228
- }
229
- reject('no data');
230
- });
231
- });
232
- if (form) {
233
- form.pipe(req_1);
234
- }
235
- req_1.on('error', function (err) {
236
- reject(err);
237
- });
238
- if (body) {
239
- req_1.write(body);
240
- }
241
- onCancel(function () {
242
- req_1.abort();
243
- });
244
- req_1.end();
245
- }
246
- else {
247
- throw new Error("Given URL '".concat(url, "' is not correct"));
248
- }
249
- });
250
- return request
251
- .then(function (data) {
252
- if (callback) {
253
- callback(data);
254
- }
255
- return data;
256
- })
257
- .catch(function (er) {
258
- if (error) {
259
- error(er);
260
- }
261
- else {
262
- throw new Error(er);
263
- }
264
- });
265
- };
37
+ let loadData;
38
+ // @ts-ignore
39
+ {
40
+ const url = require('url');
41
+ const http = require('http');
42
+ const https = require('https');
43
+ const FormData = require('form-data');
44
+ const adapterFor = (inputUrl) => {
45
+ const adapters = {
46
+ 'http:': http,
47
+ 'https:': https,
48
+ };
49
+ const protocol = url.parse(inputUrl).protocol || 'https:';
50
+ return adapters[protocol];
51
+ };
52
+ loadData = (url, callback, options = {}, error, onCancel) => {
53
+ const { file, headers, method, data, responseType } = options;
54
+ const request = new Promise((resolve, reject) => {
55
+ const adapter = adapterFor(url);
56
+ if (adapter) {
57
+ const requestOpt = {
58
+ headers: headers || {},
59
+ method,
60
+ };
61
+ const body = typeof data === 'string' ? data : JSON.stringify(data);
62
+ // https://stackoverflow.com/questions/35589109/node-http-delete-request-no-longer-works-after-upgrading-from-0-10-40
63
+ let form;
64
+ let uploadedFile = file;
65
+ if (file) {
66
+ const fileMeta = {};
67
+ if (isObject(file) &&
68
+ 'file' in file &&
69
+ ('filename' in file || 'name' in file)) {
70
+ const { file: file_, name, ...fileMeta_ } = file;
71
+ if (name && !fileMeta_.filename) {
72
+ fileMeta_.filename = name;
73
+ }
74
+ Object.assign(fileMeta, fileMeta_);
75
+ uploadedFile = file_;
76
+ }
77
+ form = new FormData();
78
+ form.append('file', uploadedFile, fileMeta);
79
+ if (data) {
80
+ for (const d in data) {
81
+ form.append(d, data[d]);
82
+ }
83
+ }
84
+ Object.assign(requestOpt.headers, {
85
+ // 'content-length': form.getLengthSync(),
86
+ ...form.getHeaders(),
87
+ });
88
+ }
89
+ if (body !== undefined) {
90
+ Object.assign(requestOpt.headers, {
91
+ 'content-type': 'application/json',
92
+ 'content-length': Buffer.byteLength(body),
93
+ });
94
+ }
95
+ const req = adapter.request(url, requestOpt, (resp) => {
96
+ let data = '';
97
+ resp.on('data', (chunk) => {
98
+ data += chunk;
99
+ });
100
+ resp.on('end', () => {
101
+ if (data) {
102
+ if (responseType === 'blob') {
103
+ resolve(data);
104
+ }
105
+ else {
106
+ let json;
107
+ try {
108
+ json = JSON.parse(data);
109
+ if (json && json.status_code && json.status_code) {
110
+ reject(json.message);
111
+ }
112
+ }
113
+ catch (er) {
114
+ reject(er);
115
+ }
116
+ if (json !== undefined) {
117
+ if (isError(json)) {
118
+ reject('extractError(json)');
119
+ }
120
+ else {
121
+ resolve(json);
122
+ }
123
+ }
124
+ }
125
+ }
126
+ reject('no data');
127
+ });
128
+ });
129
+ if (form) {
130
+ form.pipe(req);
131
+ }
132
+ req.on('error', (err) => {
133
+ reject(err);
134
+ });
135
+ if (body) {
136
+ req.write(body);
137
+ }
138
+ onCancel(() => {
139
+ req.abort();
140
+ });
141
+ req.end();
142
+ }
143
+ else {
144
+ throw new Error(`Given URL '${url}' is not correct`);
145
+ }
146
+ });
147
+ return request
148
+ .then((data) => {
149
+ if (callback) {
150
+ callback(data);
151
+ }
152
+ return data;
153
+ })
154
+ .catch((er) => {
155
+ if (error) {
156
+ error(er);
157
+ }
158
+ else {
159
+ throw new Error(er);
160
+ }
161
+ });
162
+ };
266
163
  }
267
164
 
268
- // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
269
- var templateRe = /\{ *([\w_-]+) *\}/g;
270
- function template(str, data) {
271
- return str.replace(templateRe, function (s, key) {
272
- var value = data[key];
273
- if (value === undefined) {
274
- throw new Error('No value provided for letiable ' + s);
275
- }
276
- else if (typeof value === 'function') {
277
- value = value(data);
278
- }
279
- return value;
280
- });
165
+ // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
166
+ const templateRe = /\{ *([\w_-]+) *\}/g;
167
+ function template(str, data) {
168
+ return str.replace(templateRe, (s, key) => {
169
+ let value = data[key];
170
+ if (value === undefined) {
171
+ throw new Error('No value provided for letiable ' + s);
172
+ }
173
+ else if (typeof value === 'function') {
174
+ value = value(data);
175
+ }
176
+ return value;
177
+ });
281
178
  }
282
179
 
283
- function apiRequest(opt) {
284
- var params = opt.params;
285
- return new CancelablePromise__default(function (resolve, reject) {
286
- opt.connector
287
- .connect()
288
- .then(function (apiItems) {
289
- var apiItem = apiItems && apiItems[opt.name];
290
- if (apiItem) {
291
- apiItem = __spreadArray([], apiItem, true);
292
- var url = apiItem.shift();
293
- if (apiItem.length) {
294
- var replaceParams = {};
295
- for (var fry = 0; fry < apiItem.length; fry++) {
296
- var arg = apiItem[fry];
297
- replaceParams[fry] = '{' + arg + '}';
298
- if (params[arg] === undefined) {
299
- throw new Error('`' + arg + '`' + ' url api argument is not specified');
300
- }
301
- }
302
- if (url) {
303
- url = template(url, replaceParams);
304
- }
305
- }
306
- // Transfer part of the parameters from `params` to the URL string
307
- if (params) {
308
- var paramArray_1 = [];
309
- var paramList = params.paramList;
310
- if (Array.isArray(paramList)) {
311
- delete params.paramList;
312
- paramList.forEach(function (x) {
313
- paramArray_1.push("".concat(x[0], "=").concat(x[1]));
314
- });
315
- }
316
- for (var p in params) {
317
- if (apiItem.indexOf(p) === -1) {
318
- paramArray_1.push("".concat(p, "=").concat(params[p]));
319
- }
320
- }
321
- if (paramArray_1.length) {
322
- url = url + '?' + paramArray_1.join('&');
323
- }
324
- }
325
- if (url) {
326
- resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
327
- }
328
- else {
329
- reject(new Error('request url is not set'));
330
- }
331
- }
332
- else {
333
- resolve(undefined);
334
- }
335
- })
336
- .catch(function (er) {
337
- reject(er);
338
- });
339
- });
180
+ function apiRequest(opt) {
181
+ const params = opt.params;
182
+ return new CancelablePromise__default((resolve, reject) => {
183
+ opt.connector
184
+ .connect()
185
+ .then((apiItems) => {
186
+ let apiItem = apiItems && apiItems[opt.name];
187
+ if (apiItem) {
188
+ apiItem = [...apiItem];
189
+ let url = apiItem.shift();
190
+ if (apiItem.length) {
191
+ const replaceParams = {};
192
+ for (let fry = 0; fry < apiItem.length; fry++) {
193
+ const arg = apiItem[fry];
194
+ replaceParams[fry] = '{' + arg + '}';
195
+ if (params[arg] === undefined) {
196
+ throw new Error('`' + arg + '`' + ' url api argument is not specified');
197
+ }
198
+ }
199
+ if (url) {
200
+ url = template(url, replaceParams);
201
+ }
202
+ }
203
+ // Transfer part of the parameters from `params` to the URL string
204
+ if (params) {
205
+ const paramArray = [];
206
+ const paramList = params.paramList;
207
+ if (Array.isArray(paramList)) {
208
+ delete params.paramList;
209
+ paramList.forEach((x) => {
210
+ paramArray.push(`${x[0]}=${x[1]}`);
211
+ });
212
+ }
213
+ for (const p in params) {
214
+ if (apiItem.indexOf(p) === -1) {
215
+ paramArray.push(`${p}=${params[p]}`);
216
+ }
217
+ }
218
+ if (paramArray.length) {
219
+ url = url + '?' + paramArray.join('&');
220
+ }
221
+ }
222
+ if (url) {
223
+ resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
224
+ }
225
+ else {
226
+ reject(new Error('request url is not set'));
227
+ }
228
+ }
229
+ else {
230
+ resolve(undefined);
231
+ }
232
+ })
233
+ .catch((er) => {
234
+ reject(er);
235
+ });
236
+ });
340
237
  }
341
238
 
342
- /**
343
- * Thrown when ...
344
- */
345
- var ResourceNotFoundError = /** @class */ (function (_super) {
346
- __extends(ResourceNotFoundError, _super);
347
- function ResourceNotFoundError(obj) {
348
- var _this = _super.call(this, obj) || this;
349
- _this.name = 'ResourceNotFoundError';
350
- _this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
351
- Object.setPrototypeOf(_this, ResourceNotFoundError.prototype);
352
- return _this;
353
- }
354
- return ResourceNotFoundError;
355
- }(NgwError));
239
+ /**
240
+ * Thrown when ...
241
+ */
242
+ class ResourceNotFoundError extends NgwError {
243
+ constructor(obj) {
244
+ super(obj);
245
+ this.name = 'ResourceNotFoundError';
246
+ this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
247
+ Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
248
+ }
249
+ }
356
250
 
357
- /**
358
- * Thrown when ...
359
- */
360
- var InsufficientPermissionsError = /** @class */ (function (_super) {
361
- __extends(InsufficientPermissionsError, _super);
362
- function InsufficientPermissionsError(obj) {
363
- var _this = _super.call(this, obj) || this;
364
- _this.name = 'InsufficientPermissionsError';
365
- _this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
366
- Object.setPrototypeOf(_this, InsufficientPermissionsError.prototype);
367
- return _this;
368
- }
369
- return InsufficientPermissionsError;
370
- }(NgwError));
251
+ /**
252
+ * Thrown when ...
253
+ */
254
+ class InsufficientPermissionsError extends NgwError {
255
+ constructor(obj) {
256
+ super(obj);
257
+ this.name = 'InsufficientPermissionsError';
258
+ this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
259
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
260
+ }
261
+ }
371
262
 
372
- var CONNECTORS = [];
373
- function addConnector(connector) {
374
- CONNECTORS.push(connector);
375
- }
376
- function findConnector(options) {
377
- return CONNECTORS.find(function (x) {
378
- if (x.options.baseUrl === options.baseUrl) {
379
- if (options.auth) {
380
- if (x.options.auth) {
381
- return utils.objectDeepEqual(x.options.auth, options.auth);
382
- }
383
- }
384
- else {
385
- // if auth not in find options; use first connector with same url
386
- return true;
387
- }
388
- }
389
- });
390
- }
391
- function removeConnector(connector) {
392
- var index = CONNECTORS.indexOf(connector);
393
- if (index !== -1) {
394
- CONNECTORS.splice(index, 1);
395
- }
263
+ const CONNECTORS = [];
264
+ function addConnector(connector) {
265
+ CONNECTORS.push(connector);
266
+ }
267
+ function findConnector(options) {
268
+ return CONNECTORS.find((x) => {
269
+ if (x.options.baseUrl === options.baseUrl) {
270
+ if (options.auth) {
271
+ if (x.options.auth) {
272
+ return utils.objectDeepEqual(x.options.auth, options.auth);
273
+ }
274
+ }
275
+ else {
276
+ // if auth not in find options; use first connector with same url
277
+ return true;
278
+ }
279
+ }
280
+ });
281
+ }
282
+ function removeConnector(connector) {
283
+ const index = CONNECTORS.indexOf(connector);
284
+ if (index !== -1) {
285
+ CONNECTORS.splice(index, 1);
286
+ }
396
287
  }
397
288
 
398
- var exclude = ['description'];
399
- /**
400
- * @remarks
401
- * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
402
- *
403
- * ```
404
- * { keyname, owner_user: { id }} > { keyname, owner_user__id }
405
- * ```
406
- *
407
- * @param resource - Any property from NGW resource item
408
- */
409
- function resourceToQuery(resource, prefix) {
410
- if (prefix === void 0) { prefix = ''; }
411
- prefix = prefix ? prefix + '__' : '';
412
- var query = {};
413
- for (var _i = 0, _a = Object.entries(resource); _i < _a.length; _i++) {
414
- var _b = _a[_i], key = _b[0], value = _b[1];
415
- if (exclude.indexOf(key) === -1) {
416
- if (isObject(value)) {
417
- if (key === 'owner_user') {
418
- var children = resourceToQuery(value, key);
419
- Object.assign(query, children);
420
- }
421
- else if (key === 'parent' && 'id' in value) {
422
- query.parent_id = value.id;
423
- }
424
- }
425
- else if (utils.defined(value)) {
426
- query[prefix + key] = value;
427
- }
428
- }
429
- }
430
- return query;
289
+ const exclude = ['description'];
290
+ /**
291
+ * @remarks
292
+ * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
293
+ *
294
+ * ```
295
+ * { keyname, owner_user: { id }} > { keyname, owner_user__id }
296
+ * ```
297
+ *
298
+ * @param resource - Any property from NGW resource item
299
+ */
300
+ function resourceToQuery(resource, prefix = '') {
301
+ prefix = prefix ? prefix + '__' : '';
302
+ const query = {};
303
+ for (const [key, value] of Object.entries(resource)) {
304
+ if (exclude.indexOf(key) === -1) {
305
+ if (isObject(value)) {
306
+ if (key === 'owner_user') {
307
+ const children = resourceToQuery(value, key);
308
+ Object.assign(query, children);
309
+ }
310
+ else if (key === 'parent' && 'id' in value) {
311
+ query.parent_id = value.id;
312
+ }
313
+ }
314
+ else if (utils.defined(value)) {
315
+ query[prefix + key] = value;
316
+ }
317
+ }
318
+ }
319
+ return query;
431
320
  }
432
321
 
433
- function resourceCompare(res1, res2) {
434
- return utils.objectDeepEqual(res1, res2);
322
+ function resourceCompare(res1, res2) {
323
+ return utils.objectDeepEqual(res1, res2);
435
324
  }
436
325
 
437
- var ResourcesControl = /** @class */ (function () {
438
- function ResourcesControl(connector) {
439
- this.connector = connector;
440
- this.cache = new Cache__default();
441
- }
442
- // -------------------------------------------------------------------------
443
- // Resource Methods
444
- // -------------------------------------------------------------------------
445
- /**
446
- * Receive resource from NGW by id, keyname or search-object parameter.
447
- * @param resource - Resource id, keyname or search-object
448
- *
449
- * @remarks
450
- * Fetching resource would be cached to speed up next call
451
- */
452
- ResourcesControl.prototype.getOne = function (resource, requestOptions) {
453
- var _this = this;
454
- var cache = new Cache__default();
455
- var forCache = {};
456
- var opt = __assign(__assign({}, requestOptions), { cache: false });
457
- if (typeof resource === 'string') {
458
- forCache.keyname = resource;
459
- }
460
- else if (typeof resource === 'number') {
461
- forCache.id = resource;
462
- }
463
- else if (isObject(resource)) {
464
- if (resource.id !== undefined) {
465
- forCache.id = resource.id;
466
- }
467
- else if (resource.keyname) {
468
- forCache.keyname = resource.keyname;
469
- }
470
- }
471
- var makeRequest = function () {
472
- if (typeof resource === 'string') {
473
- return _this._fetchResourceBy({ keyname: resource }, opt);
474
- }
475
- else if (typeof resource === 'number') {
476
- return _this._fetchResourceById(resource, opt);
477
- }
478
- else if (isObject(resource)) {
479
- return _this._fetchResourceBy(resource, opt);
480
- }
481
- return CancelablePromise__default.resolve(undefined);
482
- };
483
- return cache.addFull('resource', makeRequest, forCache);
484
- };
485
- ResourcesControl.prototype.getOneOrFail = function (resource, requestOptions) {
486
- return this.getOne(resource, requestOptions).then(function (res) {
487
- if (res) {
488
- return res;
489
- }
490
- throw new ResourceNotFoundError();
491
- });
492
- };
493
- /**
494
- * A fast way to retrieve resource ID for any resource definition.
495
- * @param resource - Any available resource definition
496
- *
497
- * @remarks
498
- * There are situations when exactly the resource id is needed
499
- * (for example, to compose the correct request to the api)
500
- * then this method will come in handy to facilitate the extraction of the identifier
501
- * if the resource is specified through a keyname or other parameters.
502
- */
503
- ResourcesControl.prototype.getId = function (resource, requestOptions) {
504
- if (typeof resource === 'number') {
505
- return CancelablePromise__default.resolve(resource);
506
- }
507
- else if (typeof resource === 'string' || isObject(resource)) {
508
- return this.getOne(resource, requestOptions).then(function (res) {
509
- if (res) {
510
- return res.resource.id;
511
- }
512
- });
513
- }
514
- return CancelablePromise__default.resolve(undefined);
515
- };
516
- /**
517
- * A fast way to retrieve resource ID for any resource definition.
518
- * @param resource - Any available resource definition
519
- *
520
- * @remarks
521
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
522
- * To not make one more checks if the resource is definitely exists
523
- */
524
- ResourcesControl.prototype.getIdOrFail = function (resource, requestOptions) {
525
- return this.getId(resource, requestOptions).then(function (resp) {
526
- if (resp === undefined) {
527
- throw new Error();
528
- }
529
- return resp;
530
- });
531
- };
532
- ResourcesControl.prototype.getMany = function (resource, requestOptions) {
533
- var _this = this;
534
- return this._resourceCacheFilter(resource).then(function (items) {
535
- if (!items.length) {
536
- var query = {};
537
- if (resource.keyname) {
538
- query.keyname = resource.keyname;
539
- }
540
- else {
541
- Object.assign(query, resourceToQuery(resource));
542
- }
543
- return _this.connector
544
- .get('resource.search', requestOptions, __assign({ serialization: 'full' }, query))
545
- .then(function (resources) {
546
- if (resources) {
547
- for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
548
- var x = resources_1[_i];
549
- _this.cache.add('resource.item', CancelablePromise__default.resolve(x), {
550
- id: x.resource.id,
551
- });
552
- }
553
- }
554
- return resources;
555
- });
556
- }
557
- return items;
558
- });
559
- };
560
- ResourcesControl.prototype.getParent = function (resource, requestOptions) {
561
- var _this = this;
562
- return this.getOne(resource, requestOptions).then(function (child) {
563
- if (child) {
564
- return _this.getOne(child.resource.parent.id, requestOptions);
565
- }
566
- return CancelablePromise__default.resolve(undefined);
567
- });
568
- };
569
- ResourcesControl.prototype.getChildrenOf = function (resource, requestOptions) {
570
- var _this = this;
571
- return this.getIdOrFail(resource).then(function (parent) {
572
- return _this._getChildrenOf(parent, requestOptions);
573
- });
574
- };
575
- ResourcesControl.prototype.update = function (resource, data) {
576
- var _this = this;
577
- return this.getId(resource).then(function (id) {
578
- if (id !== undefined) {
579
- return _this.connector.put('resource.item', { data: data }, { id: id });
580
- }
581
- });
582
- };
583
- /**
584
- * Fast way to delete resource from NGW and clean cache.
585
- * @param resource - Resource definition
586
- */
587
- ResourcesControl.prototype.delete = function (resource) {
588
- var _this = this;
589
- return this.getId(resource).then(function (id) {
590
- if (id !== undefined) {
591
- return _this.connector.delete('resource.item', null, { id: id }).then(function () {
592
- _this._cleanResourceItemCache(id);
593
- return undefined;
594
- });
595
- }
596
- });
597
- };
598
- ResourcesControl.prototype._getChildrenOf = function (parent, requestOptions, _items) {
599
- var _this = this;
600
- if (_items === void 0) { _items = []; }
601
- return this.connector
602
- .get('resource.collection', __assign({ cache: true }, requestOptions), {
603
- parent: parent,
604
- })
605
- .then(function (items) {
606
- var recursivePromises = [];
607
- for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
608
- var item = items_1[_i];
609
- _this.cache.add('resource.item', CancelablePromise__default.resolve(item), {
610
- id: item.resource.id,
611
- });
612
- _items.push(item);
613
- if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
614
- recursivePromises.push(_this._getChildrenOf(item.resource.id, requestOptions, _items));
615
- }
616
- }
617
- if (recursivePromises.length) {
618
- return CancelablePromise__default.all(recursivePromises).then(function () {
619
- return _items;
620
- });
621
- }
622
- return _items;
623
- });
624
- };
625
- ResourcesControl.prototype._cleanResourceItemCache = function (id) {
626
- return __awaiter(this, void 0, void 0, function () {
627
- var all, toDelete, _i, all_1, c, cid, rid, _a, toDelete_1, d;
628
- return __generator(this, function (_b) {
629
- switch (_b.label) {
630
- case 0:
631
- all = this.cache.all();
632
- toDelete = [];
633
- _i = 0, all_1 = all;
634
- _b.label = 1;
635
- case 1:
636
- if (!(_i < all_1.length)) return [3 /*break*/, 5];
637
- c = all_1[_i];
638
- cid = c.options && c.options.id;
639
- if (!(['resource.item', 'resource'].includes(c.key) && cid !== undefined)) return [3 /*break*/, 4];
640
- if (!(typeof cid === 'number')) return [3 /*break*/, 2];
641
- if (cid === id) {
642
- toDelete.push(c);
643
- }
644
- return [3 /*break*/, 4];
645
- case 2: return [4 /*yield*/, this.getId(cid)];
646
- case 3:
647
- rid = _b.sent();
648
- if (rid === id) {
649
- toDelete.push(c);
650
- }
651
- _b.label = 4;
652
- case 4:
653
- _i++;
654
- return [3 /*break*/, 1];
655
- case 5:
656
- for (_a = 0, toDelete_1 = toDelete; _a < toDelete_1.length; _a++) {
657
- d = toDelete_1[_a];
658
- this.cache.delete(d);
659
- }
660
- return [2 /*return*/];
661
- }
662
- });
663
- });
664
- };
665
- ResourcesControl.prototype._fetchResourceById = function (id, requestOptions) {
666
- var _this = this;
667
- var promise = function () {
668
- return _this.connector.get('resource.item', requestOptions, { id: id });
669
- };
670
- return this.cache
671
- .add('resource.item', promise, {
672
- id: id,
673
- })
674
- .catch(function (er) {
675
- if (!(er instanceof ResourceNotFoundError)) {
676
- throw er;
677
- }
678
- return undefined;
679
- });
680
- };
681
- ResourcesControl.prototype._fetchResourceBy = function (resource, requestOptions) {
682
- return this.getMany(resource, requestOptions).then(function (resources) {
683
- return resources[0];
684
- });
685
- };
686
- ResourcesControl.prototype._resourceCacheFilter = function (resource) {
687
- return CancelablePromise__default.all(this.cache.matchAll('resource.item')).then(function (resources) {
688
- var items = [];
689
- resources.filter(function (x) {
690
- if (x) {
691
- // identical by uniq props
692
- if (resource.keyname && x.resource.keyname) {
693
- return resource.keyname === x.resource.keyname;
694
- }
695
- if (utils.defined(resource.id) && utils.defined(x.resource.id)) {
696
- return resource.id === x.resource.id;
697
- }
698
- return resourceCompare(resource, x.resource);
699
- }
700
- });
701
- return items;
702
- });
703
- };
704
- return ResourcesControl;
705
- }());
326
+ class ResourcesControl {
327
+ constructor(connector) {
328
+ this.connector = connector;
329
+ this.cache = new Cache__default();
330
+ }
331
+ // -------------------------------------------------------------------------
332
+ // Resource Methods
333
+ // -------------------------------------------------------------------------
334
+ /**
335
+ * Receive resource from NGW by id, keyname or search-object parameter.
336
+ * @param resource - Resource id, keyname or search-object
337
+ *
338
+ * @remarks
339
+ * Fetching resource would be cached to speed up next call
340
+ */
341
+ getOne(resource, requestOptions) {
342
+ const cache = new Cache__default();
343
+ const forCache = {};
344
+ const opt = { ...requestOptions, cache: false };
345
+ if (typeof resource === 'string') {
346
+ forCache.keyname = resource;
347
+ }
348
+ else if (typeof resource === 'number') {
349
+ forCache.id = resource;
350
+ }
351
+ else if (isObject(resource)) {
352
+ if (resource.id !== undefined) {
353
+ forCache.id = resource.id;
354
+ }
355
+ else if (resource.keyname) {
356
+ forCache.keyname = resource.keyname;
357
+ }
358
+ }
359
+ const makeRequest = () => {
360
+ if (typeof resource === 'string') {
361
+ return this._fetchResourceBy({ keyname: resource }, opt);
362
+ }
363
+ else if (typeof resource === 'number') {
364
+ return this._fetchResourceById(resource, opt);
365
+ }
366
+ else if (isObject(resource)) {
367
+ return this._fetchResourceBy(resource, opt);
368
+ }
369
+ return CancelablePromise__default.resolve(undefined);
370
+ };
371
+ return cache.addFull('resource', makeRequest, forCache);
372
+ }
373
+ getOneOrFail(resource, requestOptions) {
374
+ return this.getOne(resource, requestOptions).then((res) => {
375
+ if (res) {
376
+ return res;
377
+ }
378
+ throw new ResourceNotFoundError();
379
+ });
380
+ }
381
+ /**
382
+ * A fast way to retrieve resource ID for any resource definition.
383
+ * @param resource - Any available resource definition
384
+ *
385
+ * @remarks
386
+ * There are situations when exactly the resource id is needed
387
+ * (for example, to compose the correct request to the api)
388
+ * then this method will come in handy to facilitate the extraction of the identifier
389
+ * if the resource is specified through a keyname or other parameters.
390
+ */
391
+ getId(resource, requestOptions) {
392
+ if (typeof resource === 'number') {
393
+ return CancelablePromise__default.resolve(resource);
394
+ }
395
+ else if (typeof resource === 'string' || isObject(resource)) {
396
+ return this.getOne(resource, requestOptions).then((res) => {
397
+ if (res) {
398
+ return res.resource.id;
399
+ }
400
+ });
401
+ }
402
+ return CancelablePromise__default.resolve(undefined);
403
+ }
404
+ /**
405
+ * A fast way to retrieve resource ID for any resource definition.
406
+ * @param resource - Any available resource definition
407
+ *
408
+ * @remarks
409
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
410
+ * To not make one more checks if the resource is definitely exists
411
+ */
412
+ getIdOrFail(resource, requestOptions) {
413
+ return this.getId(resource, requestOptions).then((resp) => {
414
+ if (resp === undefined) {
415
+ throw new Error();
416
+ }
417
+ return resp;
418
+ });
419
+ }
420
+ getMany(resource, requestOptions) {
421
+ return this._resourceCacheFilter(resource).then((items) => {
422
+ if (!items.length) {
423
+ const query = {};
424
+ if (resource.keyname) {
425
+ query.keyname = resource.keyname;
426
+ }
427
+ else {
428
+ Object.assign(query, resourceToQuery(resource));
429
+ }
430
+ return this.connector
431
+ .get('resource.search', requestOptions, {
432
+ serialization: 'full',
433
+ ...query,
434
+ })
435
+ .then((resources) => {
436
+ if (resources) {
437
+ for (const x of resources) {
438
+ this.cache.add('resource.item', CancelablePromise__default.resolve(x), {
439
+ id: x.resource.id,
440
+ });
441
+ }
442
+ }
443
+ return resources;
444
+ });
445
+ }
446
+ return items;
447
+ });
448
+ }
449
+ getParent(resource, requestOptions) {
450
+ return this.getOne(resource, requestOptions).then((child) => {
451
+ if (child) {
452
+ return this.getOne(child.resource.parent.id, requestOptions);
453
+ }
454
+ return CancelablePromise__default.resolve(undefined);
455
+ });
456
+ }
457
+ getChildrenOf(resource, requestOptions) {
458
+ return this.getIdOrFail(resource).then((parent) => this._getChildrenOf(parent, requestOptions));
459
+ }
460
+ update(resource, data) {
461
+ return this.getId(resource).then((id) => {
462
+ if (id !== undefined) {
463
+ return this.connector.put('resource.item', { data }, { id });
464
+ }
465
+ });
466
+ }
467
+ /**
468
+ * Fast way to delete resource from NGW and clean cache.
469
+ * @param resource - Resource definition
470
+ */
471
+ delete(resource) {
472
+ return this.getId(resource).then((id) => {
473
+ if (id !== undefined) {
474
+ return this.connector.delete('resource.item', null, { id }).then(() => {
475
+ this._cleanResourceItemCache(id);
476
+ return undefined;
477
+ });
478
+ }
479
+ });
480
+ }
481
+ _getChildrenOf(parent, requestOptions, _items = []) {
482
+ return this.connector
483
+ .get('resource.collection', { cache: true, ...requestOptions }, {
484
+ parent,
485
+ })
486
+ .then((items) => {
487
+ const recursivePromises = [];
488
+ for (const item of items) {
489
+ this.cache.add('resource.item', CancelablePromise__default.resolve(item), {
490
+ id: item.resource.id,
491
+ });
492
+ _items.push(item);
493
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
494
+ recursivePromises.push(this._getChildrenOf(item.resource.id, requestOptions, _items));
495
+ }
496
+ }
497
+ if (recursivePromises.length) {
498
+ return CancelablePromise__default.all(recursivePromises).then(() => {
499
+ return _items;
500
+ });
501
+ }
502
+ return _items;
503
+ });
504
+ }
505
+ async _cleanResourceItemCache(id) {
506
+ const all = this.cache.all();
507
+ const toDelete = [];
508
+ for (const c of all) {
509
+ const cid = c.options && c.options.id;
510
+ if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {
511
+ if (typeof cid === 'number') {
512
+ if (cid === id) {
513
+ toDelete.push(c);
514
+ }
515
+ }
516
+ else {
517
+ const rid = await this.getId(cid);
518
+ if (rid === id) {
519
+ toDelete.push(c);
520
+ }
521
+ }
522
+ }
523
+ }
524
+ for (const d of toDelete) {
525
+ this.cache.delete(d);
526
+ }
527
+ }
528
+ _fetchResourceById(id, requestOptions) {
529
+ const promise = () => this.connector.get('resource.item', requestOptions, { id });
530
+ return this.cache
531
+ .add('resource.item', promise, {
532
+ id,
533
+ })
534
+ .catch((er) => {
535
+ if (!(er instanceof ResourceNotFoundError)) {
536
+ throw er;
537
+ }
538
+ return undefined;
539
+ });
540
+ }
541
+ _fetchResourceBy(resource, requestOptions) {
542
+ return this.getMany(resource, requestOptions).then((resources) => {
543
+ return resources[0];
544
+ });
545
+ }
546
+ _resourceCacheFilter(resource) {
547
+ return CancelablePromise__default.all(this.cache.matchAll('resource.item')).then((resources) => {
548
+ const items = [];
549
+ resources.filter((x) => {
550
+ if (x) {
551
+ // identical by uniq props
552
+ if (resource.keyname && x.resource.keyname) {
553
+ return resource.keyname === x.resource.keyname;
554
+ }
555
+ if (utils.defined(resource.id) && utils.defined(x.resource.id)) {
556
+ return resource.id === x.resource.id;
557
+ }
558
+ return resourceCompare(resource, x.resource);
559
+ }
560
+ });
561
+ return items;
562
+ });
563
+ }
564
+ }
706
565
 
707
- var ID = 0;
708
- var NgwConnector$1 = /** @class */ (function () {
709
- function NgwConnector(options) {
710
- this.options = options;
711
- this.id = ID++;
712
- this.emitter = new events.EventEmitter();
713
- this.routeStr = '/api/component/pyramid/route';
714
- this.activeRequests = [];
715
- var exist = findConnector(options);
716
- if (exist) {
717
- return exist;
718
- }
719
- else {
720
- if (this.options.route) {
721
- this.routeStr = this.options.route;
722
- }
723
- if (this.options.requestTransform) {
724
- this.requestTransform = this.options.requestTransform;
725
- }
726
- this.resources = new ResourcesControl(this);
727
- addConnector(this);
728
- }
729
- }
730
- NgwConnector.create = function (options) {
731
- return new this(options);
732
- };
733
- NgwConnector.prototype.setRequestTransform = function (requestTransform) {
734
- this.requestTransform = requestTransform;
735
- };
736
- /**
737
- * Fast way to specify the connection address to NextGIS Web.
738
- * The current connection will be severed.
739
- * @param baseUrl - NGW url
740
- */
741
- NgwConnector.prototype.setNgw = function (baseUrl) {
742
- this.logout();
743
- this.options.baseUrl = baseUrl;
744
- addConnector(this);
745
- };
746
- /**
747
- * Establishing a connection with NextGIS Web to fulfill all other requests.
748
- * @remarks
749
- * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
750
- * Can be used to check connection.
751
- * @example
752
- * ```javascript
753
- * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
754
- * connector.connect()
755
- * .then(() => console.log('Ok'))
756
- * .catch((er) => console.log('Connection problem', er));
757
- * ```
758
- */
759
- NgwConnector.prototype.connect = function () {
760
- var _this = this;
761
- var cache = new Cache__default();
762
- var auth = this.options.auth;
763
- var makeConnect = function () {
764
- return new CancelablePromise__default(function (resolve, reject) {
765
- var makeQuery = function () {
766
- return _this.makeQuery(_this.routeStr, {}, {})
767
- .then(function (route) {
768
- resolve(route);
769
- })
770
- .catch(function (er) {
771
- reject(er);
772
- });
773
- };
774
- if (auth) {
775
- var login = auth.login, password = auth.password;
776
- if (login && password) {
777
- return _this._login({ login: login, password: password })
778
- .then(function () {
779
- return makeQuery();
780
- })
781
- .catch(function (er) { return reject(er); });
782
- }
783
- }
784
- return makeQuery();
785
- });
786
- };
787
- return cache.add('route', makeConnect, {
788
- id: this.id,
789
- auth: auth,
790
- baseUrl: this.options.baseUrl,
791
- });
792
- };
793
- /**
794
- * Quick way to change NextGIS Web user.
795
- * @param credentials - New user credentials
796
- */
797
- NgwConnector.prototype.login = function (credentials, options) {
798
- this.logout();
799
- addConnector(this);
800
- return this._login(credentials, options);
801
- };
802
- /**
803
- * Disconnecting a user. Aborting all current requests
804
- */
805
- NgwConnector.prototype.logout = function () {
806
- this.abort();
807
- removeConnector(this);
808
- this.options.auth = undefined;
809
- this.user = undefined;
810
- this.emitter.emit('logout');
811
- this.resources.cache.clean();
812
- };
813
- NgwConnector.prototype.getUserInfo = function (credentials, options) {
814
- if (this.user && this.user.id) {
815
- return CancelablePromise__default.resolve(this.user);
816
- }
817
- if (credentials) {
818
- this.options.auth = credentials;
819
- }
820
- var options_ = __assign({ headers: this.getAuthorizationHeaders(credentials) }, options);
821
- // Do not use apiRequest('auth.current_user') to avoid circular-references
822
- return this.makeQuery('/api/component/auth/current_user', {}, options_);
823
- };
824
- /**
825
- * Obtaining the required Headers for authentication of requests in the NGW.
826
- */
827
- NgwConnector.prototype.getAuthorizationHeaders = function (credentials) {
828
- var client = this.makeClientId(credentials);
829
- if (client) {
830
- return {
831
- Authorization: 'Basic ' + client,
832
- };
833
- }
834
- };
835
- NgwConnector.prototype.makeClientId = function (credentials) {
836
- credentials = credentials || this.options.auth;
837
- if (credentials) {
838
- var login = credentials.login, password = credentials.password;
839
- var str = unescape(encodeURIComponent("".concat(login, ":").concat(password)));
840
- // @ts-ignore
841
- {
842
- return Buffer.from(str).toString('base64');
843
- }
844
- }
845
- };
846
- /** Stop all api requests */
847
- NgwConnector.prototype.abort = function () {
848
- for (var _i = 0, _a = this.activeRequests; _i < _a.length; _i++) {
849
- var req = _a[_i];
850
- req.cancel();
851
- }
852
- this.activeRequests = [];
853
- };
854
- NgwConnector.prototype.getActiveApiRequests = function () {
855
- return __spreadArray([], this.activeRequests, true);
856
- };
857
- /**
858
- * Send request to NGW api router.
859
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
860
- * @param params - Request item params or query params
861
- * @param requestOptions - Request options
862
- *
863
- * @example
864
- * ```javascript
865
- *
866
- * // there is such an NGW route item
867
- * // "feature_layer.feature.item": [
868
- * // "/api/resource/{0}/feature/{1}",
869
- * // "id",
870
- * // "fid"
871
- * // ],
872
- *
873
- * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
874
- * connector.apiRequest('feature_layer.feature.item', {
875
- * // request params for {0} and {1}
876
- * 'id': 2011,
877
- * 'fid': 101,
878
- * // query params
879
- * 'srs': 4326,
880
- * 'geom_format': 'geojson',
881
- * }, { method: 'GET' });
882
- * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
883
- *
884
- * ```
885
- */
886
- NgwConnector.prototype.apiRequest = function (name, params_, requestOptions) {
887
- var _this = this;
888
- var _a;
889
- if (params_ === void 0) { params_ = {}; }
890
- if (requestOptions === void 0) { requestOptions = {}; }
891
- var method = requestOptions.method, headers = requestOptions.headers, withCredentials = requestOptions.withCredentials, responseType = requestOptions.responseType;
892
- var params = utils.objectRemoveEmpty(params_);
893
- var makeApiRequest = function () {
894
- return apiRequest({ name: name, params: params, requestOptions: requestOptions, connector: _this });
895
- };
896
- if (requestOptions.cache && method === 'GET') {
897
- var cache = new Cache__default();
898
- return cache.add(name, makeApiRequest, __assign({ params: params }, utils.objectRemoveEmpty({
899
- headers: headers,
900
- withCredentials: withCredentials,
901
- responseType: responseType,
902
- baseUrl: this.options.baseUrl,
903
- userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
904
- })));
905
- }
906
- return makeApiRequest();
907
- };
908
- /**
909
- * Shortcut method for send POST request to NGW.
910
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
911
- * @param options - Request options
912
- * @param params - Request item params or query params
913
- *
914
- * @example
915
- * ```javascript
916
- * connector.post('resource.collection', { data: POST_PAYLOAD })
917
- * .then((newResource) => console.log(newResource))
918
- * .catch((error) => console.warn(error));
919
- * ```
920
- */
921
- NgwConnector.prototype.post = function (name, options, params) {
922
- options = options || {};
923
- options.method = 'POST';
924
- return this.apiRequest(name, params, options);
925
- };
926
- /**
927
- * Shortcut method for send GET request to NGW.
928
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
929
- * @param options - Request options
930
- * @param params - Request item params or query params
931
- */
932
- NgwConnector.prototype.get = function (name, options, params) {
933
- options = options || {};
934
- options.method = 'GET';
935
- return this.apiRequest(name, params, options);
936
- };
937
- /**
938
- * Shortcut method for send PATCH request to NGW.
939
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
940
- * @param options - Request options
941
- * @param params - Request item params or query params
942
- */
943
- NgwConnector.prototype.patch = function (name, options, params) {
944
- options = options || {};
945
- options.method = 'PATCH';
946
- return this.apiRequest(name, params, options);
947
- };
948
- /**
949
- * Shortcut method for send PUT request to NGW.
950
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
951
- * @param options - Request options
952
- * @param params - Request item params or query params
953
- */
954
- NgwConnector.prototype.put = function (name, options, params) {
955
- options = options || {};
956
- options.method = 'PUT';
957
- return this.apiRequest(name, params, options);
958
- };
959
- /**
960
- * Shortcut method for send DELETE request to NGW.
961
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
962
- * @param options - Request options
963
- * @param params - Request item params or query params
964
- */
965
- NgwConnector.prototype.delete = function (name, options, params) {
966
- options = options || {};
967
- options.method = 'DELETE';
968
- return this.apiRequest(name, params, options);
969
- };
970
- /**
971
- * Send request to NGW.
972
- * @param url - URL address to NGW
973
- * @param params - Query params
974
- * @param options - Request options
975
- */
976
- NgwConnector.prototype.makeQuery = function (url, params, options) {
977
- if (options === void 0) { options = {}; }
978
- url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
979
- if (url) {
980
- if (params) {
981
- url = template(url, params);
982
- }
983
- url = encodeURI(utils.fixUrlStr(url));
984
- return this._loadData(url, options);
985
- }
986
- else {
987
- throw new Error('Empty `url` not allowed');
988
- }
989
- };
990
- // -------------------------------------------------------------------------
991
- // Resource Methods
992
- // -------------------------------------------------------------------------
993
- /**
994
- * {@link ResourcesControl.getOne}
995
- */
996
- NgwConnector.prototype.getResource = function (resource, requestOptions) {
997
- return this.resources.getOne(resource, requestOptions);
998
- };
999
- /**
1000
- * {@link ResourcesControl.getOneOrFail}
1001
- */
1002
- NgwConnector.prototype.getResourceOrFail = function (resource, requestOptions) {
1003
- return this.resources.getOneOrFail(resource, requestOptions);
1004
- };
1005
- /**
1006
- * @deprecated - use {@link getResource}
1007
- */
1008
- NgwConnector.prototype.getResourceBy = function (resource) {
1009
- return this.resources.getOne(resource);
1010
- };
1011
- /**
1012
- * @deprecated - use {@link getResource}
1013
- */
1014
- NgwConnector.prototype.getResourceByKeyname = function (keyname) {
1015
- return this.resources.getOne(keyname);
1016
- };
1017
- /**
1018
- * @deprecated - use {@link getResource}
1019
- */
1020
- NgwConnector.prototype.getResourceById = function (id) {
1021
- return this.resources.getOne(id);
1022
- };
1023
- /**
1024
- * {@link ResourcesControl.getId}
1025
- */
1026
- NgwConnector.prototype.getResourceId = function (resource, requestOptions) {
1027
- return this.resources.getId(resource, requestOptions);
1028
- };
1029
- /**
1030
- * {@link ResourcesControl.getIdOrFail}
1031
- */
1032
- NgwConnector.prototype.getResourceIdOrFail = function (resource, requestOptions) {
1033
- return this.resources.getIdOrFail(resource, requestOptions);
1034
- };
1035
- /**
1036
- * {@link ResourcesControl.getMany}
1037
- */
1038
- NgwConnector.prototype.getResourcesBy = function (resource, requestOptions) {
1039
- return this.resources.getMany(resource, requestOptions);
1040
- };
1041
- /**
1042
- * {@link ResourcesControl.getParent}
1043
- */
1044
- NgwConnector.prototype.getResourceParent = function (resource, requestOptions) {
1045
- return this.resources.getParent(resource, requestOptions);
1046
- };
1047
- /**
1048
- * {@link ResourcesControl.getChildrenOf}
1049
- */
1050
- NgwConnector.prototype.getResourceChildren = function (resource, requestOptions) {
1051
- return this.resources.getChildrenOf(resource, requestOptions);
1052
- };
1053
- /**
1054
- * {@link ResourcesControl.update}
1055
- */
1056
- NgwConnector.prototype.updateResource = function (resource, data) {
1057
- return this.resources.update(resource, data);
1058
- };
1059
- /**
1060
- * {@link ResourcesControl.delete}
1061
- */
1062
- NgwConnector.prototype.deleteResource = function (resource) {
1063
- return this.resources.delete(resource);
1064
- };
1065
- /**
1066
- * @internal
1067
- */
1068
- NgwConnector.prototype._loadData = function (url, options) {
1069
- var _this = this;
1070
- options.responseType = options.responseType || 'json';
1071
- var request = new CancelablePromise__default(function (resolve, reject, onCancel) {
1072
- if (_this.user) {
1073
- options = options || {};
1074
- // options.withCredentials = true;
1075
- options.headers = __assign(__assign({}, _this.getAuthorizationHeaders()), options.headers);
1076
- }
1077
- if (_this.requestTransform) {
1078
- var _a = _this.requestTransform(url, options), transUrl = _a[0], transOptions = _a[1];
1079
- url = transUrl;
1080
- options = transOptions;
1081
- }
1082
- loadData(url, resolve, options, reject, onCancel);
1083
- })
1084
- .then(function (resp) {
1085
- _this._cleanActiveRequests(request);
1086
- return resp;
1087
- })
1088
- .catch(function (httpError) {
1089
- _this._cleanActiveRequests(request);
1090
- if (httpError instanceof CancelablePromise__default.CancelError) ;
1091
- else {
1092
- // @ts-ignore
1093
- {
1094
- console.warn('DEV WARN', httpError);
1095
- }
1096
- var er = _this._handleHttpError(httpError);
1097
- if (er) {
1098
- throw er;
1099
- }
1100
- }
1101
- });
1102
- if (options.signal &&
1103
- typeof options.signal.addEventListener === 'function') {
1104
- options.signal.addEventListener('abort', function () {
1105
- request.cancel();
1106
- _this._cleanActiveRequests(request);
1107
- });
1108
- }
1109
- this.activeRequests.push(request);
1110
- return request;
1111
- };
1112
- NgwConnector.prototype._login = function (credentials, options) {
1113
- var _this = this;
1114
- return this.getUserInfo(credentials, options)
1115
- .then(function (data) {
1116
- _this.user = data;
1117
- _this.emitter.emit('login', data);
1118
- return data;
1119
- })
1120
- .catch(function (er) {
1121
- _this.emitter.emit('login:error', er);
1122
- throw er;
1123
- });
1124
- };
1125
- NgwConnector.prototype._cleanActiveRequests = function (request) {
1126
- var activeRequestIndex = this.activeRequests.indexOf(request);
1127
- if (activeRequestIndex !== -1) {
1128
- this.activeRequests.splice(activeRequestIndex, 1);
1129
- }
1130
- };
1131
- NgwConnector.prototype._handleHttpError = function (er) {
1132
- if (er) {
1133
- if (er instanceof NgwError) {
1134
- if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
1135
- throw new ResourceNotFoundError(er);
1136
- }
1137
- else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
1138
- throw new InsufficientPermissionsError(er);
1139
- }
1140
- }
1141
- }
1142
- return er;
1143
- };
1144
- NgwConnector.errors = {
1145
- NgwError: NgwError,
1146
- ResourceNotFoundError: ResourceNotFoundError,
1147
- };
1148
- return NgwConnector;
1149
- }());
566
+ let ID = 0;
567
+ class NgwConnector$1 {
568
+ constructor(options) {
569
+ this.options = options;
570
+ this.id = ID++;
571
+ this.emitter = new events.EventEmitter();
572
+ this.routeStr = '/api/component/pyramid/route';
573
+ this.activeRequests = [];
574
+ const exist = findConnector(options);
575
+ if (exist) {
576
+ return exist;
577
+ }
578
+ else {
579
+ if (this.options.route) {
580
+ this.routeStr = this.options.route;
581
+ }
582
+ if (this.options.requestTransform) {
583
+ this.requestTransform = this.options.requestTransform;
584
+ }
585
+ this.resources = new ResourcesControl(this);
586
+ addConnector(this);
587
+ }
588
+ }
589
+ static create(options) {
590
+ return new this(options);
591
+ }
592
+ setRequestTransform(requestTransform) {
593
+ this.requestTransform = requestTransform;
594
+ }
595
+ /**
596
+ * Fast way to specify the connection address to NextGIS Web.
597
+ * The current connection will be severed.
598
+ * @param baseUrl - NGW url
599
+ */
600
+ setNgw(baseUrl) {
601
+ this.logout();
602
+ this.options.baseUrl = baseUrl;
603
+ addConnector(this);
604
+ }
605
+ /**
606
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
607
+ * @remarks
608
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
609
+ * Can be used to check connection.
610
+ * @example
611
+ * ```javascript
612
+ * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
613
+ * connector.connect()
614
+ * .then(() => console.log('Ok'))
615
+ * .catch((er) => console.log('Connection problem', er));
616
+ * ```
617
+ */
618
+ connect() {
619
+ const cache = new Cache__default();
620
+ const auth = this.options.auth;
621
+ const makeConnect = () => new CancelablePromise__default((resolve, reject) => {
622
+ const makeQuery = () => {
623
+ return this.makeQuery(this.routeStr, {}, {})
624
+ .then((route) => {
625
+ resolve(route);
626
+ })
627
+ .catch((er) => {
628
+ reject(er);
629
+ });
630
+ };
631
+ if (auth) {
632
+ const { login, password } = auth;
633
+ if (login && password) {
634
+ return this._login({ login, password })
635
+ .then(() => {
636
+ return makeQuery();
637
+ })
638
+ .catch((er) => reject(er));
639
+ }
640
+ }
641
+ return makeQuery();
642
+ });
643
+ return cache.add('route', makeConnect, {
644
+ id: this.id,
645
+ auth,
646
+ baseUrl: this.options.baseUrl,
647
+ });
648
+ }
649
+ /**
650
+ * Quick way to change NextGIS Web user.
651
+ * @param credentials - New user credentials
652
+ */
653
+ login(credentials, options) {
654
+ this.logout();
655
+ addConnector(this);
656
+ return this._login(credentials, options);
657
+ }
658
+ /**
659
+ * Disconnecting a user. Aborting all current requests
660
+ */
661
+ logout() {
662
+ this.abort();
663
+ removeConnector(this);
664
+ this.options.auth = undefined;
665
+ this.user = undefined;
666
+ this.emitter.emit('logout');
667
+ this.resources.cache.clean();
668
+ }
669
+ getUserInfo(credentials, options) {
670
+ if (this.user && this.user.id) {
671
+ return CancelablePromise__default.resolve(this.user);
672
+ }
673
+ if (credentials) {
674
+ this.options.auth = credentials;
675
+ }
676
+ const options_ = {
677
+ headers: this.getAuthorizationHeaders(credentials),
678
+ // withCredentials: true
679
+ ...options,
680
+ };
681
+ // Do not use apiRequest('auth.current_user') to avoid circular-references
682
+ return this.makeQuery('/api/component/auth/current_user', {}, options_);
683
+ }
684
+ /**
685
+ * Obtaining the required Headers for authentication of requests in the NGW.
686
+ */
687
+ getAuthorizationHeaders(credentials) {
688
+ const client = this.makeClientId(credentials);
689
+ if (client) {
690
+ return {
691
+ Authorization: 'Basic ' + client,
692
+ };
693
+ }
694
+ }
695
+ makeClientId(credentials) {
696
+ credentials = credentials || this.options.auth;
697
+ if (credentials) {
698
+ const { login, password } = credentials;
699
+ const str = unescape(encodeURIComponent(`${login}:${password}`));
700
+ // @ts-ignore
701
+ {
702
+ return Buffer.from(str).toString('base64');
703
+ }
704
+ }
705
+ }
706
+ /** Stop all api requests */
707
+ abort() {
708
+ for (const req of this.activeRequests) {
709
+ req.cancel();
710
+ }
711
+ this.activeRequests = [];
712
+ }
713
+ getActiveApiRequests() {
714
+ return [...this.activeRequests];
715
+ }
716
+ /**
717
+ * Send request to NGW api router.
718
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
719
+ * @param params - Request item params or query params
720
+ * @param requestOptions - Request options
721
+ *
722
+ * @example
723
+ * ```javascript
724
+ *
725
+ * // there is such an NGW route item
726
+ * // "feature_layer.feature.item": [
727
+ * // "/api/resource/{0}/feature/{1}",
728
+ * // "id",
729
+ * // "fid"
730
+ * // ],
731
+ *
732
+ * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
733
+ * connector.apiRequest('feature_layer.feature.item', {
734
+ * // request params for {0} and {1}
735
+ * 'id': 2011,
736
+ * 'fid': 101,
737
+ * // query params
738
+ * 'srs': 4326,
739
+ * 'geom_format': 'geojson',
740
+ * }, { method: 'GET' });
741
+ * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
742
+ *
743
+ * ```
744
+ */
745
+ apiRequest(name, params_ = {}, requestOptions = {}) {
746
+ var _a;
747
+ const { method, headers, withCredentials, responseType } = requestOptions;
748
+ const params = utils.objectRemoveEmpty(params_);
749
+ const makeApiRequest = () => apiRequest({ name, params, requestOptions, connector: this });
750
+ if (requestOptions.cache && method === 'GET') {
751
+ const cache = new Cache__default();
752
+ return cache.add(name, makeApiRequest, {
753
+ params,
754
+ ...utils.objectRemoveEmpty({
755
+ headers,
756
+ withCredentials,
757
+ responseType,
758
+ baseUrl: this.options.baseUrl,
759
+ userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
760
+ }),
761
+ });
762
+ }
763
+ return makeApiRequest();
764
+ }
765
+ /**
766
+ * Shortcut method for send POST request to NGW.
767
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
768
+ * @param options - Request options
769
+ * @param params - Request item params or query params
770
+ *
771
+ * @example
772
+ * ```javascript
773
+ * connector.post('resource.collection', { data: POST_PAYLOAD })
774
+ * .then((newResource) => console.log(newResource))
775
+ * .catch((error) => console.warn(error));
776
+ * ```
777
+ */
778
+ post(name, options, params) {
779
+ options = options || {};
780
+ options.method = 'POST';
781
+ return this.apiRequest(name, params, options);
782
+ }
783
+ /**
784
+ * Shortcut method for send GET request to NGW.
785
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
786
+ * @param options - Request options
787
+ * @param params - Request item params or query params
788
+ */
789
+ get(name, options, params) {
790
+ options = options || {};
791
+ options.method = 'GET';
792
+ return this.apiRequest(name, params, options);
793
+ }
794
+ /**
795
+ * Shortcut method for send PATCH request to NGW.
796
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
797
+ * @param options - Request options
798
+ * @param params - Request item params or query params
799
+ */
800
+ patch(name, options, params) {
801
+ options = options || {};
802
+ options.method = 'PATCH';
803
+ return this.apiRequest(name, params, options);
804
+ }
805
+ /**
806
+ * Shortcut method for send PUT request to NGW.
807
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
808
+ * @param options - Request options
809
+ * @param params - Request item params or query params
810
+ */
811
+ put(name, options, params) {
812
+ options = options || {};
813
+ options.method = 'PUT';
814
+ return this.apiRequest(name, params, options);
815
+ }
816
+ /**
817
+ * Shortcut method for send DELETE request to NGW.
818
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
819
+ * @param options - Request options
820
+ * @param params - Request item params or query params
821
+ */
822
+ delete(name, options, params) {
823
+ options = options || {};
824
+ options.method = 'DELETE';
825
+ return this.apiRequest(name, params, options);
826
+ }
827
+ /**
828
+ * Send request to NGW.
829
+ * @param url - URL address to NGW
830
+ * @param params - Query params
831
+ * @param options - Request options
832
+ */
833
+ makeQuery(url, params, options = {}) {
834
+ url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
835
+ if (url) {
836
+ if (params) {
837
+ url = template(url, params);
838
+ }
839
+ url = encodeURI(utils.fixUrlStr(url));
840
+ return this._loadData(url, options);
841
+ }
842
+ else {
843
+ throw new Error('Empty `url` not allowed');
844
+ }
845
+ }
846
+ // -------------------------------------------------------------------------
847
+ // Resource Methods
848
+ // -------------------------------------------------------------------------
849
+ /**
850
+ * {@link ResourcesControl.getOne}
851
+ */
852
+ getResource(resource, requestOptions) {
853
+ return this.resources.getOne(resource, requestOptions);
854
+ }
855
+ /**
856
+ * {@link ResourcesControl.getOneOrFail}
857
+ */
858
+ getResourceOrFail(resource, requestOptions) {
859
+ return this.resources.getOneOrFail(resource, requestOptions);
860
+ }
861
+ /**
862
+ * @deprecated - use {@link getResource}
863
+ */
864
+ getResourceBy(resource) {
865
+ return this.resources.getOne(resource);
866
+ }
867
+ /**
868
+ * @deprecated - use {@link getResource}
869
+ */
870
+ getResourceByKeyname(keyname) {
871
+ return this.resources.getOne(keyname);
872
+ }
873
+ /**
874
+ * @deprecated - use {@link getResource}
875
+ */
876
+ getResourceById(id) {
877
+ return this.resources.getOne(id);
878
+ }
879
+ /**
880
+ * {@link ResourcesControl.getId}
881
+ */
882
+ getResourceId(resource, requestOptions) {
883
+ return this.resources.getId(resource, requestOptions);
884
+ }
885
+ /**
886
+ * {@link ResourcesControl.getIdOrFail}
887
+ */
888
+ getResourceIdOrFail(resource, requestOptions) {
889
+ return this.resources.getIdOrFail(resource, requestOptions);
890
+ }
891
+ /**
892
+ * {@link ResourcesControl.getMany}
893
+ */
894
+ getResourcesBy(resource, requestOptions) {
895
+ return this.resources.getMany(resource, requestOptions);
896
+ }
897
+ /**
898
+ * {@link ResourcesControl.getParent}
899
+ */
900
+ getResourceParent(resource, requestOptions) {
901
+ return this.resources.getParent(resource, requestOptions);
902
+ }
903
+ /**
904
+ * {@link ResourcesControl.getChildrenOf}
905
+ */
906
+ getResourceChildren(resource, requestOptions) {
907
+ return this.resources.getChildrenOf(resource, requestOptions);
908
+ }
909
+ /**
910
+ * {@link ResourcesControl.update}
911
+ */
912
+ updateResource(resource, data) {
913
+ return this.resources.update(resource, data);
914
+ }
915
+ /**
916
+ * {@link ResourcesControl.delete}
917
+ */
918
+ deleteResource(resource) {
919
+ return this.resources.delete(resource);
920
+ }
921
+ /**
922
+ * @internal
923
+ */
924
+ _loadData(url, options) {
925
+ options.responseType = options.responseType || 'json';
926
+ const request = new CancelablePromise__default((resolve, reject, onCancel) => {
927
+ if (this.user) {
928
+ options = options || {};
929
+ // options.withCredentials = true;
930
+ options.headers = {
931
+ ...this.getAuthorizationHeaders(),
932
+ ...options.headers,
933
+ };
934
+ }
935
+ if (this.requestTransform) {
936
+ const [transUrl, transOptions] = this.requestTransform(url, options);
937
+ url = transUrl;
938
+ options = transOptions;
939
+ }
940
+ loadData(url, resolve, options, reject, onCancel);
941
+ })
942
+ .then((resp) => {
943
+ this._cleanActiveRequests(request);
944
+ return resp;
945
+ })
946
+ .catch((httpError) => {
947
+ this._cleanActiveRequests(request);
948
+ if (httpError instanceof CancelablePromise__default.CancelError) ;
949
+ else {
950
+ // @ts-ignore
951
+ {
952
+ console.warn('DEV WARN', httpError);
953
+ }
954
+ const er = this._handleHttpError(httpError);
955
+ if (er) {
956
+ throw er;
957
+ }
958
+ }
959
+ });
960
+ if (options.signal &&
961
+ typeof options.signal.addEventListener === 'function') {
962
+ options.signal.addEventListener('abort', () => {
963
+ request.cancel();
964
+ this._cleanActiveRequests(request);
965
+ });
966
+ }
967
+ this.activeRequests.push(request);
968
+ return request;
969
+ }
970
+ _login(credentials, options) {
971
+ return this.getUserInfo(credentials, options)
972
+ .then((data) => {
973
+ this.user = data;
974
+ this.emitter.emit('login', data);
975
+ return data;
976
+ })
977
+ .catch((er) => {
978
+ this.emitter.emit('login:error', er);
979
+ throw er;
980
+ });
981
+ }
982
+ _cleanActiveRequests(request) {
983
+ const activeRequestIndex = this.activeRequests.indexOf(request);
984
+ if (activeRequestIndex !== -1) {
985
+ this.activeRequests.splice(activeRequestIndex, 1);
986
+ }
987
+ }
988
+ _handleHttpError(er) {
989
+ if (er) {
990
+ if (er instanceof NgwError) {
991
+ if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
992
+ throw new ResourceNotFoundError(er);
993
+ }
994
+ else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
995
+ throw new InsufficientPermissionsError(er);
996
+ }
997
+ }
998
+ }
999
+ return er;
1000
+ }
1001
+ }
1002
+ NgwConnector$1.errors = {
1003
+ NgwError,
1004
+ ResourceNotFoundError,
1005
+ };
1150
1006
 
1151
- /**
1152
- * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
1153
- *
1154
- * @remarks
1155
- * 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.
1156
- *
1157
- * @packageDocumentation
1158
- * @module ngw-connector
1159
- */
1007
+ /**
1008
+ * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
1009
+ *
1010
+ * @remarks
1011
+ * 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.
1012
+ *
1013
+ * @packageDocumentation
1014
+ * @module ngw-connector
1015
+ */
1160
1016
  var NgwConnector = NgwConnector$1;
1161
1017
 
1162
1018
  module.exports = NgwConnector;