@nextgis/ngw-connector 1.8.4 → 1.9.2

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,2 +1,2 @@
1
- var e,t={exports:{}},r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};e=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}t.exports=i,t.exports.once=function(e,t){return new Promise((function(r,n){function s(r){e.removeListener(t,i),n(r)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",s),r([].slice.call(arguments))}m(e,t,i,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&m(e,"error",t,r)}(e,s,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function h(e,t,r,n){var s,i,o,h;if(c(r),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),i=e._events),o=i[t]),void 0===o)o=i[t]=r,++e._eventsCount;else if("function"==typeof o?o=i[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(s=a(e))>0&&o.length>s&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,h=u,console&&console.warn&&console.warn(h)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},s=u.bind(n);return s.listener=r,n.wrapFn=s,s}function f(e,t,r){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?r?[s.listener||s]:[s]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(s):d(s,s.length)}function p(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function d(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function m(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(i){n.once&&e.removeEventListener(t,s),r(i)}))}}Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return a(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var s="error"===e,i=this._events;if(void 0!==i)s=s&&void 0===i.error;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)n(a,this,t);else{var h=a.length,u=d(a,h);for(r=0;r<h;++r)n(u[r],this,t)}return!0},i.prototype.on=i.prototype.addListener=function(e,t){return h(this,e,t,!1)},i.prototype.prependListener=function(e,t){return h(this,e,t,!0)},i.prototype.once=function(e,t){return c(t),this.on(e,l(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,l(this,e,t)),this},i.prototype.off=i.prototype.removeListener=function(e,t){var r,n,s,i,o;if(c(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,i=r.length-1;i>=0;i--)if(r[i]===t||r[i].listener===t){o=r[i].listener,s=i;break}if(s<0)return this;0===s?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,s),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},i.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var s,i=Object.keys(r);for(n=0;n<i.length;++n)"removeListener"!==(s=i[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},i.prototype.listeners=function(e){return f(this,e,!0)},i.prototype.rawListeners=function(e){return f(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},i.prototype.listenerCount=p,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]};class g extends Error{constructor(){super(),this.name="CancelError",Object.setPrototypeOf(this,g.prototype)}}class y{constructor(e={}){this.options=e,this._promises=new Map}get isLoaded(){return this._promises.size>0}remove(e){this._promises.has(e)&&(this._promises.delete(e),this._onStop())}get(e){return this._promises.get(e)}add(e,t){const r=t||e,n=this._promises.get(r);return this.options.onStart&&!this.isLoaded&&this.options.onStart(),n||(this._promises.set(r,e),e.finally((()=>{this.remove(r)})),e)}abort(){this.isLoaded&&(this._promises.forEach((e=>{e.cancel&&e.cancel()})),this._promises.clear(),this._onStop())}waitFunc(e,t=""){const r=this.get(t=t||e.name);return r||this.add(e(),t)}WaitForMe(e=""){const t=this.get.bind(this),r=this.add.bind(this);return function(n,s,i){const o=i.value;return e=e||s,i.value=function(...n){const s=t(e);if(s)return s;return r(o.apply(this,n),e)},i}}GetOrCreateDecorator(e=""){return this.WaitForMe(e)}_onStop(){this.options.onStop&&!this.isLoaded&&this.options.onStop()}}class v extends Error{constructor(){super(),this.name="TimeoutError",Object.setPrototypeOf(this,v.prototype)}}const _=(e,t,r,n)=>{try{e(r(n))}catch(e){t(e)}};let w=0;class b{constructor(e,t){this.id=w++,this._isCanceled=!1,this._isPending=!0,this._cancelHandlers=[],this._children=[],this._cancelPromise=new Promise(((e,t)=>{this._setCanceledCallback=t=>e(t||new g)}));const r=[this._cancelPromise,new Promise(((t,r)=>e((e=>{e instanceof b?this.attach(e):this._isPending=!1,t(e)}),(e=>{this._isPending=!1,r(e)}),(e=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(e)}))))];t&&r.push(new Promise(((e,r)=>{setTimeout((()=>{if(this._isPending)try{this.cancel()}finally{r(new v)}}),t)}))),this._promise=Promise.race(r)}static createControl(e){return new y(e)}static resolve(e){return new b((t=>t(e)))}static reject(e){return new b(((t,r)=>r(e)))}static all(e){return new b(((t,r)=>{Promise.all(e).then(t).catch(r)})).catch((t=>{if(t instanceof this.CancelError)for(const t of e)"cancel"in t&&t.cancel();throw t}))}attach(e){this._isCanceled?e.cancel():this._children.push(e)}then(e,t){const r=new b(((r,n)=>{if(this._promise){const s=e=>{t?_(r,n,t,e):n(e)};this._promise.then((t=>{this._isCanceled?s(t):e?_(r,n,e,t):r(t)}),s)}}));return r._parentPromise=this,this._children.push(r),r}catch(e){return this._isCanceled&&e&&e(new g),this.then(void 0,e)}finally(e){return this._promise?this._promise.finally(e):Promise.reject(this._isCanceled?new g:e)}cancel(){if(this._isCanceled||!this._isPending)return this;this._isCanceled=!0;const e=this._getTopParent();if(e&&e.cancel(),this._children&&this._children.forEach((e=>e.cancel())),this._isPending){if(this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){}this._setCanceledCallback&&this._setCanceledCallback()}return this._destroy(),this}_getTopParent(){let e=this._parentPromise,t=!!e;for(;t;)e&&e._parentPromise?(e=e._parentPromise,t=!!e):t=!1;return e}_destroy(){this._setCanceledCallback=void 0,this._cancelPromise=void 0,this._promise=void 0}}b.CancelError=g,b.TimeoutError=v,b.PromiseControl=y,Object.setPrototypeOf(b.prototype,Promise.prototype);var O=b;function E(e){return null!=e}function C(e,t,r,n){if(e instanceof Array)return t instanceof Array&&t.sort().join("")===e.sort().join("");if(e instanceof Date)return t instanceof Date&&""+e==""+t;if(e instanceof Function){if(!(t instanceof Function))return!1}else if(e instanceof Object)return t instanceof Object&&(e===r?t===n:P(e,t));return e===t}function P(e,t){const r=Object.keys(e).sort(),n=Object.keys(t).sort();if(r.length!==n.length)return!1;if(r.join("")!==n.join(""))return!1;for(let s=0;s<r.length;s++){if(!C(e[r[s]],t[n[s]],e,t))return!1}return!0}function L(e){const t={};return Object.keys(e).forEach((r=>{e[r]instanceof Array||e[r]!==Object(e[r])?void 0!==e[r]&&(t[r]=e[r]):t[r]=L(e[r])})),t}class x{constructor(){return this.cache=[],x.instance?x.instance:(x.instance=this,this)}clean(){this.cache.length=0}all(){return this.cache}add(e,t,r){const n=this._find(e,r);if(n)return n.value;{let n;n=t instanceof Function?t():t;const s=r&&JSON.parse(JSON.stringify(L(r)));return this.cache.push({key:e,value:n,options:s}),n instanceof Promise?(n.catch((t=>{throw this.delete(e,r),t})),n):n}}match(e,t){const r=this._find(e,t);if(r)return r.value}matchAll(e,t){return e?this.cache.filter((r=>this._filter(r,e,t))).map((e=>e.value)):this.cache.map((e=>e.value))}delete(e,t){const r=this.cache.filter((r=>this._filter(r,e,t)));for(const e of r){const t=this.cache.indexOf(e);this.cache.splice(t,1)}}_find(e,t){return this.cache.find((r=>this._filter(r,e,t)))}_filter(e,t,r){return e.key===t&&(!r||P(e.options||{},L(r)))}}var j=x;class R extends Error{constructor(e){super(),this.name="NgwError",Object.assign(this,e),Object.setPrototypeOf(this,R.prototype)}}class T extends Error{constructor(e){super(),this.name="NetworkError",Object.setPrototypeOf(this,T.prototype),this.message=`Unable to request ${e}.\n Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`}}let k;k=(e,t,r={},n,s)=>{r.method=r.method||"GET";const i=new XMLHttpRequest;i.open(r.method||"GET",e,!0),"blob"===r.responseType&&(i.responseType=r.responseType);const o=()=>{try{return JSON.parse(i.responseText)}catch(e){return i.responseText}};i.onload=()=>{-1!==[401,403,404,500].indexOf(i.status)&&n(new R(o())),((e=!1)=>{const s=e?n:t;"blob"===r.responseType?s(i.response):i.responseText?s(o()):n({message:""})})()},i.onerror=t=>{n(0===i.status?new T(e):t)},i.upload.onprogress=function(e){if(e.lengthComputable){const t=e.loaded/e.total*100;r.onProgress&&r.onProgress(t,e)}};const c=r.headers;if(c)for(const e in c){const t=c[e];"string"==typeof t&&i.setRequestHeader(e,t)}let a;if(void 0!==r.withCredentials&&(i.withCredentials=r.withCredentials),r.file){if(a=new FormData,a.append("file",r.file),r.data)for(const e in a)a.append(e,a[e])}else a=r.data?"string"==typeof r.data?r.data:JSON.stringify(r.data):null;s&&s((()=>{i.abort()})),i.send(a)};const F=/\{ *([\w_-]+) *\}/g;function I(e,t){return e.replace(F,((e,r)=>{let n=t[r];if(void 0===n)throw new Error("No value provided for letiable "+e);return"function"==typeof n&&(n=n(t)),n}))}class N extends R{constructor(e){super(e),this.name="ResourceNotFoundError",this.exception="nextgisweb.resource.exception.ResourceNotFound",Object.setPrototypeOf(this,N.prototype)}}class S extends R{constructor(e){super(e),this.name="InsufficientPermissionsError",this.exception="nextgisweb.core.exception.InsufficientPermissions",Object.setPrototypeOf(this,S.prototype)}}const U=[];function A(e){U.push(e)}function M(e){return"[object Object]"===Object.prototype.toString.call(e)}function q(e,t=""){t=t?t+"__":"";const r={};return Object.entries(e).forEach((([e,n])=>{if(M(n)){const t=q(n,e);Object.assign(r,t)}else E(n)&&(r[t+e]=n)})),r}class H{constructor(e){this.connector=e,this.cache=new j}getOne(e,t){return(new j).add("resource",(()=>"string"==typeof e?this._fetchResourceBy({keyname:e},t):"number"==typeof e?this._fetchResourceById(e,t):M(e)?this._fetchResourceBy(e,t):O.resolve(void 0)),{resource:e})}getOneOrFail(e){return this.getOne(e).then((e=>{if(e)return e;throw new N}))}getId(e){return"number"==typeof e?O.resolve(e):"string"==typeof e||M(e)?this.getOne(e).then((e=>{if(e)return e.resource.id})):O.resolve(void 0)}getIdOrFail(e){return this.getId(e).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,q(e)),this.connector.get("resource.search",t,{serialization:"full",...r}).then((e=>(e&&e.forEach((e=>{this.cache.add("resource.item",O.resolve(e),{id:e.resource.id})})),e)))}return r}))}getParent(e){return this.connector.getResource(e).then((e=>e?this.connector.getResource(e.resource.parent.id):O.resolve(void 0)))}getChildrenOf(e){return this.getId(e).then((e=>this.connector.get("resource.collection",{cache:!0},{parent:e}).then((e=>{for(const t of e)this.cache.add("resource.item",O.resolve(t),{id:t.resource.id});return e}))))}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.cache.delete("resource.item",{id:e})}))}))}_fetchResourceById(e,t){return this.cache.add("resource.item",(()=>this.connector.get("resource.item",t,{id:e})),{id:e}).catch((e=>{if(!(e instanceof N))throw e}))}_fetchResourceBy(e,t){return this.getMany(e,t).then((e=>e[0]))}_resourceCacheFilter(e){return O.all(this.cache.matchAll("resource.item")).then((t=>(t.filter((t=>{if(t)return e.keyname&&t.resource.keyname?e.keyname===t.resource.keyname:E(e.id)&&E(t.resource.id)?e.id===t.resource.id:P(e,t.resource)})),[])))}}let B=0;class ${constructor(e){this.options=e,this.id=B++,this.emitter=new t.exports.EventEmitter,this.routeStr="/api/component/pyramid/route";const r=function(e){return U.find((t=>{if(t.options.baseUrl===e.baseUrl){if(!e.auth)return!0;if(t.options.auth)return P(t.options.auth,e.auth)}}))}(e);if(r)return r;this.options.route&&(this.routeStr=this.options.route),this.resources=new H(this),A(this)}static create(e){return new this(e)}setNgw(e){this.logout(),this.options.baseUrl=e,A(this)}connect(){const e=new j,t=this.options.auth;return e.add("route",(()=>new O(((e,r)=>{const n=()=>this.makeQuery(this.routeStr,{},{}).then((t=>{e(t)})).catch((e=>{r(e)}));if(t){const{login:e,password:s}=t;if(e&&s)return this.getUserInfo({login:e,password:s}).then((()=>{n()})).catch((e=>r(e)))}return n()}))),{id:this.id,auth:t,baseUrl:this.options.baseUrl})}login(e){return this.logout(),A(this),this.getUserInfo(e)}logout(){!function(e){const t=U.indexOf(e);-1!==t&&U.splice(t,1)}(this),this.options.auth=void 0,this.user=void 0,this.emitter.emit("logout"),this.resources.cache.clean()}getUserInfo(e){if(this.user&&this.user.id)return O.resolve(this.user);e&&(this.options.auth=e);const t={headers:this.getAuthorizationHeaders(e)};return this.makeQuery("/api/component/auth/current_user",{},t).then((e=>(this.user=e,this.emitter.emit("login",e),e))).catch((e=>{throw this.emitter.emit("login:error",e),e}))}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,n=unescape(encodeURIComponent(`${t}:${r}`));return window.btoa(n)}}apiRequest(e,t={},r={}){const{method:n,headers:s,withCredentials:i,responseType:o}=r,c=L(t),a=()=>function(e){const t=e.params;return new O(((r,n)=>{e.connector.connect().then((s=>{let i=s&&s[e.name];if(i){i=[...i];let s=i.shift();if(i.length){const e={};for(let r=0;r<i.length;r++){const n=i[r];if(e[r]="{"+n+"}",void 0===t[n])throw new Error("`"+n+"` url api argument is not specified")}s&&(s=I(s,e))}if(t){const e=[],r=t.paramList;Array.isArray(r)&&(delete t.paramList,r.forEach((t=>{e.push(`${t[0]}=${t[1]}`)})));for(const r in t)-1===i.indexOf(r)&&e.push(`${r}=${t[r]}`);e.length&&(s=s+"?"+e.join("&"))}s?r(e.connector.makeQuery(s,t,e.requestOptions)):n(new Error("request url is not set"))}else r(void 0)})).catch((e=>{n(e)}))}))}({name:e,params:c,requestOptions:r,connector:this});if(r.cache&&"GET"===n){return(new j).add(e,a,{params:c,...L({headers:s,withCredentials:i,responseType:o,baseUrl:this.options.baseUrl,auth:this.options.auth})})}return a()}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)}makeQuery(e,t,r={}){if(e=(this.options.baseUrl?this.options.baseUrl:"")+e)return t&&(e=I(e,t)),e=function(e){return e.replace(/([^:]\/)\/+/g,"$1")}(e),this._loadData(e,r);throw new Error("Empty `url` not allowed")}getResource(e){return this.resources.getOne(e)}getResourceOrFail(e){return this.resources.getOneOrFail(e)}getResourceBy(e){return this.resources.getOne(e)}getResourceByKeyname(e){return this.resources.getOne(e)}getResourceById(e){return this.resources.getOne(e)}getResourceId(e){return this.resources.getId(e)}getResourceIdOrFail(e){return this.resources.getIdOrFail(e)}getResourcesBy(e){return this.resources.getMany(e)}getResourceParent(e){return this.resources.getParent(e)}getResourceChildren(e){return this.resources.getChildrenOf(e)}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 O(((r,n,s)=>{this.user&&((t=t||{}).headers={...this.getAuthorizationHeaders(),...t.headers}),k(e,r,t,n,s)})).catch((e=>{if(e instanceof O.CancelError);else{const t=this._handleHttpError(e);if(t)throw t}}))}_handleHttpError(e){if(e&&e instanceof R){if("nextgisweb.resource.exception.ResourceNotFound"===e.exception)throw new N(e);if("nextgisweb.core.exception.InsufficientPermissions"===e.exception)throw new S(e)}return e}}$.errors={NgwError:R,ResourceNotFoundError:N};var D=$;export{D as default};
1
+ var e,t={exports:{}},r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};e=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}t.exports=i,t.exports.once=function(e,t){return new Promise((function(r,n){function s(r){e.removeListener(t,i),n(r)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",s),r([].slice.call(arguments))}m(e,t,i,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&m(e,"error",t,r)}(e,s,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function h(e,t,r,n){var s,i,o,h;if(c(r),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),i=e._events),o=i[t]),void 0===o)o=i[t]=r,++e._eventsCount;else if("function"==typeof o?o=i[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(s=a(e))>0&&o.length>s&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,h=u,console&&console.warn&&console.warn(h)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},s=u.bind(n);return s.listener=r,n.wrapFn=s,s}function f(e,t,r){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?r?[s.listener||s]:[s]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(s):d(s,s.length)}function p(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function d(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function m(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(i){n.once&&e.removeEventListener(t,s),r(i)}))}}Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return a(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var s="error"===e,i=this._events;if(void 0!==i)s=s&&void 0===i.error;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)n(a,this,t);else{var h=a.length,u=d(a,h);for(r=0;r<h;++r)n(u[r],this,t)}return!0},i.prototype.on=i.prototype.addListener=function(e,t){return h(this,e,t,!1)},i.prototype.prependListener=function(e,t){return h(this,e,t,!0)},i.prototype.once=function(e,t){return c(t),this.on(e,l(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,l(this,e,t)),this},i.prototype.off=i.prototype.removeListener=function(e,t){var r,n,s,i,o;if(c(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,i=r.length-1;i>=0;i--)if(r[i]===t||r[i].listener===t){o=r[i].listener,s=i;break}if(s<0)return this;0===s?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,s),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},i.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var s,i=Object.keys(r);for(n=0;n<i.length;++n)"removeListener"!==(s=i[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},i.prototype.listeners=function(e){return f(this,e,!0)},i.prototype.rawListeners=function(e){return f(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},i.prototype.listenerCount=p,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]};class g extends Error{constructor(){super(),this.name="CancelError",Object.setPrototypeOf(this,g.prototype)}}class y{constructor(e={}){this.options=e,this._promises=new Map}get isLoaded(){return this._promises.size>0}remove(e){this._promises.has(e)&&(this._promises.delete(e),this._onStop())}get(e){return this._promises.get(e)}add(e,t){const r=t||e,n=this._promises.get(r);return this.options.onStart&&!this.isLoaded&&this.options.onStart(),n||(this._promises.set(r,e),e.finally((()=>{this.remove(r)})),e)}abort(){this.isLoaded&&(this._promises.forEach((e=>{e.cancel&&e.cancel()})),this._promises.clear(),this._onStop())}waitFunc(e,t=""){const r=this.get(t=t||e.name);return r||this.add(e(),t)}WaitForMe(e=""){const t=this.get.bind(this),r=this.add.bind(this);return function(n,s,i){const o=i.value;return e=e||s,i.value=function(...n){const s=t(e);if(s)return s;return r(o.apply(this,n),e)},i}}GetOrCreateDecorator(e=""){return this.WaitForMe(e)}_onStop(){this.options.onStop&&!this.isLoaded&&this.options.onStop()}}class v extends Error{constructor(){super(),this.name="TimeoutError",Object.setPrototypeOf(this,v.prototype)}}const _=(e,t,r,n)=>{try{e(r(n))}catch(e){t(e)}};let w=0;class b{constructor(e,t){this.id=w++,this._isCanceled=!1,this._isPending=!0,this._cancelHandlers=[],this._children=[],this._cancelPromise=new Promise(((e,t)=>{this._setCanceledCallback=t=>e(t||new g)}));const r=[this._cancelPromise,new Promise(((t,r)=>e((e=>{e instanceof b?this.attach(e):this._isPending=!1,t(e)}),(e=>{this._isPending=!1,r(e)}),(e=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(e)}))))];t&&r.push(new Promise(((e,r)=>{setTimeout((()=>{if(this._isPending)try{this.cancel()}finally{r(new v)}}),t)}))),this._promise=Promise.race(r)}static createControl(e){return new y(e)}static resolve(e){return new b((t=>t(e)))}static reject(e){return new b(((t,r)=>r(e)))}static all(e){return new b(((t,r)=>{Promise.all(e).then(t).catch(r)})).catch((t=>{if(t instanceof this.CancelError)for(const t of e)"cancel"in t&&t.cancel();throw t}))}attach(e){this._isCanceled?e.cancel():this._children.push(e)}then(e,t){const r=new b(((r,n)=>{if(this._promise){const s=e=>{t?_(r,n,t,e):n(e)};this._promise.then((t=>{this._isCanceled?s(t):e?_(r,n,e,t):r(t)}),s)}}));return r._parentPromise=this,this._children.push(r),r}catch(e){return this._isCanceled&&e&&e(new g),this.then(void 0,e)}finally(e){return this._promise?this._promise.finally(e):Promise.reject(this._isCanceled?new g:e)}cancel(){if(this._isCanceled||!this._isPending)return this;this._isCanceled=!0;const e=this._getTopParent();if(e&&e.cancel(),this._children&&this._children.forEach((e=>e.cancel())),this._isPending){if(this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){}this._setCanceledCallback&&this._setCanceledCallback()}return this._destroy(),this}_getTopParent(){let e=this._parentPromise,t=!!e;for(;t;)e&&e._parentPromise?(e=e._parentPromise,t=!!e):t=!1;return e}_destroy(){this._setCanceledCallback=void 0,this._cancelPromise=void 0,this._promise=void 0}}b.CancelError=g,b.TimeoutError=v,b.PromiseControl=y,Object.setPrototypeOf(b.prototype,Promise.prototype);var O=b;function E(e){return null!=e}function C(e,t,r,n){if(e instanceof Array)return t instanceof Array&&t.sort().join("")===e.sort().join("");if(e instanceof Date)return t instanceof Date&&""+e==""+t;if(e instanceof Function){if(!(t instanceof Function))return!1}else if(e instanceof Object)return t instanceof Object&&(e===r?t===n:P(e,t));return e===t}function P(e,t){const r=Object.keys(e).sort(),n=Object.keys(t).sort();if(r.length!==n.length)return!1;if(r.join("")!==n.join(""))return!1;for(let s=0;s<r.length;s++){if(!C(e[r[s]],t[n[s]],e,t))return!1}return!0}function L(e){const t={};return Object.keys(e).forEach((r=>{e[r]instanceof Array||e[r]!==Object(e[r])?void 0!==e[r]&&(t[r]=e[r]):t[r]=L(e[r])})),t}class x{constructor(){return this.cache=[],x.instance?x.instance:(x.instance=this,this)}clean(){this.cache.length=0}all(){return this.cache}add(e,t,r){const n=this._find(e,r);if(n)return n.value;{let n;n=t instanceof Function?t():t;const s=r&&JSON.parse(JSON.stringify(L(r)));return this.cache.push({key:e,value:n,options:s}),n instanceof Promise?(n.catch((t=>{throw this.delete(e,r),t})),n):n}}match(e,t){const r=this._find(e,t);if(r)return r.value}matchAll(e,t){return e?this.cache.filter((r=>this._filter(r,e,t))).map((e=>e.value)):this.cache.map((e=>e.value))}delete(e,t){const r=this.cache.filter((r=>this._filter(r,e,t)));for(const e of r){const t=this.cache.indexOf(e);this.cache.splice(t,1)}}_find(e,t){return this.cache.find((r=>this._filter(r,e,t)))}_filter(e,t,r){return e.key===t&&(!r||P(e.options||{},L(r)))}}var j=x;class R extends Error{constructor(e){super(),this.name="NgwError",Object.assign(this,e),Object.setPrototypeOf(this,R.prototype)}}class T extends Error{constructor(e){super(),this.name="NetworkError",Object.setPrototypeOf(this,T.prototype),this.message=`Unable to request ${e}.\n Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`}}let k;k=(e,t,r={},n,s)=>{r.method=r.method||"GET";const i=new XMLHttpRequest;i.open(r.method||"GET",e,!0),"blob"===r.responseType&&(i.responseType=r.responseType);const o=()=>{try{return JSON.parse(i.responseText)}catch(e){return i.responseText}};i.onload=()=>{-1!==[401,403,404,500].indexOf(i.status)&&n(new R(o())),((e=!1)=>{const s=e?n:t;"blob"===r.responseType?s(i.response):i.responseText?s(o()):n({message:""})})()},i.onerror=t=>{n(0===i.status?new T(e):t)},i.upload.onprogress=function(e){if(e.lengthComputable){const t=e.loaded/e.total*100;r.onProgress&&r.onProgress(t,e)}};const c=r.headers;if(c)for(const e in c){const t=c[e];"string"==typeof t&&i.setRequestHeader(e,t)}let a;if(void 0!==r.withCredentials&&(i.withCredentials=r.withCredentials),r.file){if(a=new FormData,a.append("file",r.file),r.data)for(const e in a)a.append(e,a[e])}else a=r.data?"string"==typeof r.data?r.data:JSON.stringify(r.data):null;s&&s((()=>{i.abort()})),i.send(a)};const F=/\{ *([\w_-]+) *\}/g;function I(e,t){return e.replace(F,((e,r)=>{let n=t[r];if(void 0===n)throw new Error("No value provided for letiable "+e);return"function"==typeof n&&(n=n(t)),n}))}class N extends R{constructor(e){super(e),this.name="ResourceNotFoundError",this.exception="nextgisweb.resource.exception.ResourceNotFound",Object.setPrototypeOf(this,N.prototype)}}class S extends R{constructor(e){super(e),this.name="InsufficientPermissionsError",this.exception="nextgisweb.core.exception.InsufficientPermissions",Object.setPrototypeOf(this,S.prototype)}}const U=[];function A(e){U.push(e)}function M(e){return"[object Object]"===Object.prototype.toString.call(e)}function q(e,t=""){t=t?t+"__":"";const r={};return Object.entries(e).forEach((([e,n])=>{if(M(n)){const t=q(n,e);Object.assign(r,t)}else E(n)&&(r[t+e]=n)})),r}class H{constructor(e){this.connector=e,this.cache=new j}getOne(e,t){return(new j).add("resource",(()=>"string"==typeof e?this._fetchResourceBy({keyname:e},t):"number"==typeof e?this._fetchResourceById(e,t):M(e)?this._fetchResourceBy(e,t):O.resolve(void 0)),{resource:e})}getOneOrFail(e,t){return this.getOne(e,t).then((e=>{if(e)return e;throw new N}))}getId(e,t){return"number"==typeof e?O.resolve(e):"string"==typeof e||M(e)?this.getOne(e,t).then((e=>{if(e)return e.resource.id})):O.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,q(e)),this.connector.get("resource.search",t,{serialization:"full",...r}).then((e=>(e&&e.forEach((e=>{this.cache.add("resource.item",O.resolve(e),{id:e.resource.id})})),e)))}return r}))}getParent(e,t){return this.getOne(e,t).then((e=>e?this.getOne(e.resource.parent.id,t):O.resolve(void 0)))}getChildrenOf(e,t){return this.getId(e).then((e=>this.connector.get("resource.collection",{cache:!0,...t},{parent:e}).then((e=>{for(const t of e)this.cache.add("resource.item",O.resolve(t),{id:t.resource.id});return e}))))}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.cache.delete("resource.item",{id:e})}))}))}_fetchResourceById(e,t){return this.cache.add("resource.item",(()=>this.connector.get("resource.item",t,{id:e})),{id:e}).catch((e=>{if(!(e instanceof N))throw e}))}_fetchResourceBy(e,t){return this.getMany(e,t).then((e=>e[0]))}_resourceCacheFilter(e){return O.all(this.cache.matchAll("resource.item")).then((t=>(t.filter((t=>{if(t)return e.keyname&&t.resource.keyname?e.keyname===t.resource.keyname:E(e.id)&&E(t.resource.id)?e.id===t.resource.id:P(e,t.resource)})),[])))}}let B=0;class ${constructor(e){this.options=e,this.id=B++,this.emitter=new t.exports.EventEmitter,this.routeStr="/api/component/pyramid/route";const r=function(e){return U.find((t=>{if(t.options.baseUrl===e.baseUrl){if(!e.auth)return!0;if(t.options.auth)return P(t.options.auth,e.auth)}}))}(e);if(r)return r;this.options.route&&(this.routeStr=this.options.route),this.resources=new H(this),A(this)}static create(e){return new this(e)}setNgw(e){this.logout(),this.options.baseUrl=e,A(this)}connect(){const e=new j,t=this.options.auth;return e.add("route",(()=>new O(((e,r)=>{const n=()=>this.makeQuery(this.routeStr,{},{}).then((t=>{e(t)})).catch((e=>{r(e)}));if(t){const{login:e,password:s}=t;if(e&&s)return this.getUserInfo({login:e,password:s}).then((()=>{n()})).catch((e=>r(e)))}return n()}))),{id:this.id,auth:t,baseUrl:this.options.baseUrl})}login(e){return this.logout(),A(this),this.getUserInfo(e)}logout(){!function(e){const t=U.indexOf(e);-1!==t&&U.splice(t,1)}(this),this.options.auth=void 0,this.user=void 0,this.emitter.emit("logout"),this.resources.cache.clean()}getUserInfo(e){if(this.user&&this.user.id)return O.resolve(this.user);e&&(this.options.auth=e);const t={headers:this.getAuthorizationHeaders(e)};return this.makeQuery("/api/component/auth/current_user",{},t).then((e=>(this.user=e,this.emitter.emit("login",e),e))).catch((e=>{throw this.emitter.emit("login:error",e),e}))}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,n=unescape(encodeURIComponent(`${t}:${r}`));return window.btoa(n)}}apiRequest(e,t={},r={}){const{method:n,headers:s,withCredentials:i,responseType:o}=r,c=L(t),a=()=>function(e){const t=e.params;return new O(((r,n)=>{e.connector.connect().then((s=>{let i=s&&s[e.name];if(i){i=[...i];let s=i.shift();if(i.length){const e={};for(let r=0;r<i.length;r++){const n=i[r];if(e[r]="{"+n+"}",void 0===t[n])throw new Error("`"+n+"` url api argument is not specified")}s&&(s=I(s,e))}if(t){const e=[],r=t.paramList;Array.isArray(r)&&(delete t.paramList,r.forEach((t=>{e.push(`${t[0]}=${t[1]}`)})));for(const r in t)-1===i.indexOf(r)&&e.push(`${r}=${t[r]}`);e.length&&(s=s+"?"+e.join("&"))}s?r(e.connector.makeQuery(s,t,e.requestOptions)):n(new Error("request url is not set"))}else r(void 0)})).catch((e=>{n(e)}))}))}({name:e,params:c,requestOptions:r,connector:this});if(r.cache&&"GET"===n){return(new j).add(e,a,{params:c,...L({headers:s,withCredentials:i,responseType:o,baseUrl:this.options.baseUrl,auth:this.options.auth})})}return a()}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)}makeQuery(e,t,r={}){if(e=(this.options.baseUrl?this.options.baseUrl:"")+e)return t&&(e=I(e,t)),e=function(e){return e.replace(/([^:]\/)\/+/g,"$1")}(e),this._loadData(e,r);throw new Error("Empty `url` not allowed")}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 O(((r,n,s)=>{this.user&&((t=t||{}).headers={...this.getAuthorizationHeaders(),...t.headers}),k(e,r,t,n,s)})).catch((e=>{if(e instanceof O.CancelError);else{const t=this._handleHttpError(e);if(t)throw t}}))}_handleHttpError(e){if(e&&e instanceof R){if("nextgisweb.resource.exception.ResourceNotFound"===e.exception)throw new N(e);if("nextgisweb.core.exception.InsufficientPermissions"===e.exception)throw new S(e)}return e}}$.errors={NgwError:R,ResourceNotFoundError:N};var D=$;export{D as default};
2
2
  //# sourceMappingURL=ngw-connector.esm-browser.prod.js.map