zavadil-ts-common 2.1.11 → 2.1.13

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,5 +1,5 @@
1
1
  import { EntityClient } from "./EntityClient";
2
- import { EntityBase } from "../type/Entity";
2
+ import { EntityBase } from "../type";
3
3
  export declare class EntityClientWithStub<T extends EntityBase, TStub extends EntityBase> extends EntityClient<T> {
4
4
  loadSingle(id: number): Promise<T>;
5
5
  loadSingleStub(id: number): Promise<TStub>;
package/dist/index.d.ts CHANGED
@@ -300,14 +300,6 @@ declare class OAuthTokenManager implements OAuthRefreshTokenProvider {
300
300
  getAccessToken(scope: string): Promise<string>;
301
301
  }
302
302
 
303
- declare class OAuthSubject {
304
- private value;
305
- constructor(value: string);
306
- getSubjectType(): string | null;
307
- getSubjectContent(): string | null;
308
- toString(): string;
309
- }
310
-
311
303
  type ServerOAuthInfoPayload = {
312
304
  debugMode?: boolean;
313
305
  targetAudience: string;
@@ -359,6 +351,7 @@ declare class StringUtil {
359
351
  static substr(str: string | null | undefined, start: number, length?: number): string;
360
352
  static replace(str: string | null | undefined, find?: null | string, replace?: string): string;
361
353
  static containsLineBreaks(str: string | null | undefined): str is string;
354
+ static safeContains(haystack: string | null | undefined, needle: string | null | undefined, caseSensitive?: boolean): haystack is string;
362
355
  static trimLeadingSlashes(str: string | null): string;
363
356
  static trimTrailingSlashes(str: string | null): string;
364
357
  static trimSlashes(str: string | null): string;
@@ -378,8 +371,10 @@ declare class StringUtil {
378
371
 
379
372
  declare class ArrayUtil {
380
373
  static isEmpty(arr?: Array<any> | null): boolean;
381
- static notEmpty(arr?: Array<any> | null): boolean;
374
+ static notEmpty(arr?: Array<any> | null): arr is Array<any>;
382
375
  static remove(arr?: Array<any> | null, element?: any): Array<any>;
376
+ static extract(arr?: Array<any> | null, start?: number, length?: number): Array<any>;
377
+ static extractStart(arr: Array<any> | null | undefined, length: number): Array<any>;
383
378
  }
384
379
 
385
380
  declare class AsyncUtil {
@@ -512,4 +507,4 @@ declare class BasicLocalization extends Localization {
512
507
  constructor(language?: string);
513
508
  }
514
509
 
515
- export { type AccessTokenPayload, ArrayUtil, AsyncUtil, BasicLocalization, ByteUtil, CacheAsync, type CacheStats, CancellablePromise, CzechBasicDictionary, DateUtil, type Dictionary, type DictionaryMemoryData, type DictionaryMemoryValue, DictionaryWithFallback, EnglishBasicDictionary, type EntityBase, EntityCachedClient, EntityClient, EntityClientWithStub, type EntityWithName, EventManager, type Func, type FuncHandlers, type FuncHandlersCache, HashCacheAsync, type HashCacheStats, HashUtil, type IdTokenPayload, type JavaHeapStats, JsonUtil, type JwKeyPayload, type JwksPayload, Lazy, LazyAsync, Localization, LookupClient, type LookupTableEntity, MemoryDictionary, NumberUtil, type OAuthRefreshTokenProvider, OAuthRestClient, OAuthSubject, OAuthTokenManager, ObjectUtil, PERMISSION_LEVELS, type Page, type PagingRequest, PagingUtil, type PermissionLevel, type QueueStats, type RefreshTokenPayload, type RenewRefreshTokenPayload, type RequestAccessTokenPayload, type RequestOptions, type RequestRefreshTokenFromLoginPayload, RestClient, RestClientWithOAuth, type ServerOAuthInfoPayload, type SortingField, type SortingRequest, StringUtil, type TokenRequestPayloadBase, type TokenResponsePayloadBase, type TranslateParams, UrlUtil, type UserAlert, UserAlertType, UserAlerts, Vector2 };
510
+ export { type AccessTokenPayload, ArrayUtil, AsyncUtil, BasicLocalization, ByteUtil, CacheAsync, type CacheStats, CancellablePromise, CzechBasicDictionary, DateUtil, type Dictionary, type DictionaryMemoryData, type DictionaryMemoryValue, DictionaryWithFallback, EnglishBasicDictionary, type EntityBase, EntityCachedClient, EntityClient, EntityClientWithStub, type EntityWithName, EventManager, type Func, type FuncHandlers, type FuncHandlersCache, HashCacheAsync, type HashCacheStats, HashUtil, type IdTokenPayload, type JavaHeapStats, JsonUtil, type JwKeyPayload, type JwksPayload, Lazy, LazyAsync, Localization, LookupClient, type LookupTableEntity, MemoryDictionary, NumberUtil, type OAuthRefreshTokenProvider, OAuthRestClient, OAuthTokenManager, ObjectUtil, PERMISSION_LEVELS, type Page, type PagingRequest, PagingUtil, type PermissionLevel, type QueueStats, type RefreshTokenPayload, type RenewRefreshTokenPayload, type RequestAccessTokenPayload, type RequestOptions, type RequestRefreshTokenFromLoginPayload, RestClient, RestClientWithOAuth, type ServerOAuthInfoPayload, type SortingField, type SortingRequest, StringUtil, type TokenRequestPayloadBase, type TokenResponsePayloadBase, type TranslateParams, UrlUtil, type UserAlert, UserAlertType, UserAlerts, Vector2 };
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- class e{constructor(e){this.supplier=e}get(){return void 0!==this.cache?Promise.resolve(this.cache):(void 0===this.promise&&(this.promise=this.supplier().then((e=>(this.cache=e,this.promise=void 0,Promise.resolve(e)))).catch((e=>(this.promise=void 0,Promise.reject(e))))),this.promise)}reset(){this.cache=void 0}hasCache(){return void 0!==this.cache}getCache(){return this.cache}}class t extends e{constructor(e,t){super(e),this.maxAgeMs=t}get(){return this.expires&&this.expires>new Date&&this.reset(),super.get()}set(e,t){this.cache=e,this.expires=t,this.maxAgeMs&&void 0===this.expires&&(this.expires=new Date((new Date).getTime()+this.maxAgeMs))}}class s{constructor(e,t){this.cache=new Map,this.maxSize=100,this.supplier=e,t&&(this.maxSize=t)}obtainCache(e){let s=this.cache.get(e);return s||(s=new t((()=>this.supplier(e))),this.cache.set(e,s)),s}get(e){return this.obtainCache(e).get()}set(e,t,s){this.obtainCache(e).set(t,s)}reset(e){e?this.cache.delete(e):this.cache.clear()}getSize(){return this.cache.size}getMaxSize(){return this.maxSize}getStats(){return{cachedItems:this.getSize(),capacity:this.getMaxSize()}}hasCache(e){return this.cache.has(e)}}class r{constructor(e){this.supplier=e}get(){return void 0===this.cache&&(this.cache=this.supplier()),this.cache}reset(){this.cache=void 0}hasCache(){return void 0!==this.cache}}class n{static isEmpty(e){return null==e}static notEmpty(e){return!n.isEmpty(e)}static clone(e){if(null===e)throw new Error("Null cannot be cloned!");if("object"!=typeof e)throw new Error("Not an object, cannot be cloned!");return{...e}}static getNestedValue(e,t){if(!e||""===e)return"";const s=t.split(".");let r=e;for(const e of s){if(!r||"object"!=typeof r||!(e in r))return"";r=r[e]}return r}}class i{static crc32hex(e){const t=(new TextEncoder).encode(e),s=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?3988292384^t>>>1:t>>>1;s[e]=t>>>0}let r=~0;for(let e=0;e<t.length;e++)r=r>>>8^s[255&(r^t[e])];return r=~r>>>0,r.toString(16)}}class o{static isString(e){return"string"==typeof e}static toString(e){return o.isString(e)?e:o.isString(e.message)?e.message:e?.toString?.()??""}static isEmpty(e){return!!n.isEmpty(e)||0===e.length}static notEmpty(e){return!o.isEmpty(e)}static isBlank(e){return o.isEmpty(o.safeTrim(e))}static notBlank(e){return!o.isBlank(e)}static substr(e,t,s){return this.isEmpty(e)?"":e.substring(t,s)}static replace(e,t,s){return this.isEmpty(e)||this.isEmpty(t)?"":e.replace(t,String(s))}static containsLineBreaks(e){return!o.isBlank(e)&&e.includes("\n")}static trimLeadingSlashes(e){return this.isEmpty(e)?"":o.toString(e).replace(/^\//g,"")}static trimTrailingSlashes(e){return this.isEmpty(e)?"":o.toString(e).replace(/\/$/g,"")}static trimSlashes(e){return this.isEmpty(e)?"":o.toString(e).replace(/^\/|\/$/g,"")}static safeTruncate(e,t,s=""){return o.isEmpty(e)||!e?"":(e=o.toString(e)).length<=t?String(e):e.substring(0,t-s.length)+s}static ellipsis(e,t,s="..."){return o.safeTruncate(e,t,s)}static safeTrim(e){return o.isEmpty(e)?"":o.toString(e).trim()}static safeLowercase(e){return o.isEmpty(e)||!e?"":o.toString(e).toLowerCase()}static safeUppercase(e){return o.isEmpty(e)||!e?"":o.toString(e).toUpperCase()}static capitalizeFirstLetter(e){return o.isBlank(e)?"":o.safeUppercase(e.charAt(0))+o.safeLowercase(o.substr(e,1))}static toBigInt(e){return this.isEmpty(e)?null:BigInt(e)}static getNonEmpty(...e){return e.find((e=>o.notEmpty(e)))||""}static getNonBlank(...e){return e.find((e=>o.notBlank(e)))||""}static emptyToNull(e){return o.isEmpty(e)?null:String(e)}static blankToNull(e){return o.isBlank(e)?null:String(e)}static randomString(){return i.crc32hex(Date()+Math.random())}}class a{static isEmpty(e){return n.isEmpty(e)||0===e.length}static notEmpty(e){return!a.isEmpty(e)}static remove(e,t){return a.isEmpty(e)?[]:e?.filter((e=>e!==t))}}class h{}h.sleep=e=>new Promise((t=>setTimeout(t,e)));class c{static formatByteSize(e){const t=Number(e);if(null===t||Number.isNaN(t))return"";if(0===t)return"0";const s=Math.floor(Math.log(t)/Math.log(1024));return 1*+(t/Math.pow(1024,s)).toFixed(2)+" "+["B","kB","MB","GB","TB"][s]}}const u={page:0,size:10};class l{static sortingFieldToString(e){if(!e)return"";const t=[];return t.push(e.name),t.push(e.desc?"desc":""),t.push(e.nullsLast?"nl":""),t.join("-")}static sortingFieldFromString(e){const t=e.split("-");return{name:t[0],desc:t.length>1&&"desc"===o.safeLowercase(t[1]),nullsLast:t.length>2&&"nl"===o.safeLowercase(t[2])}}static sortingRequestToString(e){return e.map((e=>l.sortingFieldToString(e))).join("+")}static sortingRequestFromString(e){if(!e)return[];return e.split("+").map((e=>l.sortingFieldFromString(e)))}static pagingRequestToQueryParams(e){if(!e)return;const t={page:e.page,size:e.size};return e.search&&(t.search=e.search),e.sorting&&(t.sorting=l.sortingRequestToString(e.sorting)),t}static pagingRequestToString(e){if(!e)return"";const t=[];return t.push(String(e.page)),t.push(String(e.size)),t.push(o.safeTrim(e.search)),t.push(e.sorting?l.sortingRequestToString(e.sorting):""),t.join(":")}static pagingRequestFromString(e){if(!e||o.isEmpty(e))return{...u};const t=e.split(":");return t.length<4?{...u}:{page:Number(t[0]),size:Number(t[1]),search:String(t[2]),sorting:o.isEmpty(t[3])?void 0:l.sortingRequestFromString(t[3])}}}class g{static isEmpty(e){return null==e||Number.isNaN(e)}static notEmpty(e){return!n.isEmpty(e)}static parseNumber(e){if(!e)return null;const t=Number(e);return Number.isNaN(t)?null:t}static round(e,t){t||(t=0);const s=Math.pow(10,t);return Math.round(e*s)/s}static portionToPercent(e,t){if(null==e)return"";return`${g.round(100*e,t)}%`}}class d{static formatNumber(e,t=2){return String(e).padStart(t,"0")}static parseDate(e){if(e)return"string"==typeof e?new Date(e):e}static formatDateForHumans(e,t=!1){if(!(e=d.parseDate(e)))return"";const s=e.getFullYear(),r=d.formatNumber(e.getMonth()+1),n=d.formatNumber(e.getDate());if(!t)return`${s}-${r}-${n}`;return`${s}/${r}/${n} ${d.formatNumber(e.getHours())}:${d.formatNumber(e.getMinutes())}:${d.formatNumber(e.getSeconds())}`}static formatDateTimeForHumans(e){return d.formatDateForHumans(e,!0)}static formatDateForInput(e,t=!1){if(!(e=d.parseDate(e)))return"";const s=e.getFullYear(),r=d.formatNumber(e.getMonth()+1),n=d.formatNumber(e.getDate());if(!t)return`${s}-${r}-${n}`;return`${s}-${r}-${n}T${d.formatNumber(e.getHours())}:${d.formatNumber(e.getMinutes())}:${d.formatNumber(e.getSeconds())}`}static formatDateTimeForInput(e){return d.formatDateForInput(e,!0)}static getDurationMs(e,t){if(e=d.parseDate(e),t=d.parseDate(t),n.isEmpty(e)||n.isEmpty(t))return null;try{return t.getTime()-e.getTime()}catch(e){return null}}static getSinceDurationMs(e){return d.getDurationMs(e,new Date)}static formatDuration(e){if(!e)return"";let t=Math.floor(e/1e3);e-=1e3*t;let s=Math.floor(t/60);t-=60*s;let r=Math.floor(s/60);s-=60*r;let n=Math.floor(r/24);r-=24*n;const i=[];return n>0&&i.push(`${n}d`),r>0&&i.push(`${r}h`),s>0&&i.push(`${s}m`),t>0&&0===n&&0===r&&i.push(`${t}s`),e>0&&0===n&&0===r&&0===s&&i.push(`${g.round(e,2)}ms`),i.join(" ")}}class m{static dateParser(e,t){return"string"==typeof t&&m.reISO.exec(t)?new Date(t):t}static parseWithDates(e){if(!o.isBlank(e))return JSON.parse(o.getNonEmpty(e),m.dateParser)}static parse(e){return m.parseWithDates(e)}}m.reISO=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;class p{static deleteParamFromUrl(e,t){const s=new URL(e);return s.searchParams.delete(t),o.trimTrailingSlashes(s.toString())}static extractParamFromUrl(e,t){return new URLSearchParams(new URL(e).search).get(t)}static paramExistsInUrl(e,t){return o.notBlank(p.extractParamFromUrl(e,t))}static extractHostFromUrl(e){return o.isBlank(e)?null:new URL(e).host}static extractDomainFromUrl(e){const t=p.extractHostFromUrl(e);return o.isBlank(t)?null:t.split(".").slice(-2).join(".")}}class f{constructor(e){o.isBlank(e)?this.baseUrl=f.baseHostUrl():(e.endsWith("/")||(e+="/"),this.baseUrl=e.startsWith("http")?new URL(e):new URL(e,f.baseHostUrl()))}static baseHostUrl(){return new URL(`${window.location.protocol}//${window.location.host}/`)}static pagingRequestToQueryParams(e){return l.pagingRequestToQueryParams(e)}static paramsToQueryString(e){if(!e)return"";const t=new URLSearchParams(e),s=new URLSearchParams;t.forEach(((e,t)=>{""!==e&&void 0!==e&&"undefined"!==e&&s.set(t,e)}));const r=s.toString();return o.isEmpty(r)?"":`?${r}`}getHeaders(e){const t=new Headers;return t.set("Content-Type","application/json"),Promise.resolve(t)}getBaseUrl(){return this.baseUrl}getUrl(e,t){const s=new URL(o.trimLeadingSlashes(e),this.getBaseUrl());return t&&Object.keys(t).forEach((e=>{const r=t[e];""!==r&&void 0!==r&&"undefined"!==r&&s.searchParams.set(e,r)})),s}getRequestOptions(e,t="GET",s=null){return this.getHeaders(e).then((e=>({method:t,headers:e,body:null===s?null:s instanceof FormData?s:JSON.stringify(s)})))}processRequest(e,t,s){return fetch(this.getUrl(e,t),s).then((e=>{if(!e.ok){const t={cause:e.status};return"application/json"===e.headers.get("Content-Type")?e.json().then((s=>{if(s.message)throw new Error(s.message,t);if(s.error)throw new Error(s.error,t);throw new Error(e.statusText,t)}),(()=>{throw new Error(e.statusText,t)})):e.text().then((s=>{throw o.isEmpty(s)?new Error(e.statusText,t):new Error(s,t)}),(()=>{throw new Error(e.statusText,t)}))}return e}))}processRequestJson(e,t,s){return this.processRequest(e,t,s).then((e=>e.text().then(m.parseWithDates)))}getJson(e,t){return this.getRequestOptions(e).then((s=>this.processRequestJson(e,t,s)))}postJson(e,t=null,s){return this.getRequestOptions(e,"POST",t).then((t=>this.processRequestJson(e,s,t)))}postForm(e,t,s){return this.getRequestOptions(e,"POST",t).then((t=>(t.headers.delete("Content-Type"),this.processRequest(e,s,t))))}postFormJson(e,t,s){return this.getRequestOptions(e,"POST",t).then((t=>(t.headers.delete("Content-Type"),this.processRequestJson(e,s,t))))}putJson(e,t=null,s){return this.getRequestOptions(e,"PUT",t).then((t=>this.processRequestJson(e,s,t)))}get(e,t){return this.getRequestOptions(e).then((s=>this.processRequest(e,t,s)))}del(e,t){return this.getRequestOptions(e,"DELETE").then((s=>this.processRequest(e,t,s)))}post(e,t=null,s){return this.getRequestOptions(e,"POST",t).then((t=>this.processRequest(e,s,t)))}put(e,t=null,s){return this.getRequestOptions(e,"PUT",t).then((t=>this.processRequest(e,s,t)))}}class k{constructor(e,t){this.client=e,this.name=t}loadSingle(e){return this.client.getJson(`${this.name}/${e}`)}loadPage(e){return this.client.getJson(this.name,f.pagingRequestToQueryParams(e))}save(e){return e.id?this.client.putJson(`${this.name}/${e.id}`,e):this.client.postJson(this.name,e)}delete(e){return this.client.del(`${this.name}/${e}`)}}class T extends k{constructor(e,t,r){super(e,t),this.cache=new s((e=>super.loadSingle(e)),r)}loadSingle(e){return this.cache.get(e)}save(e){return super.save(e).then((e=>(e.id&&this.cache.set(e.id,e),e)))}delete(e){return super.delete(e).then((()=>this.cache.reset(e)))}reset(e){this.cache.reset(e)}getStats(){return this.cache.getStats()}}class v extends k{loadSingle(e){throw new Error("Use loadSingleStub() instead!")}loadSingleStub(e){return this.client.getJson(`${this.name}/${e}`)}save(e){throw new Error("Use saveStub() instead!")}saveStub(e){return e.id?this.client.putJson(`${this.name}/${e.id}`,e):this.client.postJson(this.name,e)}}class y extends k{constructor(t,s){super(t,s),this.cache=new e((()=>this.loadAllInternal()))}loadAllInternal(){return this.client.getJson(`${this.name}/all`)}loadAll(){return this.cache.get()}loadSingle(e){return this.loadAll().then((t=>{const s=t.find((t=>t.id===e));if(void 0===e)throw new Error(`${this.name} id ${e} not found!`);return s}))}save(e){return super.save(e).then((e=>(this.cache.reset(),e)))}delete(e){return super.delete(e).then((()=>this.cache.reset()))}reset(){this.cache.reset()}getStats(){const e=this.cache.getCache()?.length;return{cachedItems:e||0,capacity:e||0}}}class S{constructor(){this.handlers=new Map}addEventListener(e,t){this.handlers.has(e)||this.handlers.set(e,[]),this.handlers.get(e).push(t)}removeEventListener(e,t){const s=this.handlers.get(e);s&&s.splice(s.indexOf(t),1)}triggerEvent(e,t){this.handlers.has(e)&&this.handlers.get(e).forEach((e=>e(t)))}}var w;!function(e){e.info="info",e.warning="warning",e.error="danger"}(w||(w={}));class R{constructor(e=20,t=7e3){this.maxAlerts=e,this.maxVisibilityMs=t,this.em=new S,this.alerts=[],this.visibleAlerts=[]}addOnChangeHandler(e){this.em.addEventListener("change",e)}removeOnChangeHandler(e){this.em.removeEventListener("change",e)}triggerChange(){this.em.triggerEvent("change")}reset(){this.alerts=[],this.visibleAlerts=[],this.triggerChange()}hide(e){this.visibleAlerts.splice(this.visibleAlerts.indexOf(e),1),this.triggerChange()}hideAll(){this.visibleAlerts=[],this.triggerChange()}updateVisibility(){this.visibleAlerts.forEach((e=>{const t=d.getSinceDurationMs(e.time)||this.maxVisibilityMs,s=this.maxVisibilityMs-t;s>0?e.remainsMs=s:(e.remainsMs=void 0,this.hide(e))})),this.triggerChange()}remove(e){this.alerts.splice(this.alerts.indexOf(e),1),this.triggerChange()}add(e){for(void 0===e.remainsMs&&(e.remainsMs=this.maxVisibilityMs),this.alerts.push(e),this.visibleAlerts.push(e);this.alerts.length>this.maxAlerts;)this.alerts.shift();this.triggerChange()}custom(e,t){this.add({time:new Date,type:e,message:t})}err(e){this.custom(w.error,"string"==typeof e?e:e.toString())}warn(e){this.custom(w.warning,e)}info(e){this.custom(w.info,e)}getSummary(){const e=new Map;Object.values(w).forEach(((t,s)=>{e.set(t,0)}));for(let t=0;t<this.alerts.length;t++){const s=this.alerts[t],r=e.get(s.type)||0;e.set(s.type,r+1)}return e}}class x{constructor(e,t=!1){this.isCancelled={value:!1},this.throwWhenCancelled=t,this.promise=new Promise(((t,s)=>{e.then((e=>{if(!this.isCancelled.value)return t(e)})).catch((e=>{!this.throwWhenCancelled&&this.isCancelled.value||s(e)}))}))}cancel(){this.isCancelled.value=!0}}const E=["read","write","admin"];class b extends f{constructor(e){super(`${o.trimSlashes(e)}/api/oauth`)}jwks(){return this.getJson("jwks.json")}verifyRefreshToken(e){return this.getJson(`refresh-tokens/verify/${e}`)}verifyAccessToken(e){return this.getJson(`access-tokens/verify/${e}`)}verifyIdToken(e){return this.getJson(`id-tokens/verify/${e}`)}requestRefreshTokenFromLogin(e){return this.postJson("refresh-tokens/from-login",e)}renewRefreshToken(e){return this.postJson("refresh-tokens/renew",e)}requestAccessToken(e){return this.postJson("access-tokens/from-refresh-token",e)}}class P{static isValidToken(e){return n.notEmpty(e)&&o.notBlank(e.token)&&!P.isTokenExpired(e)}static isTokenExpired(e){return null!=e&&(void 0!==e.expires&&null!==e.expires&&e.expires<new Date)}static isTokenReadyForRefresh(e){if(null==e)return!1;if(P.isTokenExpired(e))return!1;if(void 0===e.expires||null===e.expires)return!1;return new Date((e.expires.getTime()+e.issuedAt.getTime())/2)<new Date}static getScopeString(e,t){return`${t}:${e}`}static extractPrivilege(e){const t=e.split(":");return t.length<2?"":t[1]}static isPermissionLevel(e){return E.includes(e)}static extractPermissionLevel(e){const t=e.split(":");if(0===t.length)throw new Error(`Scope value ${e} is invalid!`);const s=t[0];if(!P.isPermissionLevel(s))throw new Error(`"${s} is not valid permission level!`);return s}static getLevel(e){switch(e){case"admin":return 3;case"write":return 2;case"read":return 1;default:return 0}}static hasPermission(e,t,s){if(void 0===s)try{s=P.extractPermissionLevel(t),t=P.extractPrivilege(t)}catch(e){s="admin"}const r=P.extractPermissionLevel(e);if(P.getLevel(r)<P.getLevel(s))return!1;const n=P.extractPrivilege(e);if("*"===n)return!0;if(n===t)return!0;if(!n?.endsWith("/*"))return!1;const i=n.replace("/*","");return t?.startsWith(i)??!1}}class M{constructor(e,t,s){this.initialRefreshTokenProvider=s,this.audience=t,this.oAuthServer=new b(e),this.accessTokens=new Map}hasValidRefreshToken(){return P.isValidToken(this.refreshToken)}hasValidAccessToken(e){return P.isValidToken(this.accessTokens.get(e))}reset(){return this.refreshToken=void 0,this.accessTokens.clear(),this.initialRefreshTokenProvider.reset()}getRefreshTokenInternal(){return this.hasValidRefreshToken()&&void 0!==this.refreshToken?Promise.resolve(this.refreshToken):this.initialRefreshTokenProvider.getRefreshToken()}getRefreshToken(){return this.getRefreshTokenInternal().then((e=>P.isValidToken(e)?P.isTokenReadyForRefresh(e)?this.oAuthServer.renewRefreshToken({refreshToken:e.token}).then((e=>(this.setRefreshToken(e),e))):(this.setRefreshToken(e),Promise.resolve(e)):(console.log("invalid refresh token",e),Promise.reject("Received invalid ID token!"))))}getRefreshTokenRaw(){return this.getRefreshToken().then((e=>e.token))}setRefreshToken(e){this.refreshToken=e}verifyRefreshToken(e){return this.oAuthServer.verifyRefreshToken(e)}login(e,t){return this.reset(),this.oAuthServer.requestRefreshTokenFromLogin({login:e,password:t,targetAudience:this.audience}).then((e=>(this.setRefreshToken(e),e)))}storeAccessToken(e,t){this.accessTokens.set(e,t)}findStoredAccessToken(e){const t=P.extractPermissionLevel(e),s=P.extractPrivilege(e);for(const[e,r]of this.accessTokens)if(P.hasPermission(e,s,t))return r}getAccessTokenInternal(e){return this.getRefreshTokenRaw().then((t=>this.oAuthServer.requestAccessToken({refreshToken:t,targetAudience:this.audience,scope:e}).then((t=>P.isValidToken(t)?(t.scopes&&t.scopes.length>0?t.scopes.forEach((e=>this.storeAccessToken(e,t))):this.storeAccessToken(e,t),t):Promise.reject("Received access token is not valid!")))))}getAccessToken(e){const t=this.findStoredAccessToken(e);return void 0!==t&&P.isValidToken(t)?(P.isTokenReadyForRefresh(t)&&this.getAccessTokenInternal(e),Promise.resolve(t.token)):this.getAccessTokenInternal(e).then((e=>e.token))}}class ${constructor(e){this.value=e}getSubjectType(){return o.isEmpty(this.value)?null:this.value.split(":")[0]}getSubjectContent(){if(o.isEmpty(this.value))return null;const e=this.value.split("//");return e.length>1?e[1]:null}toString(){return this.value}}class A{redirectTo(e){return this.redirecting=e,document.location.href=e,Promise.reject(`Redirecting to ${e}`)}isRedirecting(){return o.notBlank(this.redirecting)}redirectingTo(){return o.getNonEmpty(this.redirecting)}}class L extends A{constructor(e,t){super(),this.client=e,this.tokenQueryName=t||"token"}redirectToLogin(){return this.client.getServerInfo().then((e=>{const t=p.deleteParamFromUrl(document.location.toString(),this.tokenQueryName),s=`${e.oauthServerUrl}/login?app_name=${e.targetAudience}&redirect_url=${t}`;return this.redirectTo(s)})).catch((e=>(console.error("Redirection failed: OAuth info not fetched:",e),Promise.reject(e))))}getRefreshToken(){return this.redirectToLogin()}reset(){return Promise.resolve()}}class N extends A{constructor(e,t){super(),this.client=e,this.tokenQueryName=t||"token"}getRefreshTokenFromUrl(){return p.extractParamFromUrl(document.location.toString(),this.tokenQueryName)}getRefreshToken(){const e=this.getRefreshTokenFromUrl();return null===e||o.isBlank(e)?Promise.reject("No token in URL!"):this.client.getTokenManager().then((t=>t.verifyRefreshToken(e)))}reset(){const e=this.getRefreshTokenFromUrl();if(null===e||o.isBlank(e))return Promise.resolve();console.log("Token in URL, redirecting...");const t=p.deleteParamFromUrl(document.location.toString(),this.tokenQueryName);return this.redirectTo(t)}}class U{constructor(e){this.key=e||"refresh-token"}saveRefreshTokenToLocalStorage(e){const t=e?JSON.stringify(e):null;null!==t?localStorage.setItem(this.key,t):localStorage.removeItem(this.key)}getRefreshTokenFromLocalStorage(){return m.parse(localStorage.getItem(this.key))}getRefreshToken(){const e=this.getRefreshTokenFromLocalStorage();return e&&P.isValidToken(e)?Promise.resolve(e):Promise.reject("No valid token found in storage!")}reset(){return this.saveRefreshTokenToLocalStorage(null),Promise.resolve()}}class D{constructor(e,t,s){this.login=new L(e,s),this.url=new N(e,s),this.storage=new U(t)}getRefreshToken(){return this.url.getRefreshToken().catch((e=>(console.log("No token in url, loading from storage:",e),this.storage.getRefreshToken().catch((e=>(console.log("No token in storage, redirecting to login page:",e),this.login.getRefreshToken())))))).then((e=>(console.log("Token found, saving to storage..."),this.storage.saveRefreshTokenToLocalStorage(e),this.url.reset().then((()=>e)))))}reset(){return this.storage.reset().then((()=>this.url.reset()))}}class F extends f{constructor(t,s,r="admin:*"){super(t),this.freshIdTokenProvider=s||new D(this),this.defaultScope=r,this.insecureClient=new f(t),this.serverInfo=new e((()=>this.getServerInfoInternal())),this.tokenManager=new e((()=>this.getTokenManagerInternal()))}getRefreshToken(){return this.getTokenManager().then((e=>e.getRefreshToken()))}initialize(){return this.getRefreshToken()}logout(){return this.reset().then((()=>this.initialize()))}reset(){return this.getTokenManager().then((e=>e.reset()))}getScope(e){return this.defaultScope}getServerInfoInternal(){return this.insecureClient.getJson("status/oauth/info")}getServerInfo(){return this.serverInfo.get()}getTokenManagerInternal(){return this.getServerInfo().then((e=>new M(e.oauthServerUrl,e.targetAudience,this.freshIdTokenProvider)))}getTokenManager(){return this.tokenManager.get()}login(e,t){return this.getTokenManager().then((s=>s.login(e,t)))}setIdToken(e){return this.getTokenManager().then((t=>t.setRefreshToken(e)))}getHeaders(e){return this.getTokenManager().then((t=>t.getAccessToken(this.getScope(e)))).then((t=>super.getHeaders(e).then((e=>(e.set("Authorization",`Bearer ${t}`),e)))))}}class q{constructor(e,t){this.x=e,this.y=t}distanceTo(e){return Math.sqrt(Math.pow(this.x-e.x,2)+Math.pow(this.y-e.y,2))}equalsTo(e){return!!e&&(this.x===e.x&&this.y===e.y)}size(){return this.distanceTo(new q(0,0))}inSize(e){const t=this.size();if(0!==t){const s=e/t;return new q(this.x*s,this.y*s)}return this}round(){return new q(Math.round(this.x),Math.round(this.y))}add(e){return new q(this.x+e.x,this.y+e.y)}multiply(e){return new q(this.x*e,this.y*e)}subtract(e){return new q(this.x-e.x,this.y-e.y)}sub(e){return this.subtract(e)}toArray(){return[this.x,this.y]}static fromArray(e){if("object"==typeof e&&2===e.length)return new q(e[0],e[1])}clone(){return new q(this.x,this.y)}getAngleToYAxis(e){const t=e.subtract(this),s=t.y<0,r=t.x/t.size(),n=Math.asin(r);return(s?Math.PI-n:n)||0}getNeighborPositions(e=1,t=!1){const s=[],r=this.x+e;for(let n=this.x-e;n<=r;n++){const r=this.y+e;for(let i=this.y-e;i<=r;i++){const e=new q(n,i);!t&&this.equalsTo(e)||s.push(e)}}return s}getClosest(e){if(!e||0===e.length)return null;if(1===e.length)return e[0];let t=e[0],s=this.distanceTo(t);for(let r=1,n=e.length;r<n;r++){const n=this.distanceTo(e[r]);n<s&&(t=e[r],s=n)}return t}toString(e=2){return`[${g.round(this.x,e)},${g.round(this.y,e)}]`}}var I={"--self-name":"Čeština",Anonymous:"Anonym",Administrator:"Administrátor",Back:"Zpět",File:"Soubor",Language:"Jazyk",Image:"Obrázek",Status:"Stav",State:"Stav",System:"Systém",Date:"Datum",Page:"Stránka","Page size":"Velikost stránky","Total items":"Celkem záznamů","Log out":"Odhlásit",Move:"Přesunout",Delete:"Smazat",Close:"Zavřít",Edit:"Upravit",Save:"Uložit",Refresh:"Obnovit",Select:"Vybrat","More...":"Více...","Loading...":"Nahrávám...",New:[{tags:["feminine"],value:"Nová"},{value:"Nový"}],Name:[{tags:["neutral"],value:"Název"},{value:"Jméno"}]},C={"--self-name":"English"};class B{constructor(e){this.data=e}translate(e,t){const s=this.data[e];if(void 0===s||"string"==typeof s)return s;const r=s.find((e=>void 0===e.tags||0===e.tags.length));if((void 0===t||void 0===t.tags||0===t.tags.length)&&void 0!==r)return r.value;const n=s.filter((e=>void 0!==e.tags&&0!==e.tags.length&&(t&&t.tags&&t.tags.every((t=>e.tags&&e.tags.includes(t))))));return n.length>0?n[0].value:r?r.value:void 0}}class J extends B{constructor(){super(I)}}class O extends B{constructor(){super(C)}}class z{constructor(e,t){this.primary=e,this.fallback=t}translate(e,t){const s=this.primary.translate(e,t);return void 0===s?this.fallback.translate(e,t):s}}class j{constructor(e){this.dictionaries=new Map,this.setLanguage(e)}addDictionary(e,t){const s=this.dictionaries.get(e);s?this.dictionaries.set(e,new z(t,s)):this.dictionaries.set(e,t)}hasDictionary(e){return!!e&&this.dictionaries.has(e)}getLanguage(){return this.language}getLanguages(){return Array.from(this.dictionaries.keys())}setLanguage(e){this.language=e&&this.hasDictionary(e)?e:this.hasDictionary(navigator.language)?navigator.language:void 0}translate(e,t,s){if(!(s=s||this.language))return e;const r=this.dictionaries.get(s);if(!r)return e;const n=r.translate(e,t);return void 0===n?e:n}}class V extends j{constructor(e){super(),this.addDictionary("cs",new J),this.addDictionary("en",new O),this.setLanguage(e)}}export{a as ArrayUtil,h as AsyncUtil,V as BasicLocalization,c as ByteUtil,t as CacheAsync,x as CancellablePromise,J as CzechBasicDictionary,d as DateUtil,z as DictionaryWithFallback,O as EnglishBasicDictionary,T as EntityCachedClient,k as EntityClient,v as EntityClientWithStub,S as EventManager,s as HashCacheAsync,i as HashUtil,m as JsonUtil,r as Lazy,e as LazyAsync,j as Localization,y as LookupClient,B as MemoryDictionary,g as NumberUtil,b as OAuthRestClient,$ as OAuthSubject,M as OAuthTokenManager,n as ObjectUtil,E as PERMISSION_LEVELS,l as PagingUtil,f as RestClient,F as RestClientWithOAuth,o as StringUtil,p as UrlUtil,w as UserAlertType,R as UserAlerts,q as Vector2};
1
+ class e{constructor(e){this.supplier=e}get(){return void 0!==this.cache?Promise.resolve(this.cache):(void 0===this.promise&&(this.promise=this.supplier().then((e=>(this.cache=e,this.promise=void 0,Promise.resolve(e)))).catch((e=>(this.promise=void 0,Promise.reject(e))))),this.promise)}reset(){this.cache=void 0}hasCache(){return void 0!==this.cache}getCache(){return this.cache}}class t extends e{constructor(e,t){super(e),this.maxAgeMs=t}get(){return this.expires&&this.expires>new Date&&this.reset(),super.get()}set(e,t){this.cache=e,this.expires=t,this.maxAgeMs&&void 0===this.expires&&(this.expires=new Date((new Date).getTime()+this.maxAgeMs))}}class s{constructor(e,t){this.cache=new Map,this.maxSize=100,this.supplier=e,t&&(this.maxSize=t)}obtainCache(e){let s=this.cache.get(e);return s||(s=new t((()=>this.supplier(e))),this.cache.set(e,s)),s}get(e){return this.obtainCache(e).get()}set(e,t,s){this.obtainCache(e).set(t,s)}reset(e){e?this.cache.delete(e):this.cache.clear()}getSize(){return this.cache.size}getMaxSize(){return this.maxSize}getStats(){return{cachedItems:this.getSize(),capacity:this.getMaxSize()}}hasCache(e){return this.cache.has(e)}}class r{constructor(e){this.supplier=e}get(){return void 0===this.cache&&(this.cache=this.supplier()),this.cache}reset(){this.cache=void 0}hasCache(){return void 0!==this.cache}}class n{static isEmpty(e){return null==e}static notEmpty(e){return!n.isEmpty(e)}static clone(e){if(null===e)throw new Error("Null cannot be cloned!");if("object"!=typeof e)throw new Error("Not an object, cannot be cloned!");return{...e}}static getNestedValue(e,t){if(!e||""===e)return"";const s=t.split(".");let r=e;for(const e of s){if(!r||"object"!=typeof r||!(e in r))return"";r=r[e]}return r}}class i{static crc32hex(e){const t=(new TextEncoder).encode(e),s=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?3988292384^t>>>1:t>>>1;s[e]=t>>>0}let r=~0;for(let e=0;e<t.length;e++)r=r>>>8^s[255&(r^t[e])];return r=~r>>>0,r.toString(16)}}class o{static isString(e){return"string"==typeof e}static toString(e){return o.isString(e)?e:o.isString(e.message)?e.message:e?.toString?.()??""}static isEmpty(e){return!!n.isEmpty(e)||0===e.length}static notEmpty(e){return!o.isEmpty(e)}static isBlank(e){return o.isEmpty(o.safeTrim(e))}static notBlank(e){return!o.isBlank(e)}static substr(e,t,s){return this.isEmpty(e)?"":e.substring(t,s)}static replace(e,t,s){return this.isEmpty(e)||this.isEmpty(t)?"":e.replace(t,String(s))}static containsLineBreaks(e){return o.safeContains(e,"\n")}static safeContains(e,t,s=!0){return!o.isBlank(e)&&!o.isBlank(t)&&(s?o.safeContains(e.toLowerCase(),t.toLowerCase(),!1):e.includes(t))}static trimLeadingSlashes(e){return this.isEmpty(e)?"":o.toString(e).replace(/^\//g,"")}static trimTrailingSlashes(e){return this.isEmpty(e)?"":o.toString(e).replace(/\/$/g,"")}static trimSlashes(e){return this.isEmpty(e)?"":o.toString(e).replace(/^\/|\/$/g,"")}static safeTruncate(e,t,s=""){return o.isEmpty(e)||!e?"":(e=o.toString(e)).length<=t?String(e):e.substring(0,t-s.length)+s}static ellipsis(e,t,s="..."){return o.safeTruncate(e,t,s)}static safeTrim(e){return o.isEmpty(e)?"":o.toString(e).trim()}static safeLowercase(e){return o.isEmpty(e)||!e?"":o.toString(e).toLowerCase()}static safeUppercase(e){return o.isEmpty(e)||!e?"":o.toString(e).toUpperCase()}static capitalizeFirstLetter(e){return o.isBlank(e)?"":o.safeUppercase(e.charAt(0))+o.safeLowercase(o.substr(e,1))}static toBigInt(e){return this.isEmpty(e)?null:BigInt(e)}static getNonEmpty(...e){return e.find((e=>o.notEmpty(e)))||""}static getNonBlank(...e){return e.find((e=>o.notBlank(e)))||""}static emptyToNull(e){return o.isEmpty(e)?null:String(e)}static blankToNull(e){return o.isBlank(e)?null:String(e)}static randomString(){return i.crc32hex(Date()+Math.random())}}class a{static isEmpty(e){return n.isEmpty(e)||0===e.length}static notEmpty(e){return!a.isEmpty(e)}static remove(e,t){return a.isEmpty(e)?[]:e?.filter((e=>e!==t))}static extract(e,t=0,s){if(!e||e.length<=t)return[];const r=void 0===s?void 0:t+s;return e.slice(t,r)}static extractStart(e,t){return a.extract(e,0,t)}}class h{}h.sleep=e=>new Promise((t=>setTimeout(t,e)));class c{static formatByteSize(e){const t=Number(e);if(null===t||Number.isNaN(t))return"";if(0===t)return"0";const s=Math.floor(Math.log(t)/Math.log(1024));return 1*+(t/Math.pow(1024,s)).toFixed(2)+" "+["B","kB","MB","GB","TB"][s]}}const u={page:0,size:10};class l{static sortingFieldToString(e){if(!e)return"";const t=[];return t.push(e.name),t.push(e.desc?"desc":""),t.push(e.nullsLast?"nl":""),t.join("-")}static sortingFieldFromString(e){const t=e.split("-");return{name:t[0],desc:t.length>1&&"desc"===o.safeLowercase(t[1]),nullsLast:t.length>2&&"nl"===o.safeLowercase(t[2])}}static sortingRequestToString(e){return e.map((e=>l.sortingFieldToString(e))).join("+")}static sortingRequestFromString(e){if(!e)return[];return e.split("+").map((e=>l.sortingFieldFromString(e)))}static pagingRequestToQueryParams(e){if(!e)return;const t={page:e.page,size:e.size};return e.search&&(t.search=e.search),e.sorting&&(t.sorting=l.sortingRequestToString(e.sorting)),t}static pagingRequestToString(e){if(!e)return"";const t=[];return t.push(String(e.page)),t.push(String(e.size)),t.push(o.safeTrim(e.search)),t.push(e.sorting?l.sortingRequestToString(e.sorting):""),t.join(":")}static pagingRequestFromString(e){if(!e||o.isEmpty(e))return{...u};const t=e.split(":");return t.length<4?{...u}:{page:Number(t[0]),size:Number(t[1]),search:String(t[2]),sorting:o.isEmpty(t[3])?void 0:l.sortingRequestFromString(t[3])}}}class g{static isEmpty(e){return null==e||Number.isNaN(e)}static notEmpty(e){return!n.isEmpty(e)}static parseNumber(e){if(!e)return null;const t=Number(e);return Number.isNaN(t)?null:t}static round(e,t){t||(t=0);const s=Math.pow(10,t);return Math.round(e*s)/s}static portionToPercent(e,t){if(null==e)return"";return`${g.round(100*e,t)}%`}}class d{static formatNumber(e,t=2){return String(e).padStart(t,"0")}static parseDate(e){if(e)return"string"==typeof e?new Date(e):e}static formatDateForHumans(e,t=!1){if(!(e=d.parseDate(e)))return"";const s=e.getFullYear(),r=d.formatNumber(e.getMonth()+1),n=d.formatNumber(e.getDate());if(!t)return`${s}-${r}-${n}`;return`${s}/${r}/${n} ${d.formatNumber(e.getHours())}:${d.formatNumber(e.getMinutes())}:${d.formatNumber(e.getSeconds())}`}static formatDateTimeForHumans(e){return d.formatDateForHumans(e,!0)}static formatDateForInput(e,t=!1){if(!(e=d.parseDate(e)))return"";const s=e.getFullYear(),r=d.formatNumber(e.getMonth()+1),n=d.formatNumber(e.getDate());if(!t)return`${s}-${r}-${n}`;return`${s}-${r}-${n}T${d.formatNumber(e.getHours())}:${d.formatNumber(e.getMinutes())}:${d.formatNumber(e.getSeconds())}`}static formatDateTimeForInput(e){return d.formatDateForInput(e,!0)}static getDurationMs(e,t){if(e=d.parseDate(e),t=d.parseDate(t),n.isEmpty(e)||n.isEmpty(t))return null;try{return t.getTime()-e.getTime()}catch(e){return null}}static getSinceDurationMs(e){return d.getDurationMs(e,new Date)}static formatDuration(e){if(!e)return"";let t=Math.floor(e/1e3);e-=1e3*t;let s=Math.floor(t/60);t-=60*s;let r=Math.floor(s/60);s-=60*r;let n=Math.floor(r/24);r-=24*n;const i=[];return n>0&&i.push(`${n}d`),r>0&&i.push(`${r}h`),s>0&&i.push(`${s}m`),t>0&&0===n&&0===r&&i.push(`${t}s`),e>0&&0===n&&0===r&&0===s&&i.push(`${g.round(e,2)}ms`),i.join(" ")}}class m{static dateParser(e,t){return"string"==typeof t&&m.reISO.exec(t)?new Date(t):t}static parseWithDates(e){if(!o.isBlank(e))return JSON.parse(o.getNonEmpty(e),m.dateParser)}static parse(e){return m.parseWithDates(e)}}m.reISO=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;class p{static deleteParamFromUrl(e,t){const s=new URL(e);return s.searchParams.delete(t),o.trimTrailingSlashes(s.toString())}static extractParamFromUrl(e,t){return new URLSearchParams(new URL(e).search).get(t)}static paramExistsInUrl(e,t){return o.notBlank(p.extractParamFromUrl(e,t))}static extractHostFromUrl(e){return o.isBlank(e)?null:new URL(e).host}static extractDomainFromUrl(e){const t=p.extractHostFromUrl(e);return o.isBlank(t)?null:t.split(".").slice(-2).join(".")}}class f{constructor(e){o.isBlank(e)?this.baseUrl=f.baseHostUrl():(e.endsWith("/")||(e+="/"),this.baseUrl=e.startsWith("http")?new URL(e):new URL(e,f.baseHostUrl()))}static baseHostUrl(){return new URL(`${window.location.protocol}//${window.location.host}/`)}static pagingRequestToQueryParams(e){return l.pagingRequestToQueryParams(e)}static paramsToQueryString(e){if(!e)return"";const t=new URLSearchParams(e),s=new URLSearchParams;t.forEach(((e,t)=>{""!==e&&void 0!==e&&"undefined"!==e&&s.set(t,e)}));const r=s.toString();return o.isEmpty(r)?"":`?${r}`}getHeaders(e){const t=new Headers;return t.set("Content-Type","application/json"),Promise.resolve(t)}getBaseUrl(){return this.baseUrl}getUrl(e,t){const s=new URL(o.trimLeadingSlashes(e),this.getBaseUrl());return t&&Object.keys(t).forEach((e=>{const r=t[e];""!==r&&void 0!==r&&"undefined"!==r&&s.searchParams.set(e,r)})),s}getRequestOptions(e,t="GET",s=null){return this.getHeaders(e).then((e=>({method:t,headers:e,body:null===s?null:s instanceof FormData?s:JSON.stringify(s)})))}processRequest(e,t,s){return fetch(this.getUrl(e,t),s).then((e=>{if(!e.ok){const t={cause:e.status};return"application/json"===e.headers.get("Content-Type")?e.json().then((s=>{if(s.message)throw new Error(s.message,t);if(s.error)throw new Error(s.error,t);throw new Error(e.statusText,t)}),(()=>{throw new Error(e.statusText,t)})):e.text().then((s=>{throw o.isEmpty(s)?new Error(e.statusText,t):new Error(s,t)}),(()=>{throw new Error(e.statusText,t)}))}return e}))}processRequestJson(e,t,s){return this.processRequest(e,t,s).then((e=>e.text().then(m.parseWithDates)))}getJson(e,t){return this.getRequestOptions(e).then((s=>this.processRequestJson(e,t,s)))}postJson(e,t=null,s){return this.getRequestOptions(e,"POST",t).then((t=>this.processRequestJson(e,s,t)))}postForm(e,t,s){return this.getRequestOptions(e,"POST",t).then((t=>(t.headers.delete("Content-Type"),this.processRequest(e,s,t))))}postFormJson(e,t,s){return this.getRequestOptions(e,"POST",t).then((t=>(t.headers.delete("Content-Type"),this.processRequestJson(e,s,t))))}putJson(e,t=null,s){return this.getRequestOptions(e,"PUT",t).then((t=>this.processRequestJson(e,s,t)))}get(e,t){return this.getRequestOptions(e).then((s=>this.processRequest(e,t,s)))}del(e,t){return this.getRequestOptions(e,"DELETE").then((s=>this.processRequest(e,t,s)))}post(e,t=null,s){return this.getRequestOptions(e,"POST",t).then((t=>this.processRequest(e,s,t)))}put(e,t=null,s){return this.getRequestOptions(e,"PUT",t).then((t=>this.processRequest(e,s,t)))}}class k{constructor(e,t){this.client=e,this.name=t}loadSingle(e){return this.client.getJson(`${this.name}/${e}`)}loadPage(e){return this.client.getJson(this.name,f.pagingRequestToQueryParams(e))}save(e){return e.id?this.client.putJson(`${this.name}/${e.id}`,e):this.client.postJson(this.name,e)}delete(e){return this.client.del(`${this.name}/${e}`)}}class T extends k{constructor(e,t,r){super(e,t),this.cache=new s((e=>super.loadSingle(e)),r)}loadSingle(e){return this.cache.get(e)}save(e){return super.save(e).then((e=>(e.id&&this.cache.set(e.id,e),e)))}delete(e){return super.delete(e).then((()=>this.cache.reset(e)))}reset(e){this.cache.reset(e)}getStats(){return this.cache.getStats()}}class v extends k{loadSingle(e){throw new Error("Use loadSingleStub() instead!")}loadSingleStub(e){return this.client.getJson(`${this.name}/${e}`)}save(e){throw new Error("Use saveStub() instead!")}saveStub(e){return e.id?this.client.putJson(`${this.name}/${e.id}`,e):this.client.postJson(this.name,e)}}class y extends k{constructor(t,s){super(t,s),this.cache=new e((()=>this.loadAllInternal()))}loadAllInternal(){return this.client.getJson(`${this.name}/all`)}loadAll(){return this.cache.get()}loadSingle(e){return this.loadAll().then((t=>{const s=t.find((t=>t.id===e));if(void 0===e)throw new Error(`${this.name} id ${e} not found!`);return s}))}save(e){return super.save(e).then((e=>(this.cache.reset(),e)))}delete(e){return super.delete(e).then((()=>this.cache.reset()))}reset(){this.cache.reset()}getStats(){const e=this.cache.getCache()?.length;return{cachedItems:e||0,capacity:e||0}}}class S{constructor(){this.handlers=new Map}addEventListener(e,t){this.handlers.has(e)||this.handlers.set(e,[]),this.handlers.get(e).push(t)}removeEventListener(e,t){const s=this.handlers.get(e);s&&s.splice(s.indexOf(t),1)}triggerEvent(e,t){this.handlers.has(e)&&this.handlers.get(e).forEach((e=>e(t)))}}var w;!function(e){e.info="info",e.warning="warning",e.error="danger"}(w||(w={}));class R{constructor(e=20,t=7e3){this.maxAlerts=e,this.maxVisibilityMs=t,this.em=new S,this.alerts=[],this.visibleAlerts=[]}addOnChangeHandler(e){this.em.addEventListener("change",e)}removeOnChangeHandler(e){this.em.removeEventListener("change",e)}triggerChange(){this.em.triggerEvent("change")}reset(){this.alerts=[],this.visibleAlerts=[],this.triggerChange()}hide(e){this.visibleAlerts.splice(this.visibleAlerts.indexOf(e),1),this.triggerChange()}hideAll(){this.visibleAlerts=[],this.triggerChange()}updateVisibility(){this.visibleAlerts.forEach((e=>{const t=d.getSinceDurationMs(e.time)||this.maxVisibilityMs,s=this.maxVisibilityMs-t;s>0?e.remainsMs=s:(e.remainsMs=void 0,this.hide(e))})),this.triggerChange()}remove(e){this.alerts.splice(this.alerts.indexOf(e),1),this.triggerChange()}add(e){for(void 0===e.remainsMs&&(e.remainsMs=this.maxVisibilityMs),this.alerts.push(e),this.visibleAlerts.push(e);this.alerts.length>this.maxAlerts;)this.alerts.shift();this.triggerChange()}custom(e,t){this.add({time:new Date,type:e,message:t})}err(e){this.custom(w.error,"string"==typeof e?e:e.toString())}warn(e){this.custom(w.warning,e)}info(e){this.custom(w.info,e)}getSummary(){const e=new Map;Object.values(w).forEach(((t,s)=>{e.set(t,0)}));for(let t=0;t<this.alerts.length;t++){const s=this.alerts[t],r=e.get(s.type)||0;e.set(s.type,r+1)}return e}}class x{constructor(e,t=!1){this.isCancelled={value:!1},this.throwWhenCancelled=t,this.promise=new Promise(((t,s)=>{e.then((e=>{if(!this.isCancelled.value)return t(e)})).catch((e=>{!this.throwWhenCancelled&&this.isCancelled.value||s(e)}))}))}cancel(){this.isCancelled.value=!0}}const E=["read","write","admin"];class b extends f{constructor(e){super(`${o.trimSlashes(e)}/api/oauth`)}jwks(){return this.getJson("jwks.json")}verifyRefreshToken(e){return this.getJson(`refresh-tokens/verify/${e}`)}verifyAccessToken(e){return this.getJson(`access-tokens/verify/${e}`)}verifyIdToken(e){return this.getJson(`id-tokens/verify/${e}`)}requestRefreshTokenFromLogin(e){return this.postJson("refresh-tokens/from-login",e)}renewRefreshToken(e){return this.postJson("refresh-tokens/renew",e)}requestAccessToken(e){return this.postJson("access-tokens/from-refresh-token",e)}}class P{static isValidToken(e){return n.notEmpty(e)&&o.notBlank(e.token)&&!P.isTokenExpired(e)}static isTokenExpired(e){return null!=e&&(void 0!==e.expires&&null!==e.expires&&e.expires<new Date)}static isTokenReadyForRefresh(e){if(null==e)return!1;if(P.isTokenExpired(e))return!1;if(void 0===e.expires||null===e.expires)return!1;return new Date((e.expires.getTime()+e.issuedAt.getTime())/2)<new Date}static getScopeString(e,t){return`${t}:${e}`}static extractPrivilege(e){const t=e.split(":");return t.length<2?"":t[1]}static isPermissionLevel(e){return E.includes(e)}static extractPermissionLevel(e){const t=e.split(":");if(0===t.length)throw new Error(`Scope value ${e} is invalid!`);const s=t[0];if(!P.isPermissionLevel(s))throw new Error(`"${s} is not valid permission level!`);return s}static getLevel(e){switch(e){case"admin":return 3;case"write":return 2;case"read":return 1;default:return 0}}static hasPermission(e,t,s){if(void 0===s)try{s=P.extractPermissionLevel(t),t=P.extractPrivilege(t)}catch(e){s="admin"}const r=P.extractPermissionLevel(e);if(P.getLevel(r)<P.getLevel(s))return!1;const n=P.extractPrivilege(e);if("*"===n)return!0;if(n===t)return!0;if(!n?.endsWith("/*"))return!1;const i=n.replace("/*","");return t?.startsWith(i)??!1}}class M{constructor(e,t,s){this.initialRefreshTokenProvider=s,this.audience=t,this.oAuthServer=new b(e),this.accessTokens=new Map}hasValidRefreshToken(){return P.isValidToken(this.refreshToken)}hasValidAccessToken(e){return P.isValidToken(this.accessTokens.get(e))}reset(){return this.refreshToken=void 0,this.accessTokens.clear(),this.initialRefreshTokenProvider.reset()}getRefreshTokenInternal(){return void 0!==this.refreshToken&&this.hasValidRefreshToken()?Promise.resolve(this.refreshToken):this.initialRefreshTokenProvider.getRefreshToken()}getRefreshToken(){return this.getRefreshTokenInternal().then((e=>P.isValidToken(e)?P.isTokenReadyForRefresh(e)?this.oAuthServer.renewRefreshToken({refreshToken:e.token}).then((e=>(this.setRefreshToken(e),e))):(this.setRefreshToken(e),Promise.resolve(e)):(console.log("invalid refresh token",e),Promise.reject("Received invalid refresh token!"))))}getRefreshTokenRaw(){return this.getRefreshToken().then((e=>e.token))}setRefreshToken(e){this.refreshToken=e}verifyRefreshToken(e){return this.oAuthServer.verifyRefreshToken(e)}login(e,t){return this.reset(),this.oAuthServer.requestRefreshTokenFromLogin({login:e,password:t,targetAudience:this.audience}).then((e=>(this.setRefreshToken(e),e)))}storeAccessToken(e,t){this.accessTokens.set(e,t)}findStoredAccessToken(e){const t=P.extractPermissionLevel(e),s=P.extractPrivilege(e);for(const[e,r]of this.accessTokens)if(P.hasPermission(e,s,t))return r}getAccessTokenInternal(e){return this.getRefreshTokenRaw().then((t=>this.oAuthServer.requestAccessToken({refreshToken:t,targetAudience:this.audience,scope:e}).then((t=>P.isValidToken(t)?(t.scopes&&t.scopes.length>0?t.scopes.forEach((e=>this.storeAccessToken(e,t))):this.storeAccessToken(e,t),t):Promise.reject("Received access token is not valid!")))))}getAccessToken(e){const t=this.findStoredAccessToken(e);return void 0!==t&&P.isValidToken(t)?(P.isTokenReadyForRefresh(t)&&this.getAccessTokenInternal(e),Promise.resolve(t.token)):this.getAccessTokenInternal(e).then((e=>e.token))}}class ${redirectTo(e){return this.redirecting=e,document.location.href=e,Promise.reject(`Redirecting to ${e}`)}isRedirecting(){return o.notBlank(this.redirecting)}redirectingTo(){return o.getNonEmpty(this.redirecting)}}class L extends ${constructor(e,t){super(),this.client=e,this.tokenQueryName=t||"token"}redirectToLogin(){return this.client.getServerInfo().then((e=>{const t=p.deleteParamFromUrl(document.location.toString(),this.tokenQueryName),s=`${e.oauthServerUrl}/login?app_name=${e.targetAudience}&redirect_url=${t}`;return this.redirectTo(s)})).catch((e=>(console.error("Redirection failed: OAuth info not fetched:",e),Promise.reject(e))))}getRefreshToken(){return this.redirectToLogin()}reset(){return Promise.resolve()}}class A extends ${constructor(e,t){super(),this.client=e,this.tokenQueryName=t||"token"}getRefreshTokenFromUrl(){return p.extractParamFromUrl(document.location.toString(),this.tokenQueryName)}getRefreshToken(){const e=this.getRefreshTokenFromUrl();return null===e||o.isBlank(e)?Promise.reject("No token in URL!"):this.client.getTokenManager().then((t=>t.verifyRefreshToken(e)))}reset(){const e=this.getRefreshTokenFromUrl();if(null===e||o.isBlank(e))return Promise.resolve();console.log("Token in URL, redirecting...");const t=p.deleteParamFromUrl(document.location.toString(),this.tokenQueryName);return this.redirectTo(t)}}class N{constructor(e){this.key=e||"refresh-token"}saveRefreshTokenToLocalStorage(e){const t=e?JSON.stringify(e):null;null!==t?localStorage.setItem(this.key,t):localStorage.removeItem(this.key)}getRefreshTokenFromLocalStorage(){return m.parse(localStorage.getItem(this.key))}getRefreshToken(){const e=this.getRefreshTokenFromLocalStorage();return e&&P.isValidToken(e)?Promise.resolve(e):Promise.reject("No valid token found in storage!")}reset(){return this.saveRefreshTokenToLocalStorage(null),Promise.resolve()}}class U{constructor(e,t,s){this.login=new L(e,s),this.url=new A(e,s),this.storage=new N(t)}getRefreshToken(){return this.url.getRefreshToken().catch((e=>(console.log("No token in url, loading from storage:",e),this.storage.getRefreshToken().catch((e=>(console.log("No token in storage, redirecting to login page:",e),this.login.getRefreshToken())))))).then((e=>(console.log("Token found, saving to storage..."),this.storage.saveRefreshTokenToLocalStorage(e),this.url.reset().then((()=>e)))))}reset(){return this.storage.reset().then((()=>this.url.reset()))}}class D extends f{constructor(t,s,r="admin:*"){super(t),this.freshIdTokenProvider=s||new U(this),this.defaultScope=r,this.insecureClient=new f(t),this.serverInfo=new e((()=>this.getServerInfoInternal())),this.tokenManager=new e((()=>this.getTokenManagerInternal()))}getRefreshToken(){return this.getTokenManager().then((e=>e.getRefreshToken()))}initialize(){return this.getRefreshToken()}logout(){return this.reset().then((()=>this.initialize()))}reset(){return this.getTokenManager().then((e=>e.reset()))}getScope(e){return this.defaultScope}getServerInfoInternal(){return this.insecureClient.getJson("status/oauth/info")}getServerInfo(){return this.serverInfo.get()}getTokenManagerInternal(){return this.getServerInfo().then((e=>new M(e.oauthServerUrl,e.targetAudience,this.freshIdTokenProvider)))}getTokenManager(){return this.tokenManager.get()}login(e,t){return this.getTokenManager().then((s=>s.login(e,t)))}setIdToken(e){return this.getTokenManager().then((t=>t.setRefreshToken(e)))}getHeaders(e){return this.getTokenManager().then((t=>t.getAccessToken(this.getScope(e)))).then((t=>super.getHeaders(e).then((e=>(e.set("Authorization",`Bearer ${t}`),e)))))}}class F{constructor(e,t){this.x=e,this.y=t}distanceTo(e){return Math.sqrt(Math.pow(this.x-e.x,2)+Math.pow(this.y-e.y,2))}equalsTo(e){return!!e&&(this.x===e.x&&this.y===e.y)}size(){return this.distanceTo(new F(0,0))}inSize(e){const t=this.size();if(0!==t){const s=e/t;return new F(this.x*s,this.y*s)}return this}round(){return new F(Math.round(this.x),Math.round(this.y))}add(e){return new F(this.x+e.x,this.y+e.y)}multiply(e){return new F(this.x*e,this.y*e)}subtract(e){return new F(this.x-e.x,this.y-e.y)}sub(e){return this.subtract(e)}toArray(){return[this.x,this.y]}static fromArray(e){if("object"==typeof e&&2===e.length)return new F(e[0],e[1])}clone(){return new F(this.x,this.y)}getAngleToYAxis(e){const t=e.subtract(this),s=t.y<0,r=t.x/t.size(),n=Math.asin(r);return(s?Math.PI-n:n)||0}getNeighborPositions(e=1,t=!1){const s=[],r=this.x+e;for(let n=this.x-e;n<=r;n++){const r=this.y+e;for(let i=this.y-e;i<=r;i++){const e=new F(n,i);!t&&this.equalsTo(e)||s.push(e)}}return s}getClosest(e){if(!e||0===e.length)return null;if(1===e.length)return e[0];let t=e[0],s=this.distanceTo(t);for(let r=1,n=e.length;r<n;r++){const n=this.distanceTo(e[r]);n<s&&(t=e[r],s=n)}return t}toString(e=2){return`[${g.round(this.x,e)},${g.round(this.y,e)}]`}}var q={"--self-name":"Čeština",Anonymous:"Anonym",Administrator:"Administrátor",Back:"Zpět",File:"Soubor",Language:"Jazyk",Image:"Obrázek",Status:"Stav",State:"Stav",System:"Systém",Date:"Datum",Page:"Stránka","Page size":"Velikost stránky","Total items":"Celkem záznamů","Log out":"Odhlásit",Move:"Přesunout",Delete:"Smazat",Close:"Zavřít",Edit:"Upravit",Save:"Uložit",Refresh:"Obnovit",Select:"Vybrat","More...":"Více...","Loading...":"Nahrávám...",New:[{tags:["feminine"],value:"Nová"},{value:"Nový"}],Name:[{tags:["neutral"],value:"Název"},{value:"Jméno"}]},C={"--self-name":"English"};class I{constructor(e){this.data=e}translate(e,t){const s=this.data[e];if(void 0===s||"string"==typeof s)return s;const r=s.find((e=>void 0===e.tags||0===e.tags.length));if((void 0===t||void 0===t.tags||0===t.tags.length)&&void 0!==r)return r.value;const n=s.filter((e=>void 0!==e.tags&&0!==e.tags.length&&(t&&t.tags&&t.tags.every((t=>e.tags&&e.tags.includes(t))))));return n.length>0?n[0].value:r?r.value:void 0}}class B extends I{constructor(){super(q)}}class J extends I{constructor(){super(C)}}class O{constructor(e,t){this.primary=e,this.fallback=t}translate(e,t){const s=this.primary.translate(e,t);return void 0===s?this.fallback.translate(e,t):s}}class z{constructor(e){this.dictionaries=new Map,this.setLanguage(e)}addDictionary(e,t){const s=this.dictionaries.get(e);s?this.dictionaries.set(e,new O(t,s)):this.dictionaries.set(e,t)}hasDictionary(e){return!!e&&this.dictionaries.has(e)}getLanguage(){return this.language}getLanguages(){return Array.from(this.dictionaries.keys())}setLanguage(e){this.language=e&&this.hasDictionary(e)?e:this.hasDictionary(navigator.language)?navigator.language:void 0}translate(e,t,s){if(!(s=s||this.language))return e;const r=this.dictionaries.get(s);if(!r)return e;const n=r.translate(e,t);return void 0===n?e:n}}class j extends z{constructor(e){super(),this.addDictionary("cs",new B),this.addDictionary("en",new J),this.setLanguage(e)}}export{a as ArrayUtil,h as AsyncUtil,j as BasicLocalization,c as ByteUtil,t as CacheAsync,x as CancellablePromise,B as CzechBasicDictionary,d as DateUtil,O as DictionaryWithFallback,J as EnglishBasicDictionary,T as EntityCachedClient,k as EntityClient,v as EntityClientWithStub,S as EventManager,s as HashCacheAsync,i as HashUtil,m as JsonUtil,r as Lazy,e as LazyAsync,z as Localization,y as LookupClient,I as MemoryDictionary,g as NumberUtil,b as OAuthRestClient,M as OAuthTokenManager,n as ObjectUtil,E as PERMISSION_LEVELS,l as PagingUtil,f as RestClient,D as RestClientWithOAuth,o as StringUtil,p as UrlUtil,w as UserAlertType,R as UserAlerts,F as Vector2};
2
2
  //# sourceMappingURL=index.esm.js.map