@nextgis/ngw-connector 3.0.0-alpha.3 → 3.0.0-alpha.4

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.
package/lib/index.d.ts CHANGED
@@ -42,6 +42,49 @@ interface FeatureItem<F = FeatureProperties, G extends Geometry | string = Geome
42
42
  }
43
43
  type FeatureItemToNgw<F = FeatureProperties, G extends Geometry | string = Geometry> = FeatureItem<F, G>;
44
44
 
45
+ /**
46
+ * Represents an item in a legend, with additional rendering and indexing information.
47
+ */
48
+ interface LegendItem {
49
+ /**
50
+ * The index of the legend item.
51
+ */
52
+ index: number;
53
+ /**
54
+ * A flag indicating whether this legend item should be rendered.
55
+ */
56
+ render: boolean | null;
57
+ /**
58
+ * The display name of the legend item.
59
+ */
60
+ display_name: string;
61
+ /**
62
+ * The symbol associated with this legend item.
63
+ */
64
+ icon: LegendItemSymbol;
65
+ }
66
+ /**
67
+ * Represents a symbol in a legend item.
68
+ */
69
+ interface LegendItemSymbol {
70
+ /**
71
+ * The format of the symbol, e.g., 'svg', 'png'.
72
+ */
73
+ format: string;
74
+ /**
75
+ * The actual data of the symbol in a specified format.
76
+ * This could be a base64 encoded string, SVG path, etc.
77
+ */
78
+ data: string;
79
+ }
80
+ /**
81
+ * Represents a legend for a specific layer.
82
+ */
83
+ interface LayerLegend {
84
+ layerId: string;
85
+ legend: LegendItem[];
86
+ }
87
+
45
88
  interface RequestItemsParamsMap {
46
89
  'pyramid.static': {
47
90
  skey: number;
@@ -693,14 +736,6 @@ interface SrsItem {
693
736
  id: number;
694
737
  wkt: string;
695
738
  }
696
- interface Icon {
697
- format: string;
698
- data: string;
699
- }
700
- interface RenderLegendSymbol {
701
- display_name: string;
702
- icon: Icon;
703
- }
704
739
  interface FeatureLayerCount {
705
740
  total_count: number;
706
741
  }
@@ -754,7 +789,7 @@ interface GetRequestItemsResponseMap extends RequestItemKeys {
754
789
  'feature_layer.feature.count': FeatureLayerCount;
755
790
  'pyramid.company_logo': string;
756
791
  'spatial_ref_sys.collection': SrsItem[];
757
- 'render.legend_symbols': RenderLegendSymbol[];
792
+ 'render.legend_symbols': LegendItem[];
758
793
  }
759
794
  interface IdOnly {
760
795
  id: number;
@@ -1196,4 +1231,4 @@ declare class NgwConnector {
1196
1231
  private _handleHttpError;
1197
1232
  }
1198
1233
 
1199
- export { type BaseRequestOptions, type BasemapResource, type BasemapWebmap, type BasemapWebmapItem, type BookmarkProperties, type CreatedResource, type Credentials, type DeleteRequestItemsResponseMap, type FeatureItem, type FeatureItemAttachment, type FeatureItemExtensions, type FeatureItemToNgw, type FeatureLayerCount, type FeatureLayerField, type FeatureLayersIdentify, type FeatureLayersIdentifyItems, type FeatureResource, type FileBucket, type FileMeta, type FileUploadResp, type GeometryType, type GetChildrenOfOptions, type GetRequestItemsResponseMap, type IdOnly, type LayerFeature, type LoadingQueue, type LookupTableResource, type NgwConnectorOptions, type NgwDateFormat, type NgwDateTimeFormat, type NgwExceptions, type NgwExtent, type NgwFile, type NgwLayerIdentifyError, type NgwTimeFormat, type Params, type PatchRequestItemsResponseMap, type Permission, type PostRequestItemsResponseMap, type PutRequestItemsResponseMap, type PyramidRoute, type PyramidSettings, type PyramidSettingsPyramid, type PyramidSettingsPyramidCompanyLogo, type RenderLegendSymbol, type RequestHeaders, type RequestItemAdditionalParams, type RequestItemKeys, type RequestItemsParams, type RequestItemsParamsMap, type RequestItemsResponseMap, type RequestMethods, type RequestOptions, type RequestTransformFunction, type Resmeta, type Resource, type ResourceCls, type ResourceDefinition, type ResourceHierarchy, type ResourceIdKeynameDef, type ResourceItem, type ResourceItemDatatype, type ResourceItemMain, type ResourceStoreItem, type ResourceStoreItemDefault, type ResourceStoreItemProperties, type Router, type SrsItem, type TreeGroup, type TreeItem, type TreeLayer, type UserInfo, type VectorFieldDatatype, type VectorLayer, type VectorLayerResourceItem, type WebmapResource, type WmsClientConnection, type WmsClientLayer, type WmsServerService, type WmsServerServiceLayer, NgwConnector as default };
1234
+ export { type BaseRequestOptions, type BasemapResource, type BasemapWebmap, type BasemapWebmapItem, type BookmarkProperties, type CreatedResource, type Credentials, type DeleteRequestItemsResponseMap, type FeatureItem, type FeatureItemAttachment, type FeatureItemExtensions, type FeatureItemToNgw, type FeatureLayerCount, type FeatureLayerField, type FeatureLayersIdentify, type FeatureLayersIdentifyItems, type FeatureResource, type FileBucket, type FileMeta, type FileUploadResp, type GeometryType, type GetChildrenOfOptions, type GetRequestItemsResponseMap, type IdOnly, type LayerFeature, type LayerLegend, type LegendItem, type LegendItemSymbol, type LoadingQueue, type LookupTableResource, type NgwConnectorOptions, type NgwDateFormat, type NgwDateTimeFormat, type NgwExceptions, type NgwExtent, type NgwFile, type NgwLayerIdentifyError, type NgwTimeFormat, type Params, type PatchRequestItemsResponseMap, type Permission, type PostRequestItemsResponseMap, type PutRequestItemsResponseMap, type PyramidRoute, type PyramidSettings, type PyramidSettingsPyramid, type PyramidSettingsPyramidCompanyLogo, type RequestHeaders, type RequestItemAdditionalParams, type RequestItemKeys, type RequestItemsParams, type RequestItemsParamsMap, type RequestItemsResponseMap, type RequestMethods, type RequestOptions, type RequestTransformFunction, type Resmeta, type Resource, type ResourceCls, type ResourceDefinition, type ResourceHierarchy, type ResourceIdKeynameDef, type ResourceItem, type ResourceItemDatatype, type ResourceItemMain, type ResourceStoreItem, type ResourceStoreItemDefault, type ResourceStoreItemProperties, type Router, type SrsItem, type TreeGroup, type TreeItem, type TreeLayer, type UserInfo, type VectorFieldDatatype, type VectorLayer, type VectorLayerResourceItem, type WebmapResource, type WmsClientConnection, type WmsClientLayer, type WmsServerService, type WmsServerServiceLayer, NgwConnector as default };
@@ -1,4 +1,4 @@
1
- /** Bundle of @nextgis/ngw-connector; version: 3.0.0-alpha.3; author: NextGIS */
1
+ /** Bundle of @nextgis/ngw-connector; version: 3.0.0-alpha.4; author: NextGIS */
2
2
  'use strict';
3
3
 
4
4
  var events = require('events');
@@ -7,7 +7,7 @@ var utils = require('@nextgis/utils');
7
7
 
8
8
  var pkg = {
9
9
  name: "@nextgis/ngw-connector",
10
- version: "3.0.0-alpha.3",
10
+ version: "3.0.0-alpha.4",
11
11
  _priority: 12,
12
12
  description: "A lightweight HTTP client optimized for use with NextGIS Web API",
13
13
  main: "index.js",
@@ -16,9 +16,9 @@ var pkg = {
16
16
  jsdelivr: "lib/ngw-connector.global.prod.js",
17
17
  types: "lib/index.d.ts",
18
18
  dependencies: {
19
- "@nextgis/cache": "^3.0.0-alpha.3",
19
+ "@nextgis/cache": "^3.0.0-alpha.4",
20
20
  "@nextgis/cancelable-promise": "^3.0.0-alpha.3",
21
- "@nextgis/utils": "^3.0.0-alpha.3",
21
+ "@nextgis/utils": "^3.0.0-alpha.4",
22
22
  "@types/events": "^3.0.0",
23
23
  events: "*",
24
24
  "form-data": "^4.0.0"
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("events"),t=require("@nextgis/cache"),r=require("@nextgis/utils"),s="3.0.0-alpha.3",i=Object.defineProperty,o=(e,t,r)=>((e,t,r)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class n extends Error{constructor(e){super(),o(this,"name","NgwError"),o(this,"title"),o(this,"message"),o(this,"detail"),o(this,"exception"),o(this,"status_code"),o(this,"data"),o(this,"guru_meditation"),Object.assign(this,e),Object.setPrototypeOf(this,n.prototype)}}var c=Object.defineProperty,a=(e,t,r)=>((e,t,r)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class u extends n{constructor(e){super(e),a(this,"name","ResourceNotFoundError"),a(this,"exception","nextgisweb.resource.exception.ResourceNotFound"),Object.setPrototypeOf(this,u.prototype)}}function h(e){return"[object Object]"===Object.prototype.toString.call(e)}const l=["description"];function d(e,t=""){t=t?t+"__":"";const s={};for(const[i,o]of Object.entries(e))if(-1===l.indexOf(i))if(h(o))if("owner_user"===i){const e=d(o,i);Object.assign(s,e)}else"parent"===i&&"id"in o&&(s.parent_id=o.id);else r.defined(o)&&(s[t+i]=o);return s}var f=Object.defineProperty,p=(e,t,r)=>((e,t,r)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class m{constructor({connector:e,cacheId:r}){p(this,"cache"),p(this,"connector"),this.connector=e,this.cache=new t({namespace:r})}getOne(e,t){const r={...t};return"string"==typeof e||"number"==typeof e||h(e),"string"==typeof e?this._fetchResourceBy({keyname:e},r):"number"==typeof e?this._fetchResourceById(e,r):h(e)?this._fetchResourceBy(e,r):Promise.resolve(void 0)}getOneOrFail(e,t){return this.getOne(e,t).then((e=>{if(e)return e;throw new u}))}getId(e,t){return"number"==typeof e?Promise.resolve(e):"string"==typeof e||h(e)?this.getOne(e,t).then((e=>{if(e)return e.resource.id})):Promise.resolve(void 0)}getIdOrFail(e,t){return this.getId(e,t).then((e=>{if(void 0===e)throw new Error;return e}))}getMany(e,t){return this._resourceCacheFilter(e).then((r=>{if(!r.length){const r={};return e.keyname?r.keyname=e.keyname:Object.assign(r,d(e)),this.connector.get("resource.search",t,{serialization:"full",...r}).then((e=>{if((null==t?void 0:t.cache)&&e)for(const t of e)this.cache.add("resource.item",Promise.resolve(t),{id:t.resource.id});return e}))}return r}))}getParent(e,t){return this.getOne(e,t).then((e=>e?this.getOne(e.resource.parent.id,t):Promise.resolve(void 0)))}getChildrenOf(e,t){return this.getIdOrFail(e).then((e=>this._getChildrenOf(e,t)))}update(e,t){return this.getId(e).then((e=>{if(void 0!==e)return this.connector.put("resource.item",{data:t},{id:e})}))}delete(e){return this.getId(e).then((e=>{if(void 0!==e)return this.connector.delete("resource.item",null,{id:e}).then((()=>{this._cleanResourceItemCache(e)}))}))}_getChildrenOf(e,t,r=[]){return this.connector.get("resource.collection",t,{parent:e}).then((e=>{const s=[];for(const i of e)(null==t?void 0:t.cache)&&this.cache.add("resource.item",Promise.resolve(i),{id:i.resource.id}),r.push(i),(null==t?void 0:t.recursive)&&i.resource.children&&s.push(this._getChildrenOf(i.resource.id,t,r));return s.length?Promise.all(s).then((()=>r)):r}))}async _cleanResourceItemCache(e){var t;const r=this.cache.all(),s=[];for(const i of r){const r=null==(t=i.props)?void 0:t.id;if(["resource.item","resource"].includes(i.key)&&void 0!==r)if("number"==typeof r)r===e&&s.push(i);else{await this.getId(r)===e&&s.push(i)}}for(const i of s)this.cache.delete(i)}_fetchResourceById(e,t){return this.connector.get("resource.item",t,{id:e})}_fetchResourceBy(e,t){return this.getMany(e,t).then((e=>e[0]))}_resourceCacheFilter(e){return Promise.all(this.cache.matchAll("resource.item")).then((t=>(t.filter((t=>{if(t)return e.keyname&&t.resource.keyname?e.keyname===t.resource.keyname:r.defined(e.id)&&r.defined(t.resource.id)?e.id===t.resource.id:r.objectDeepEqual(e,t.resource)})),[])))}}const g=[];function y(e){g.push(e)}class b extends Error{constructor(e="AbortError"){super(e),this.name="AbortError"}}var w=Object.defineProperty,v=(e,t,r)=>((e,t,r)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class O extends n{constructor(e){super(e),v(this,"name","InsufficientPermissionsError"),v(this,"exception","nextgisweb.core.exception.InsufficientPermissions"),Object.setPrototypeOf(this,O.prototype)}}const R=/\{ *([\w_-]+) *\}/g;function E(e,t){return e.replace(R,((e,r)=>{let s=t[r];if(void 0===s)throw new Error("No value provided for letiable "+e);return"function"==typeof s&&(s=s(t)),s}))}let q;{const e=require("url"),t=require("http"),s=require("https"),i=require("form-data"),o=r=>({"http:":t,"https:":s}[e.parse(r).protocol||"https:"]);q=(e,t,s={},n,c)=>{const{file:a,headers:u,method:l,data:d,responseType:f}=s,p=new Promise(((t,s)=>{const n=o(e);if(!n)throw new Error(`Given URL '${e}' is not correct`);{const o={headers:u||{},method:l},p="string"==typeof d?d:JSON.stringify(d);let m,g=a;if(a){const e={};if(h(a)&&"file"in a&&("filename"in a||"name"in a)){const{file:t,name:r,...s}=a;r&&!s.filename&&(s.filename=r),Object.assign(e,s),g=t}if(m=new i,m.append("file",g,e),d)for(const t in d)m.append(t,d[t]);Object.assign(o.headers,{...m.getHeaders()})}void 0!==p&&Object.assign(o.headers,{"content-type":"application/json","content-length":Buffer.byteLength(p)});const y=n.request(e,o,(e=>{let i="";e.on("data",(e=>{i+=e})),e.on("end",(()=>{if(i)if("blob"===f)t(i);else{let o;try{o=JSON.parse(i),o&&o.status_code&&o.status_code&&s(o.message)}catch(e){s(e)}void 0!==o&&(!function(e){return!!r.isObject(e)&&e.status_code&&e.exception&&e.title}(o)?t(o):s("extractError(json)"))}s("no data")}))}));m&&m.pipe(y),y.on("error",(e=>{s(e)})),p&&y.write(p),c((()=>{y.abort()})),y.end()}}));return p.then((e=>(t&&t(e),e))).catch((e=>{if(!n)throw new Error(e);n(e)}))}}var I=Object.defineProperty,_=(e,t,r)=>((e,t,r)=>t in e?I(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);let P=0,j=0;class x{constructor(i){this.options=i,_(this,"id",P++),_(this,"emitter",new e.EventEmitter),_(this,"user"),_(this,"resources"),_(this,"cache"),_(this,"withCredentials"),_(this,"client",`NextGIS-NGW-Connector/${s}`),_(this,"routeStr","/api/component/pyramid/route"),_(this,"activeRequests",{}),_(this,"requestTransform");const o=function(e){return g.find((t=>{if(t.options.baseUrl===e.baseUrl){if(!e.auth)return!0;if(t.options.auth)return r.objectDeepEqual(t.options.auth,e.auth)}}))}(i);if(this.cache=new t({namespace:i.cacheId}),o)return o;{const{route:e,requestTransform:t,withCredentials:r}=this.options;e&&(this.routeStr=e),t&&(this.requestTransform=t),void 0!==r&&(this.withCredentials=r),this.resources=new m({connector:this,cacheId:i.cacheId}),y(this)}}static create(e){return new this(e)}clearCache(){this.cache.clean(),this.resources.cache.clean()}setRequestTransform(e){this.requestTransform=e}setNgw(e){this.logout(),this.options.baseUrl=e,y(this)}async connect(){const e=this.options.auth;if(e){const{login:t,password:r}=e;t&&r&&await this._login({login:t,password:r})}const t=`${this.routeStr}?client=${this.client}`;return await this.makeQuery(t,{},{cacheName:"route",cache:!0,cacheProps:{id:this.id,auth:e,baseUrl:this.options.baseUrl}})}login(e,t){return this.logout(),y(this),this._login(e,t)}logout(){this.abort(),function(e){const t=g.indexOf(e);-1!==t&&g.splice(t,1)}(this),this.options.auth=void 0,this.user=void 0,this.clearCache(),this.emitter.emit("logout")}async getUserInfo(e,t){if(this.user&&this.user.id)return this.user;e&&(this.options.auth=e);const r={headers:this.getAuthorizationHeaders(e),...t};return this.makeQuery("/api/component/auth/current_user",{},r)}getAuthorizationHeaders(e){const t=this.makeClientId(e);if(t)return{Authorization:`Basic ${t}`}}makeClientId(e){if(e=e||this.options.auth){const{login:t,password:r}=e,s=[t,r].map(encodeURIComponent).join(":");return Buffer.from(s).toString("base64")}}abort(){for(const e of Object.values(this.activeRequests))e.abort();this.activeRequests={}}getActiveApiRequests(){return{...this.activeRequests}}apiRequest(e,t={},s={}){var i;t=null!=(i=s.params)?i:t;return async function(e){const{params:t,name:r,connector:s,requestOptions:i}=e,o=await s.connect();let n=o&&o[r];if(n){n=[...n];let e=n.shift();if(n.length){const r={};for(let e=0;e<n.length;e++){const s=n[e];if(r[e]=`{${s}}`,void 0===t[s])throw new Error(`\`${s}\` URL API argument is not specified`)}e&&(e=E(e,r))}if(t){const r=[],s=t.paramList;Array.isArray(s)&&s.forEach((([e,t])=>{r.push(`${e}=${t}`)}));for(const e in t)-1===n.indexOf(e)&&r.push(`${e}=${t[e]}`);r.length&&(e=`${e}?${r.join("&")}`)}if(e)return s.makeQuery(e,t,{cacheName:r,...i});throw new Error("Request URL is not set")}}({name:e,params:r.objectRemoveEmpty(t),requestOptions:s,connector:this})}post(e,t,r){return(t=t||{}).method="POST",this.apiRequest(e,r,t)}get(e,t,r){return(t=t||{}).method="GET",this.apiRequest(e,r,t)}patch(e,t,r){return(t=t||{}).method="PATCH",this.apiRequest(e,r,t)}put(e,t,r){return(t=t||{}).method="PUT",this.apiRequest(e,r,t)}delete(e,t,r){return(t=t||{}).method="DELETE",this.apiRequest(e,r,t)}async makeQuery(e,t,s={}){var i;if(!(e=(this.options.baseUrl?this.options.baseUrl:"")+e))throw new Error("Empty `url` not allowed");if(t){const{paramList:r,...s}=t;e=E(e,s)}e=encodeURI(r.fixUrlStr(e)),s={withCredentials:this.withCredentials,...s};const{cache:o,signal:n,method:c="GET",headers:a,cacheName:u,cacheProps:h,responseType:l,withCredentials:d}=s,f=new AbortController,p=f.signal;if(n){if(n.aborted)throw new b;n.addEventListener("abort",(()=>{f.abort()}))}s.signal=p;const m=async()=>{const t=j++;this.activeRequests[t]=f;try{return this._loadData(e,s)}finally{this._cleanActiveRequest(t)}};if(o&&"GET"===c){const s=h||{...r.objectRemoveEmpty({headers:a,withCredentials:d,responseType:l,baseUrl:this.options.baseUrl,userId:null==(i=this.user)?void 0:i.id}),params:t};return this.cache.add(u||e,m,s,!1)}return m()}getResource(e,t){return this.resources.getOne(e,t)}getResourceOrFail(e,t){return this.resources.getOneOrFail(e,t)}getResourceBy(e){return this.resources.getOne(e)}getResourceByKeyname(e){return this.resources.getOne(e)}getResourceById(e){return this.resources.getOne(e)}getResourceId(e,t){return this.resources.getId(e,t)}getResourceIdOrFail(e,t){return this.resources.getIdOrFail(e,t)}getResourcesBy(e,t){return this.resources.getMany(e,t)}getResourceParent(e,t){return this.resources.getParent(e,t)}getResourceChildren(e,t){return this.resources.getChildrenOf(e,t)}updateResource(e,t){return this.resources.update(e,t)}deleteResource(e){return this.resources.delete(e)}_loadData(e,t){return t.responseType=t.responseType||"json",new Promise(((r,s)=>{var i;if(this.user&&((t=t||{}).headers={...this.getAuthorizationHeaders(),...t.headers}),this.requestTransform){const[r,s]=this.requestTransform(e,t);e=r,t=s}let o;q(e,r,t,s,(e=>{o=e})),null==(i=t.signal)||i.addEventListener("abort",(()=>{void 0!==o&&o(),s(new b)}))})).catch((e=>{if("AbortError"!==e.name){const t=this._handleHttpError(e);if(t)throw t}throw e}))}async _login(e,t){try{const r=await this.getUserInfo(e,t);return this.user=r,this.emitter.emit("login",r),r}catch(r){throw this.emitter.emit("login:error",r),r}}_cleanActiveRequest(e){delete this.activeRequests[e]}_handleHttpError(e){if(e&&e instanceof n){if("nextgisweb.resource.exception.ResourceNotFound"===e.exception)throw new u(e);if("nextgisweb.core.exception.InsufficientPermissions"===e.exception)throw new O(e)}return e}}_(x,"errors",{NgwError:n,ResourceNotFoundError:u}),module.exports=x;
1
+ "use strict";var e=require("events"),t=require("@nextgis/cache"),r=require("@nextgis/utils"),s="3.0.0-alpha.4",i=Object.defineProperty,o=(e,t,r)=>((e,t,r)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class n extends Error{constructor(e){super(),o(this,"name","NgwError"),o(this,"title"),o(this,"message"),o(this,"detail"),o(this,"exception"),o(this,"status_code"),o(this,"data"),o(this,"guru_meditation"),Object.assign(this,e),Object.setPrototypeOf(this,n.prototype)}}var c=Object.defineProperty,a=(e,t,r)=>((e,t,r)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class u extends n{constructor(e){super(e),a(this,"name","ResourceNotFoundError"),a(this,"exception","nextgisweb.resource.exception.ResourceNotFound"),Object.setPrototypeOf(this,u.prototype)}}function h(e){return"[object Object]"===Object.prototype.toString.call(e)}const l=["description"];function d(e,t=""){t=t?t+"__":"";const s={};for(const[i,o]of Object.entries(e))if(-1===l.indexOf(i))if(h(o))if("owner_user"===i){const e=d(o,i);Object.assign(s,e)}else"parent"===i&&"id"in o&&(s.parent_id=o.id);else r.defined(o)&&(s[t+i]=o);return s}var f=Object.defineProperty,p=(e,t,r)=>((e,t,r)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class m{constructor({connector:e,cacheId:r}){p(this,"cache"),p(this,"connector"),this.connector=e,this.cache=new t({namespace:r})}getOne(e,t){const r={...t};return"string"==typeof e||"number"==typeof e||h(e),"string"==typeof e?this._fetchResourceBy({keyname:e},r):"number"==typeof e?this._fetchResourceById(e,r):h(e)?this._fetchResourceBy(e,r):Promise.resolve(void 0)}getOneOrFail(e,t){return this.getOne(e,t).then((e=>{if(e)return e;throw new u}))}getId(e,t){return"number"==typeof e?Promise.resolve(e):"string"==typeof e||h(e)?this.getOne(e,t).then((e=>{if(e)return e.resource.id})):Promise.resolve(void 0)}getIdOrFail(e,t){return this.getId(e,t).then((e=>{if(void 0===e)throw new Error;return e}))}getMany(e,t){return this._resourceCacheFilter(e).then((r=>{if(!r.length){const r={};return e.keyname?r.keyname=e.keyname:Object.assign(r,d(e)),this.connector.get("resource.search",t,{serialization:"full",...r}).then((e=>{if((null==t?void 0:t.cache)&&e)for(const t of e)this.cache.add("resource.item",Promise.resolve(t),{id:t.resource.id});return e}))}return r}))}getParent(e,t){return this.getOne(e,t).then((e=>e?this.getOne(e.resource.parent.id,t):Promise.resolve(void 0)))}getChildrenOf(e,t){return this.getIdOrFail(e).then((e=>this._getChildrenOf(e,t)))}update(e,t){return this.getId(e).then((e=>{if(void 0!==e)return this.connector.put("resource.item",{data:t},{id:e})}))}delete(e){return this.getId(e).then((e=>{if(void 0!==e)return this.connector.delete("resource.item",null,{id:e}).then((()=>{this._cleanResourceItemCache(e)}))}))}_getChildrenOf(e,t,r=[]){return this.connector.get("resource.collection",t,{parent:e}).then((e=>{const s=[];for(const i of e)(null==t?void 0:t.cache)&&this.cache.add("resource.item",Promise.resolve(i),{id:i.resource.id}),r.push(i),(null==t?void 0:t.recursive)&&i.resource.children&&s.push(this._getChildrenOf(i.resource.id,t,r));return s.length?Promise.all(s).then((()=>r)):r}))}async _cleanResourceItemCache(e){var t;const r=this.cache.all(),s=[];for(const i of r){const r=null==(t=i.props)?void 0:t.id;if(["resource.item","resource"].includes(i.key)&&void 0!==r)if("number"==typeof r)r===e&&s.push(i);else{await this.getId(r)===e&&s.push(i)}}for(const i of s)this.cache.delete(i)}_fetchResourceById(e,t){return this.connector.get("resource.item",t,{id:e})}_fetchResourceBy(e,t){return this.getMany(e,t).then((e=>e[0]))}_resourceCacheFilter(e){return Promise.all(this.cache.matchAll("resource.item")).then((t=>(t.filter((t=>{if(t)return e.keyname&&t.resource.keyname?e.keyname===t.resource.keyname:r.defined(e.id)&&r.defined(t.resource.id)?e.id===t.resource.id:r.objectDeepEqual(e,t.resource)})),[])))}}const g=[];function y(e){g.push(e)}class b extends Error{constructor(e="AbortError"){super(e),this.name="AbortError"}}var w=Object.defineProperty,v=(e,t,r)=>((e,t,r)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class O extends n{constructor(e){super(e),v(this,"name","InsufficientPermissionsError"),v(this,"exception","nextgisweb.core.exception.InsufficientPermissions"),Object.setPrototypeOf(this,O.prototype)}}const R=/\{ *([\w_-]+) *\}/g;function E(e,t){return e.replace(R,((e,r)=>{let s=t[r];if(void 0===s)throw new Error("No value provided for letiable "+e);return"function"==typeof s&&(s=s(t)),s}))}let q;{const e=require("url"),t=require("http"),s=require("https"),i=require("form-data"),o=r=>({"http:":t,"https:":s}[e.parse(r).protocol||"https:"]);q=(e,t,s={},n,c)=>{const{file:a,headers:u,method:l,data:d,responseType:f}=s,p=new Promise(((t,s)=>{const n=o(e);if(!n)throw new Error(`Given URL '${e}' is not correct`);{const o={headers:u||{},method:l},p="string"==typeof d?d:JSON.stringify(d);let m,g=a;if(a){const e={};if(h(a)&&"file"in a&&("filename"in a||"name"in a)){const{file:t,name:r,...s}=a;r&&!s.filename&&(s.filename=r),Object.assign(e,s),g=t}if(m=new i,m.append("file",g,e),d)for(const t in d)m.append(t,d[t]);Object.assign(o.headers,{...m.getHeaders()})}void 0!==p&&Object.assign(o.headers,{"content-type":"application/json","content-length":Buffer.byteLength(p)});const y=n.request(e,o,(e=>{let i="";e.on("data",(e=>{i+=e})),e.on("end",(()=>{if(i)if("blob"===f)t(i);else{let o;try{o=JSON.parse(i),o&&o.status_code&&o.status_code&&s(o.message)}catch(e){s(e)}void 0!==o&&(!function(e){return!!r.isObject(e)&&e.status_code&&e.exception&&e.title}(o)?t(o):s("extractError(json)"))}s("no data")}))}));m&&m.pipe(y),y.on("error",(e=>{s(e)})),p&&y.write(p),c((()=>{y.abort()})),y.end()}}));return p.then((e=>(t&&t(e),e))).catch((e=>{if(!n)throw new Error(e);n(e)}))}}var I=Object.defineProperty,_=(e,t,r)=>((e,t,r)=>t in e?I(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);let P=0,j=0;class x{constructor(i){this.options=i,_(this,"id",P++),_(this,"emitter",new e.EventEmitter),_(this,"user"),_(this,"resources"),_(this,"cache"),_(this,"withCredentials"),_(this,"client",`NextGIS-NGW-Connector/${s}`),_(this,"routeStr","/api/component/pyramid/route"),_(this,"activeRequests",{}),_(this,"requestTransform");const o=function(e){return g.find((t=>{if(t.options.baseUrl===e.baseUrl){if(!e.auth)return!0;if(t.options.auth)return r.objectDeepEqual(t.options.auth,e.auth)}}))}(i);if(this.cache=new t({namespace:i.cacheId}),o)return o;{const{route:e,requestTransform:t,withCredentials:r}=this.options;e&&(this.routeStr=e),t&&(this.requestTransform=t),void 0!==r&&(this.withCredentials=r),this.resources=new m({connector:this,cacheId:i.cacheId}),y(this)}}static create(e){return new this(e)}clearCache(){this.cache.clean(),this.resources.cache.clean()}setRequestTransform(e){this.requestTransform=e}setNgw(e){this.logout(),this.options.baseUrl=e,y(this)}async connect(){const e=this.options.auth;if(e){const{login:t,password:r}=e;t&&r&&await this._login({login:t,password:r})}const t=`${this.routeStr}?client=${this.client}`;return await this.makeQuery(t,{},{cacheName:"route",cache:!0,cacheProps:{id:this.id,auth:e,baseUrl:this.options.baseUrl}})}login(e,t){return this.logout(),y(this),this._login(e,t)}logout(){this.abort(),function(e){const t=g.indexOf(e);-1!==t&&g.splice(t,1)}(this),this.options.auth=void 0,this.user=void 0,this.clearCache(),this.emitter.emit("logout")}async getUserInfo(e,t){if(this.user&&this.user.id)return this.user;e&&(this.options.auth=e);const r={headers:this.getAuthorizationHeaders(e),...t};return this.makeQuery("/api/component/auth/current_user",{},r)}getAuthorizationHeaders(e){const t=this.makeClientId(e);if(t)return{Authorization:`Basic ${t}`}}makeClientId(e){if(e=e||this.options.auth){const{login:t,password:r}=e,s=[t,r].map(encodeURIComponent).join(":");return Buffer.from(s).toString("base64")}}abort(){for(const e of Object.values(this.activeRequests))e.abort();this.activeRequests={}}getActiveApiRequests(){return{...this.activeRequests}}apiRequest(e,t={},s={}){var i;t=null!=(i=s.params)?i:t;return async function(e){const{params:t,name:r,connector:s,requestOptions:i}=e,o=await s.connect();let n=o&&o[r];if(n){n=[...n];let e=n.shift();if(n.length){const r={};for(let e=0;e<n.length;e++){const s=n[e];if(r[e]=`{${s}}`,void 0===t[s])throw new Error(`\`${s}\` URL API argument is not specified`)}e&&(e=E(e,r))}if(t){const r=[],s=t.paramList;Array.isArray(s)&&s.forEach((([e,t])=>{r.push(`${e}=${t}`)}));for(const e in t)-1===n.indexOf(e)&&r.push(`${e}=${t[e]}`);r.length&&(e=`${e}?${r.join("&")}`)}if(e)return s.makeQuery(e,t,{cacheName:r,...i});throw new Error("Request URL is not set")}}({name:e,params:r.objectRemoveEmpty(t),requestOptions:s,connector:this})}post(e,t,r){return(t=t||{}).method="POST",this.apiRequest(e,r,t)}get(e,t,r){return(t=t||{}).method="GET",this.apiRequest(e,r,t)}patch(e,t,r){return(t=t||{}).method="PATCH",this.apiRequest(e,r,t)}put(e,t,r){return(t=t||{}).method="PUT",this.apiRequest(e,r,t)}delete(e,t,r){return(t=t||{}).method="DELETE",this.apiRequest(e,r,t)}async makeQuery(e,t,s={}){var i;if(!(e=(this.options.baseUrl?this.options.baseUrl:"")+e))throw new Error("Empty `url` not allowed");if(t){const{paramList:r,...s}=t;e=E(e,s)}e=encodeURI(r.fixUrlStr(e)),s={withCredentials:this.withCredentials,...s};const{cache:o,signal:n,method:c="GET",headers:a,cacheName:u,cacheProps:h,responseType:l,withCredentials:d}=s,f=new AbortController,p=f.signal;if(n){if(n.aborted)throw new b;n.addEventListener("abort",(()=>{f.abort()}))}s.signal=p;const m=async()=>{const t=j++;this.activeRequests[t]=f;try{return this._loadData(e,s)}finally{this._cleanActiveRequest(t)}};if(o&&"GET"===c){const s=h||{...r.objectRemoveEmpty({headers:a,withCredentials:d,responseType:l,baseUrl:this.options.baseUrl,userId:null==(i=this.user)?void 0:i.id}),params:t};return this.cache.add(u||e,m,s,!1)}return m()}getResource(e,t){return this.resources.getOne(e,t)}getResourceOrFail(e,t){return this.resources.getOneOrFail(e,t)}getResourceBy(e){return this.resources.getOne(e)}getResourceByKeyname(e){return this.resources.getOne(e)}getResourceById(e){return this.resources.getOne(e)}getResourceId(e,t){return this.resources.getId(e,t)}getResourceIdOrFail(e,t){return this.resources.getIdOrFail(e,t)}getResourcesBy(e,t){return this.resources.getMany(e,t)}getResourceParent(e,t){return this.resources.getParent(e,t)}getResourceChildren(e,t){return this.resources.getChildrenOf(e,t)}updateResource(e,t){return this.resources.update(e,t)}deleteResource(e){return this.resources.delete(e)}_loadData(e,t){return t.responseType=t.responseType||"json",new Promise(((r,s)=>{var i;if(this.user&&((t=t||{}).headers={...this.getAuthorizationHeaders(),...t.headers}),this.requestTransform){const[r,s]=this.requestTransform(e,t);e=r,t=s}let o;q(e,r,t,s,(e=>{o=e})),null==(i=t.signal)||i.addEventListener("abort",(()=>{void 0!==o&&o(),s(new b)}))})).catch((e=>{if("AbortError"!==e.name){const t=this._handleHttpError(e);if(t)throw t}throw e}))}async _login(e,t){try{const r=await this.getUserInfo(e,t);return this.user=r,this.emitter.emit("login",r),r}catch(r){throw this.emitter.emit("login:error",r),r}}_cleanActiveRequest(e){delete this.activeRequests[e]}_handleHttpError(e){if(e&&e instanceof n){if("nextgisweb.resource.exception.ResourceNotFound"===e.exception)throw new u(e);if("nextgisweb.core.exception.InsufficientPermissions"===e.exception)throw new O(e)}return e}}_(x,"errors",{NgwError:n,ResourceNotFoundError:u}),module.exports=x;
2
2
  //# sourceMappingURL=ngw-connector.cjs.prod.js.map
@@ -1,4 +1,4 @@
1
- /** Bundle of @nextgis/ngw-connector; version: 3.0.0-alpha.3; author: NextGIS */
1
+ /** Bundle of @nextgis/ngw-connector; version: 3.0.0-alpha.4; author: NextGIS */
2
2
  var domain;
3
3
 
4
4
  // This constructor is used to store event handlers. Instantiating this is
@@ -644,7 +644,7 @@ let Cache = _Cache;
644
644
 
645
645
  var pkg = {
646
646
  name: "@nextgis/ngw-connector",
647
- version: "3.0.0-alpha.3",
647
+ version: "3.0.0-alpha.4",
648
648
  _priority: 12,
649
649
  description: "A lightweight HTTP client optimized for use with NextGIS Web API",
650
650
  main: "index.js",
@@ -653,9 +653,9 @@ var pkg = {
653
653
  jsdelivr: "lib/ngw-connector.global.prod.js",
654
654
  types: "lib/index.d.ts",
655
655
  dependencies: {
656
- "@nextgis/cache": "^3.0.0-alpha.3",
656
+ "@nextgis/cache": "^3.0.0-alpha.4",
657
657
  "@nextgis/cancelable-promise": "^3.0.0-alpha.3",
658
- "@nextgis/utils": "^3.0.0-alpha.3",
658
+ "@nextgis/utils": "^3.0.0-alpha.4",
659
659
  "@types/events": "^3.0.0",
660
660
  events: "*",
661
661
  "form-data": "^4.0.0"