@uploadcare/blocks
Version:
Building blocks for Uploadcare products integration
26 lines • 80.2 kB
JavaScript
/**
* @license
* MIT License
*
* Copyright (c) 2022 Uploadcare (hello@uploadcare.com). All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
var Se=Object.defineProperty;var Re=(i,e,t)=>e in i?Se(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var d=(i,e,t)=>(Re(i,typeof e!="symbol"?e+"":e,t),t);function Gt(i){for(let e in i){let t=[...e].reduce((s,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),s+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),i[e].reg&&i[e].reg(t)}}var Ue=Object.defineProperty,Ie=(i,e,t)=>e in i?Ue(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,At=(i,e,t)=>(Ie(i,typeof e!="symbol"?e+"":e,t),t);function Oe(i){let e=t=>{var s;for(let r in t)((s=t[r])==null?void 0:s.constructor)===Object&&(t[r]=e(t[r]));return{...t}};return e(i)}var b=class{constructor(i){i.constructor===Object?this.store=Oe(i):(this._storeIsProxy=!0,this.store=i),this.callbackMap=Object.create(null)}static warn(i,e){console.warn(`Symbiote Data: cannot ${i}. Prop name: `+e)}read(i){return!this._storeIsProxy&&!this.store.hasOwnProperty(i)?(b.warn("read",i),null):this.store[i]}has(i){return this._storeIsProxy?this.store[i]!==void 0:this.store.hasOwnProperty(i)}add(i,e,t=!1){!t&&Object.keys(this.store).includes(i)||(this.store[i]=e,this.notify(i))}pub(i,e){if(!this._storeIsProxy&&!this.store.hasOwnProperty(i)){b.warn("publish",i);return}this.store[i]=e,this.notify(i)}multiPub(i){for(let e in i)this.pub(e,i[e])}notify(i){this.callbackMap[i]&&this.callbackMap[i].forEach(e=>{e(this.store[i])})}sub(i,e,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(i)?(b.warn("subscribe",i),null):(this.callbackMap[i]||(this.callbackMap[i]=new Set),this.callbackMap[i].add(e),t&&e(this.store[i]),{remove:()=>{this.callbackMap[i].delete(e),this.callbackMap[i].size||delete this.callbackMap[i]},callback:e})}static registerCtx(i,e=Symbol()){let t=b.globalStore.get(e);return t?console.warn('State: context UID "'+e+'" already in use'):(t=new b(i),b.globalStore.set(e,t)),t}static deleteCtx(i){b.globalStore.delete(i)}static getCtx(i,e=!0){return b.globalStore.get(i)||(e&&console.warn('State: wrong context UID - "'+i+'"'),null)}};b.globalStore=new Map;var _=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),Kt="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",De=Kt.length-1,Q=class{static generate(i="XXXXXXXXX-XXX"){let e="";for(let t=0;t<i.length;t++)e+=i[t]==="-"?i[t]:Kt.charAt(Math.random()*De);return e}};function Jt(i,e,t){let s=!0,r,n=e.split(".");return n.forEach((o,a)=>{a<n.length-1?i=i[o]:r=o}),i?i[r]=t:s=!1,s}function ke(i){return i.split("-").map((e,t)=>e&&t?e[0].toUpperCase()+e.slice(1):e).join("").split("_").map((e,t)=>e&&t?e.toUpperCase():e).join("")}function Le(i,e){[...i.querySelectorAll(`[${_.REPEAT_ATTR}]`)].forEach(t=>{let s=t.getAttribute(_.REPEAT_ITEM_TAG_ATTR),r;if(s&&(r=window.customElements.get(s)),!r){r=class extends e.BaseComponent{constructor(){super(),s||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(s)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(_.REPEAT_ATTR);e.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],l,c=u=>{u.forEach((p,m)=>{if(a[m])if(a[m].set$)setTimeout(()=>{a[m].set$(p)});else for(let g in p)a[m][g]=p[g];else{l||(l=new DocumentFragment);let g=new r;Object.assign(g.init$,p),l.appendChild(g)}}),l&&t.appendChild(l);let h=a.slice(u.length,a.length);for(let p of h)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let h in o){let p=o[h];Object.defineProperty(p,"_KEY_",{value:h,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(_.REPEAT_ATTR),t.removeAttribute(_.REPEAT_ITEM_TAG_ATTR)})}function Pe(i,e){if(e.shadowRoot)return;let t=[...i.querySelectorAll("slot")];if(e.initChildren.length&&t.length){let s={};t.forEach(r=>{let n=r.getAttribute("name");n?s[n]={slot:r,fr:document.createDocumentFragment()}:s.__default__={slot:r,fr:document.createDocumentFragment()}}),e.initChildren.forEach(r=>{var n;let o=(n=r.getAttribute)==null?void 0:n.call(r,"slot");o?(r.removeAttribute("slot"),s[o].fr.appendChild(r)):s.__default__&&s.__default__.fr.appendChild(r)}),Object.values(s).forEach(r=>{r.slot.parentNode.insertBefore(r.fr,r.slot),r.slot.remove()})}}function Me(i,e){[...i.querySelectorAll(`[${_.EL_REF_ATTR}]`)].forEach(t=>{let s=t.getAttribute(_.EL_REF_ATTR);e.ref[s]=t,t.removeAttribute(_.EL_REF_ATTR)})}function Ne(i,e){[...i.querySelectorAll(`[${_.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(_.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=ke(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),a=o[0],l;a.indexOf(_.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(_.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let h;u.startsWith("!!")?(h="double",u=u.replace("!!","")):u.startsWith("!")&&(h="single",u=u.replace("!","")),e.sub(u,p=>{h==="double"?p=!!p:h==="single"&&(p=!p),l?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,p):Jt(t,a,p)||(t[_.SET_LATER_KEY]||(t[_.SET_LATER_KEY]=Object.create(null)),t[_.SET_LATER_KEY][a]=p)})}}),t.removeAttribute(_.BIND_ATTR)})}var ut="{{",Z="}}",Ve="skip-text";function $e(i){let e,t=[],s=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Ve))&&r.textContent.includes(ut)&&r.textContent.includes(Z)&&1}});for(;e=s.nextNode();)t.push(e);return t}var Fe=function(i,e){$e(i).forEach(s=>{let r=[],n;for(;s.textContent.includes(Z);)s.textContent.startsWith(ut)?(n=s.textContent.indexOf(Z)+Z.length,s.splitText(n),r.push(s)):(n=s.textContent.indexOf(ut),s.splitText(n)),s=s.nextSibling;r.forEach(o=>{let a=o.textContent.replace(ut,"").replace(Z,"");o.textContent="",e.sub(a,l=>{o.textContent=l})})})},Be=[Le,Pe,Me,Ne,Fe],Wt="'",qt='"',je=/\\([0-9a-fA-F]{1,6} ?)/g,ze=/^'|'$/g;function He(i){return i.startsWith(Wt)&&i.endsWith(Wt)||i.startsWith(qt)&&i.endsWith(qt)}function Xe(i){let e=i;return He(i)&&(e=e.replace(ze,'"'),e=e.replace(je,(t,s)=>String.fromCodePoint(parseInt(s.trim(),16)))),e}var Yt=0,H=null,M=null,V=class extends HTMLElement{constructor(){super(),At(this,"updateCssData",()=>{var i;this.dropCssDataCache(),(i=this.__boundCssProps)==null||i.forEach(e=>{let t=this.getCssData(this.__extractCssName(e),!0);t!==null&&this.$[e]!==t&&(this.$[e]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return V}initCallback(){}__initCallback(){var i;this.__initialized||(this.__initialized=!0,(i=this.initCallback)==null||i.call(this))}render(i,e=this.renderShadow){let t;if((e||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(_.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?i=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(i||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(i==null?void 0:i.constructor)===DocumentFragment)t=i;else if((i==null?void 0:i.constructor)===String){let r=document.createElement("template");r.innerHTML=i,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let s=()=>{t&&(e&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){e=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=s,this.shadowRoot.prepend(r)}else s()}addTemplateProcessor(i){this.tplProcessors.add(i)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Q.generate(),this.style.setProperty(_.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(_.CSS_CTX_PROP,!0)}get ctxName(){var i;let e=((i=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:i.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=e,e}get localCtx(){return this.__localCtx||(this.__localCtx=b.registerCtx({},this)),this.__localCtx}get nodeCtx(){return b.getCtx(this.ctxName,!1)||b.registerCtx({},this.ctxName)}static __parseProp(i,e){let t,s;if(i.startsWith(_.EXT_DATA_CTX_PRFX))t=e.nodeCtx,s=i.replace(_.EXT_DATA_CTX_PRFX,"");else if(i.includes(_.NAMED_DATA_CTX_SPLTR)){let r=i.split(_.NAMED_DATA_CTX_SPLTR);t=b.getCtx(r[0]),s=r[1]}else t=e.localCtx,s=i;return{ctx:t,name:s}}sub(i,e,t=!0){let s=n=>{!this.isConnected||e(n)},r=V.__parseProp(i,this);r.ctx.has(i)?this.allSubs.add(r.ctx.sub(r.name,s,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,s,t))})}notify(i){let e=V.__parseProp(i,this);e.ctx.notify(e.name)}has(i){let e=V.__parseProp(i,this);return e.ctx.has(e.name)}add(i,e,t=!1){let s=V.__parseProp(i,this);s.ctx.add(s.name,e,t)}add$(i,e=!1){for(let t in i)this.add(t,i[t],e)}get $(){if(!this.__stateProxy){let i=Object.create(null);this.__stateProxy=new Proxy(i,{set:(e,t,s)=>{let r=V.__parseProp(t,this);return r.ctx.pub(r.name,s),!0},get:(e,t)=>{let s=V.__parseProp(t,this);return s.ctx.read(s.name)}})}return this.__stateProxy}set$(i,e=!1){for(let t in i){let s=i[t];e||![String,Number,Boolean].includes(s==null?void 0:s.constructor)?this.$[t]=s:this.$[t]!==s&&(this.$[t]=s)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(_.CTX_OWNER_ATTR)&&this.getAttribute(_.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let i=this.constructor.__attrDesc;if(i)for(let e of Object.values(i))Object.keys(this.init$).includes(e)||(this.init$[e]="");for(let e in this.init$)if(e.startsWith(_.EXT_DATA_CTX_PRFX))this.nodeCtx.add(e.replace(_.EXT_DATA_CTX_PRFX,""),this.init$[e],this.__ctxOwner);else if(e.includes(_.NAMED_DATA_CTX_SPLTR)){let t=e.split(_.NAMED_DATA_CTX_SPLTR),s=t[0].trim(),r=t[1].trim();if(s&&r){let n=b.getCtx(s,!1);n||(n=b.registerCtx({},s)),n.add(r,this.init$[e])}}else this.localCtx.add(e,this.init$[e]);for(let e in this.cssInit$)this.bindCssData(e,this.cssInit$[e]);this.__dataCtxInitialized=!0}connectedCallback(){var i;if(!!this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let e=(i=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:i.trim();if(e&&this.style.setProperty(_.CSS_CTX_PROP,`'${e}'`),this.__initDataCtx(),this[_.SET_LATER_KEY]){for(let t in this[_.SET_LATER_KEY])Jt(this,t,this[_.SET_LATER_KEY][t]);delete this[_.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Be)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${_.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(_.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){!this.connectedOnce||(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let i of this.allSubs)i.remove(),this.allSubs.delete(i);for(let i of this.tplProcessors)this.tplProcessors.delete(i);M==null||M.delete(this.updateCssData),M!=null&&M.size||(H==null||H.disconnect(),H=null,M=null)},100)))}static reg(i,e=!1){if(i||(Yt++,i=`${_.AUTO_TAG_PRFX}-${Yt}`),this.__tag=i,window.customElements.get(i)){console.warn(`${i} - is already in "customElements" registry`);return}window.customElements.define(i,e?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(i){this.observedAttributes=Object.keys(i),this.__attrDesc=i}attributeChangedCallback(i,e,t){var s;if(e===t)return;let r=(s=this.constructor.__attrDesc)==null?void 0:s[i];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[i]=t}getCssData(i,e=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(i)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(i).trim();t=Xe(t);try{this.__cssDataCache[i]=JSON.parse(t)}catch{!e&&console.warn(`CSS Data error: ${i}`),this.__cssDataCache[i]=null}}return this.__cssDataCache[i]}__extractCssName(i){return i.split("--").map((e,t)=>t===0?"":e).join("--")}__initStyleAttrObserver(){M||(M=new Set),M.add(this.updateCssData),H||(H=new MutationObserver(i=>{i[0].type==="attributes"&&M.forEach(e=>{e()})}),H.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(i,e=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(i);let t=this.getCssData(this.__extractCssName(i),!0);t===null&&(t=e),this.add(i,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(i,e,t){let s="__"+i;this[s]=this[i],Object.defineProperty(this,i,{set:r=>{this[s]=r,t?window.setTimeout(()=>{e==null||e(r)}):e==null||e(r)},get:()=>this[s]}),this[i]=this[s]}static set shadowStyles(i){let e=new Blob([i],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(e)}static set rootStyles(i){if(!this.__rootStylesLink){let e=new Blob([i],{type:"text/css"}),t=URL.createObjectURL(e),s=document.createElement("link");s.href=t,s.rel="stylesheet",this.__rootStylesLink=s}}},xt=V;At(xt,"template");var wt=class{static _print(i){console.warn(i)}static setDefaultTitle(i){this.defaultTitle=i}static setRoutingMap(i){Object.assign(this.appMap,i);for(let e in this.appMap)!this.defaultRoute&&this.appMap[e].default===!0?this.defaultRoute=e:!this.errorRoute&&this.appMap[e].error===!0&&(this.errorRoute=e)}static set routingEventName(i){this.__routingEventName=i}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let i={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))i.route=t.replace("?","");else if(t.includes("=")){let s=t.split("=");i.options[s[0]]=decodeURI(s[1])}else i.options[t]=!0}),i}static notify(){let i=this.readAddressBar(),e=this.appMap[i.route];if(e&&e.title&&(document.title=e.title),i.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!e&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!e&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!e){this._print(`Route "${i.route}" not found...`);return}let t=new CustomEvent(wt.routingEventName,{detail:{route:i.route,options:Object.assign(e||{},i.options)}});window.dispatchEvent(t)}static reflect(i,e={}){let t=this.appMap[i];if(!t){this._print("Wrong route: "+i);return}let s="?"+i;for(let n in e)e[n]===!0?s+=this.separator+n:s+=this.separator+n+`=${e[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,s),document.title=r}static applyRoute(i,e={}){this.reflect(i,e),this.notify()}static setSeparator(i){this._separator=i}static get separator(){return this._separator||"&"}static createRouterData(i,e){this.setRoutingMap(e);let t=b.registerCtx({route:null,options:null,title:null},i);return window.addEventListener(this.routingEventName,s=>{var r;t.multiPub({route:s.detail.route,options:s.detail.options,title:((r=s.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),wt.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};wt.appMap=Object.create(null);var Zt="idb-store-ready",Ge="symbiote-db",We="symbiote-idb-update_",qe=class{_notifyWhenReady(i=null){window.dispatchEvent(new CustomEvent(Zt,{detail:{dbName:this.name,storeName:this.storeName,event:i}}))}get _updEventName(){return We+this.name}_getUpdateEvent(i){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:i}})}_notifySubscribers(i){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,i),window.dispatchEvent(this._getUpdateEvent(i))}constructor(i,e){this.name=i,this.storeName=e,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(e,{keyPath:"_key"}),this.objStore.transaction.oncomplete=s=>{this._notifyWhenReady(s)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(i){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(i);return new Promise((s,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?s(n.target.result._value):(s(null),console.warn(`IDB: cannot read "${i}"`))},t.onerror=n=>{r(n)}})}write(i,e,t=!1){let s={_key:i,_value:e},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(s);return new Promise((o,a)=>{n.onsuccess=l=>{t||this._notifySubscribers(i),o(l.target.result)},n.onerror=l=>{a(l)}})}delete(i,e=!1){let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(i);return new Promise((r,n)=>{s.onsuccess=o=>{e||this._notifySubscribers(i),r(o)},s.onerror=o=>{n(o)}})}getAll(){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,s)=>{e.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},e.onerror=r=>{s(r)}})}subscribe(i,e){this._subscriptionsMap[i]||(this._subscriptionsMap[i]=new Set);let t=this._subscriptionsMap[i];return t.add(e),{remove:()=>{t.delete(e),t.size||delete this._subscriptionsMap[i]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Qt.clear(this.name)}},Qt=class{static get readyEventName(){return Zt}static open(i=Ge,e="store"){let t=i+"/"+e;return this._reg[t]||(this._reg[t]=new qe(i,e)),this._reg[t]}static clear(i){window.indexedDB.deleteDatabase(i);for(let e in this._reg)e.split("/")[0]===i&&delete this._reg[e]}};At(Qt,"_reg",Object.create(null));var Ye=i=>i;function St(i,e,t={}){var o;let{openToken:s="{{",closeToken:r="}}",transform:n=Ye}=t;for(let a in e){let l=(o=e[a])==null?void 0:o.toString();i=i.replaceAll(s+a+r,typeof l=="string"?n(l):l)}return i}function te(i,e){[...i.querySelectorAll("[l10n]")].forEach(t=>{let s=t.getAttribute("l10n"),r="textContent";if(s.includes(":")){let o=s.split(":");r=o[0],s=o[1]}let n="l10n:"+s;e.__l10nKeys.push(n),e.add(n,s),e.sub(n,o=>{t[r]=e.l10n(o)}),t.removeAttribute("l10n")})}var Rt=()=>({"*ctxTargetsRegistry":new Map}),Ut=()=>({...Rt(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*activityCaption":"","*activityIcon":""}),ht=()=>({...Ut(),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null});function N(i,e){let t,s=(...r)=>{clearTimeout(t),t=setTimeout(()=>i(...r),e)};return s.cancel=()=>{clearTimeout(t)},s}var Ke="--uploadcare-blocks-window-height",dt="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function It(){return typeof window[dt]=="undefined"?!1:!!window[dt]}function ee(){if(It())return;let i=()=>{document.documentElement.style.setProperty(Ke,`${window.innerHeight}px`),window[dt]=!0},e=N(i,100);return window.addEventListener("resize",e,{passive:!0}),i(),()=>{window[dt]=!1,window.removeEventListener("resize",e)}}var ie="lr-",D=class extends xt{constructor(){super();d(this,"allowCustomTemplate",!0);d(this,"ctxInit",Rt());d(this,"init$",this.ctxInit);this.activityType=null,this.addTemplateProcessor(te),this.__l10nKeys=[]}l10n(t,s={}){let r=this.getCssData("--l10n-"+t,!0)||t;return St(r,s)}applyL10nKey(t,s){let r="l10n:"+t;this.$[r]=s,this.__l10nKeys.push(t)}checkCtxTarget(t){let s=this.$["*ctxTargetsRegistry"];return s==null?void 0:s.has(t)}setForCtxTarget(t,s,r){this.checkCtxTarget(t)&&(this.$[s]=r)}connectedCallback(){if(It()||(this._destroyInnerHeightTracker=ee()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.isConnected&&this.__ctxOwner){let t=b.getCtx(this.ctxName,!1);t&&(t.store={...this.ctxInit})}super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){let t=this.constructor.is,s=this.$["*ctxTargetsRegistry"],r=s.has(t)?s.get(t)+1:1;s.set(t,r),this.$["*ctxTargetsRegistry"]=s}destroyCallback(){let t=this.constructor.is,s=this.$["*ctxTargetsRegistry"],r=s.has(s)?s.get(t)-1:0;r===0?s.delete(t):s.set(t,r),this.$["*ctxTargetsRegistry"]=s}fileSizeFmt(t,s=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,a=s<0?0:s,l=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**l).toFixed(a))+" "+n(r[l])}proxyUrl(t){let s=this.getCssData("--cfg-secure-delivery-proxy",!0);return s?St(s,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(ie)?t:ie+t)}};var Je="css-src",pt=class extends D{constructor(){super(...arguments);d(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback();let t=this.getAttribute(Je);if(t){this.renderShadow=!0,this.attachShadow({mode:"open"});let s=document.createElement("link");s.rel="stylesheet",s.type="text/css",s.href=t,s.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.shadowReadyCallback()})})},this.shadowRoot.appendChild(s)}else this.render(),this.shadowReadyCallback()}};var ft=class extends pt{constructor(){super(...arguments);d(this,"ctxInit",ht());d(this,"ctxOwner",!0)}};var se="active",tt="___ACTIVITY_IS_ACTIVE___",X=class extends D{constructor(){super(...arguments);d(this,"ctxInit",Ut());d(this,"_debouncedHistoryFlush",N(this._historyFlush.bind(this),10))}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{var n,o;let s=this.ctxName+this.activityType,r=X._activityRegistry[s];this.activityType!==t&&this[tt]?(this[tt]=!1,this.removeAttribute(se),(n=r==null?void 0:r.deactivateCallback)==null||n.call(r)):this.activityType===t&&!this[tt]&&(this[tt]=!0,this.setAttribute(se,""),this.setForCtxTarget("lr-modal","*modalCloseCallback",r==null?void 0:r.modalCloseCallback),(o=r==null?void 0:r.activateCallback)==null||o.call(r),this._debouncedHistoryFlush()),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),t.push(this.activityType),this.$["*history"]=t)}get isActivityActive(){return this[tt]}registerActivity(t,s){let{onActivate:r,onDeactivate:n,onClose:o}=s;X._activityRegistry||(X._activityRegistry=Object.create(null));let a=this.ctxName+t;X._activityRegistry[a]={activateCallback:r,deactivateCallback:n,modalCloseCallback:o}}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){t.pop();let s=t.pop();this.$["*currentActivity"]=s,this.$["*history"]=t}}},y=X;d(y,"_activityRegistry",Object.create(null));y.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var et=class extends ft{constructor(){super(...arguments);d(this,"pauseRender",!0);d(this,"init$",{...this.ctxInit,selectClicked:()=>{this.ref.uBlock.openSystemDialog()}})}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",s=>{s||(this.$["*currentActivity"]=t.initActivity||y.activities.START_FROM)}),this.sub("*uploadList",s=>{(s==null?void 0:s.length)===0&&(this.$["*currentActivity"]=t.initActivity||y.activities.START_FROM)})}};et.template=`<lr-start-from><lr-drop-area clickable l10n="drop-files-here"></lr-drop-area></lr-start-from><lr-upload-list ref="uBlock"></lr-upload-list><lr-message-box></lr-message-box>`;var mt=class extends y{constructor(){super(...arguments);d(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.add$({"*activityCaption":this.l10n("select-file-source"),"*activityIcon":"default"},!0)}})}};var it=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],_t=i=>i?i.map(e=>e==null?void 0:e.split(",")).flat().filter(e=>typeof e=="string"&&e).map(e=>e.trim()):[],Ot=(i,e)=>e.some(t=>t.endsWith("*")?(t=t.replace("*",""),i.startsWith(t)):i===t),gt=i=>{let e=i==null?void 0:i.type;return e?Ot(e,it):!1};var A=class extends Error{constructor(e,t,s,r,n){super(),this.name="UploadClientError",this.message=e,this.code=t,this.request=s,this.response=r,this.headers=n,Object.setPrototypeOf(this,A.prototype)}},Mt=(i="Request canceled")=>{let e=new A(i);return e.isCancel=!0,e},bt=(i,e)=>{i&&(i.aborted?Promise.resolve().then(e):i.addEventListener("abort",()=>e(),{once:!0}))},B=({method:i,url:e,data:t,headers:s={},signal:r,onProgress:n})=>new Promise((o,a)=>{let l=new XMLHttpRequest,c=(i==null?void 0:i.toUpperCase())||"GET",u=!1;l.open(c,e,!0),s&&Object.entries(s).forEach(h=>{let[p,m]=h;typeof m!="undefined"&&!Array.isArray(m)&&l.setRequestHeader(p,m)}),l.responseType="text",bt(r,()=>{u=!0,l.abort(),a(Mt())}),l.onload=()=>{if(l.status!=200)a(new Error(`Error ${l.status}: ${l.statusText}`));else{let h={method:c,url:e,data:t,headers:s||void 0,signal:r,onProgress:n},p=l.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function(v){let S=v.split(": "),f=S.shift(),C=S.join(": ");f&&typeof f!="undefined"&&(m[f]=C)});let g=l.response,E=l.status;o({request:h,data:g,headers:m,status:E})}},l.onerror=()=>{u||a(new Error("Network error"))},n&&typeof n=="function"&&(l.upload.onprogress=h=>{h.lengthComputable?n({isComputable:!0,value:h.loaded/h.total}):n({isComputable:!1})}),t?l.send(t):l.send()});function Ze(i){return i}var Qe=({name:i})=>i?[i]:[],ti=Ze,ei=()=>new FormData,yt=i=>i!==void 0&&(typeof Blob!="undefined"&&i instanceof Blob||typeof File!="undefined"&&i instanceof File||typeof Buffer!="undefined"&&i instanceof Buffer),ii=i=>{let e="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(e);return!yt(i)&&t.test(i)},si=i=>{let e="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(e);return!yt(i)&&t.test(i)},ri=i=>typeof i=="string"||typeof i=="number"||typeof i=="undefined",ni=i=>!!i&&typeof i=="object"&&!Array.isArray(i),oi=i=>!!i&&typeof i=="object"&&"data"in i&&yt(i.data);function ai(i,e,t){if(oi(t)){let{name:s,contentType:r}=t,n=ti(t.data),o=Qe({name:s,contentType:r});i.push([e,n,...o])}else if(ni(t))for(let[s,r]of Object.entries(t))typeof r!="undefined"&&i.push([`${e}[${s}]`,String(r)]);else ri(t)&&t&&i.push([e,t.toString()])}function li(i){let e=[];for(let[t,s]of Object.entries(i))ai(e,t,s);return e}function Nt(i){let e=ei(),t=li(i);for(let s of t){let[r,n,...o]=s;e.append(r,n,...o)}return e}var ci=i=>{let e=new URLSearchParams;for(let[t,s]of Object.entries(i))s&&typeof s=="object"&&!Array.isArray(s)?Object.entries(s).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>e.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(s)?s.forEach(r=>{e.append(`${t}[]`,r)}):typeof s=="string"&&s?e.set(t,s):typeof s=="number"&&e.set(t,s.toString());return e.toString()},G=(i,e,t)=>{let s=new URL(i);return s.pathname=(s.pathname+e).replace("//","/"),t&&(s.search=ci(t)),s.toString()},T={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,multipartMaxAttempts:3,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},ui="application/octet-stream",oe="original",hi="4.3.1";function re(i){return Object.prototype.toString.call(i)==="[object Object]"}var di=/\W|_/g;function pi(i){return i.split(di).map((e,t)=>e.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+e.slice(1)).join("")}function ne(i,{ignoreKeys:e}={ignoreKeys:[]}){return Array.isArray(i)?i.map(t=>F(t,{ignoreKeys:e})):i}function F(i,{ignoreKeys:e}={ignoreKeys:[]}){if(Array.isArray(i))return ne(i,{ignoreKeys:e});if(!re(i))return i;let t={};for(let s of Object.keys(i)){let r=i[s];if(e.includes(s)){t[s]=r;continue}re(r)?r=F(r,{ignoreKeys:e}):Array.isArray(r)&&(r=ne(r,{ignoreKeys:e})),t[pi(s)]=r}return t}var fi=i=>new Promise(e=>setTimeout(e,i));function Vt({libraryName:i,libraryVersion:e,userAgent:t,publicKey:s="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:s,libraryName:i,libraryVersion:e,languageName:n,integration:r});let o=[i,e,s].filter(Boolean).join("/"),a=[n,r].filter(Boolean).join("; ");return`${o} (${a})`}var mi={factor:2,time:100};function ae(i,e=mi){let t=0;function s(r){let n=Math.round(e.time*e.factor**t);return r({attempt:t,retry:a=>fi(a!=null?a:n).then(()=>(t+=1,s(r)))})}return s(i)}var _i="UploadcareUploadClient",gi=hi;function W(i){return Vt({libraryName:_i,libraryVersion:gi,...i})}var bi="RequestThrottledError",yi=15e3;function Ci(i){let{headers:e}=i||{};return e&&Number.parseInt(e["x-throttle-wait-seconds"])*1e3||yi}function q(i,e){return ae(({attempt:t,retry:s})=>i().catch(r=>{if("response"in r&&(r==null?void 0:r.code)===bi&&t<e)return s(Ci(r));throw r}))}function $t(i){return typeof i=="undefined"?"auto":i?"1":"0"}function vi(i,{publicKey:e,fileName:t,contentType:s,baseURL:r=T.baseURL,secureSignature:n,secureExpire:o,store:a,signal:l,onProgress:c,source:u="local",integration:h,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,metadata:g}){return q(()=>{var E;return B({method:"POST",url:G(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":W({publicKey:e,integration:h,userAgent:p})},data:Nt({file:{data:i,name:(E=t!=null?t:i.name)!=null?E:oe,contentType:s},UPLOADCARE_PUB_KEY:e,UPLOADCARE_STORE:$t(a),signature:n,expire:o,source:u,metadata:g}),signal:l,onProgress:c}).then(({data:v,headers:S,request:f})=>{let C=F(JSON.parse(v));if("error"in C)throw new A(C.error.content,C.error.errorCode,f,C,S);return C})},m)}var kt;(function(i){i.Token="token",i.FileInfo="file_info"})(kt||(kt={}));function Ti(i,{publicKey:e,baseURL:t=T.baseURL,store:s,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:l,source:c="url",signal:u,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,metadata:g}){return q(()=>B({method:"POST",headers:{"X-UC-User-Agent":W({publicKey:e,integration:h,userAgent:p})},url:G(t,"/from_url/",{jsonerrors:1,pub_key:e,source_url:i,store:$t(s),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:a,expire:l,source:c,metadata:g}),signal:u}).then(({data:E,headers:v,request:S})=>{let f=F(JSON.parse(E));if("error"in f)throw new A(f.error.content,f.error.errorCode,S,f,v);return f}),m)}var U;(function(i){i.Unknown="unknown",i.Waiting="waiting",i.Progress="progress",i.Error="error",i.Success="success"})(U||(U={}));var Ei=i=>"status"in i&&i.status===U.Error;function wi(i,{publicKey:e,baseURL:t=T.baseURL,signal:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=T.retryThrottledRequestMaxTimes}={}){return q(()=>B({method:"GET",headers:e?{"X-UC-User-Agent":W({publicKey:e,integration:r,userAgent:n})}:void 0,url:G(t,"/from_url/status/",{jsonerrors:1,token:i}),signal:s}).then(({data:a,headers:l,request:c})=>{let u=F(JSON.parse(a));if("error"in u&&!Ei(u))throw new A(u.error.content,void 0,c,u,l);return u}),o)}function le(i,{publicKey:e,baseURL:t=T.baseURL,signal:s,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=T.retryThrottledRequestMaxTimes}){return q(()=>B({method:"GET",headers:{"X-UC-User-Agent":W({publicKey:e,integration:n,userAgent:o})},url:G(t,"/info/",{jsonerrors:1,pub_key:e,file_id:i,source:r}),signal:s}).then(({data:l,headers:c,request:u})=>{let h=F(JSON.parse(l));if("error"in h)throw new A(h.error.content,h.error.errorCode,u,h,c);return h}),a)}function Ai(i,{publicKey:e,contentType:t,fileName:s,multipartChunkSize:r=T.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:a,store:l,signal:c,source:u="local",integration:h,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,metadata:g}){return q(()=>B({method:"POST",url:G(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":W({publicKey:e,integration:h,userAgent:p})},data:Nt({filename:s!=null?s:oe,size:i,content_type:t!=null?t:ui,part_size:r,UPLOADCARE_STORE:$t(l),UPLOADCARE_PUB_KEY:e,signature:o,expire:a,source:u,metadata:g}),signal:c}).then(({data:E,headers:v,request:S})=>{let f=F(JSON.parse(E));if("error"in f)throw new A(f.error.content,f.error.errorCode,S,f,v);return f.parts=Object.keys(f.parts).map(C=>f.parts[C]),f}),m)}function xi(i,e,{signal:t,onProgress:s}){return B({method:"PUT",url:e,data:i,onProgress:s,signal:t}).then(r=>(s&&s({isComputable:!0,value:1}),r)).then(({status:r})=>({code:r}))}function Si(i,{publicKey:e,baseURL:t=T.baseURL,source:s="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=T.retryThrottledRequestMaxTimes}){return q(()=>B({method:"POST",url:G(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":W({publicKey:e,integration:n,userAgent:o})},data:Nt({uuid:i,UPLOADCARE_PUB_KEY:e,source:s}),signal:r}).then(({data:l,headers:c,request:u})=>{let h=F(JSON.parse(l));if("error"in h)throw new A(h.error.content,h.error.errorCode,u,h,c);return h}),a)}var $=class{constructor(e,{baseCDN:t,fileName:s}){this.name=null,this.size=null,this.isStored=null,this.isImage=null,this.mimeType=null,this.cdnUrl=null,this.s3Url=null,this.originalFilename=null,this.imageInfo=null,this.videoInfo=null,this.contentInfo=null,this.metadata=null,this.s3Bucket=null;let{uuid:r,s3Bucket:n}=e,o=`${t}/${r}/`,a=n?`https://${n}.s3.amazonaws.com/${r}/${e.filename}`:null;this.uuid=r,this.name=s||e.filename,this.size=e.size,this.isStored=e.isStored,this.isImage=e.isImage,this.mimeType=e.mimeType,this.cdnUrl=o,this.originalFilename=e.originalFilename,this.imageInfo=e.imageInfo,this.videoInfo=e.videoInfo,this.contentInfo=e.contentInfo,this.metadata=e.metadata||null,this.s3Bucket=n||null,this.s3Url=a}},Ri=500,ce=({check:i,interval:e=Ri,signal:t})=>new Promise((s,r)=>{let n;bt(t,()=>{n&&clearTimeout(n),r(Mt("Poll cancelled"))});let o=()=>{try{Promise.resolve(i(t)).then(a=>{a?s(a):n=setTimeout(o,e)}).catch(a=>r(a))}catch(a){r(a)}};n=setTimeout(o,0)});function Ft({file:i,publicKey:e,baseURL:t,source:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,signal:a,onProgress:l}){return ce({check:c=>le(i,{publicKey:e,baseURL:t,signal:c,source:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o}).then(u=>u.isReady?u:(l&&l({isComputable:!0,value:1}),!1)),signal:a})}var Ui=(i,{publicKey:e,fileName:t,baseURL:s,secureSignature:r,secureExpire:n,store:o,contentType:a,signal:l,onProgress:c,source:u,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,baseCDN:g,metadata:E})=>vi(i,{publicKey:e,fileName:t,contentType:a,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:c,source:u,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,metadata:E}).then(({file:v})=>Ft({file:v,publicKey:e,baseURL:s,source:u,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,onProgress:c,signal:l})).then(v=>new $(v,{baseCDN:g})),Ii=(i,{signal:e}={})=>{let t=null,s=null,r=i.map(()=>new AbortController),n=o=>()=>{s=o,r.forEach((a,l)=>l!==o&&a.abort())};return bt(e,()=>{r.forEach(o=>o.abort())}),Promise.all(i.map((o,a)=>{let l=n(a);return Promise.resolve().then(()=>o({stopRace:l,signal:r[a].signal})).then(c=>(l(),c)).catch(c=>(t=c,null))})).then(o=>{if(s===null)throw t;return o[s]})},Oi=window.WebSocket,Lt=class{constructor(){this.events=Object.create({})}emit(e,t){var s;(s=this.events[e])==null||s.forEach(r=>r(t))}on(e,t){this.events[e]=this.events[e]||[],this.events[e].push(t)}off(e,t){t?this.events[e]=this.events[e].filter(s=>s!==t):this.events[e]=[]}},Di=(i,e)=>i==="success"?{status:U.Success,...e}:i==="progress"?{status:U.Progress,...e}:{status:U.Error,...e},Pt=class{constructor(e,t=3e4){this.ws=void 0,this.queue=[],this.isConnected=!1,this.subscribers=0,this.emmitter=new Lt,this.disconnectTimeoutId=null,this.key=e,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let e=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Oi(e),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let s=JSON.parse(t.data.toString());switch(s.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(s.channel,Di(s.event,JSON.parse(s.data)))}})}}disconnect(){let e=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{e()},this.disconnectTime):e()}send(e,t){var r;let s=JSON.stringify({event:e,data:t});(r=this.ws)==null||r.send(s)}subscribe(e,t){this.subscribers+=1,this.connect();let s=`task-status-${e}`,r={event:"pusher:subscribe",data:{channel:s}};this.emmitter.on(s,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(e){this.subscribers-=1;let t=`task-status-${e}`,s={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(s.event,s.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(e){return this.emmitter.on("error",e),()=>this.emmitter.off("error",e)}},Dt=null,Bt=i=>{if(!Dt){let e=typeof window=="undefined"?0:3e4;Dt=new Pt(i,e)}return Dt},ki=i=>{Bt(i).connect()};function Li({token:i,publicKey:e,baseURL:t,integration:s,userAgent:r,retryThrottledRequestMaxTimes:n,onProgress:o,signal:a}){return ce({check:l=>wi(i,{publicKey:e,baseURL:t,integration:s,userAgent:r,retryThrottledRequestMaxTimes:n,signal:l}).then(c=>{switch(c.status){case U.Error:return new A(c.error,c.errorCode);case U.Waiting:return!1;case U.Unknown:return new A(`Token "${i}" was not found.`);case U.Progress:return o&&(c.total==="unknown"?o({isComputable:!1}):o({isComputable:!0,value:c.done/c.total})),!1;case U.Success:return o&&o({isComputable:!0,value:c.done/c.total}),c;default:throw new Error("Unknown status")}}),signal:a})}var Pi=({token:i,pusherKey:e,signal:t,onProgress:s})=>new Promise((r,n)=>{let o=Bt(e),a=o.onError(n),l=()=>{a(),o.unsubscribe(i)};bt(t,()=>{l(),n(Mt("pusher cancelled"))}),o.subscribe(i,c=>{switch(c.status){case U.Progress:{s&&(c.total==="unknown"?s({isComputable:!1}):s({isComputable:!0,value:c.done/c.total}));break}case U.Success:{l(),s&&s({isComputable:!0,value:c.done/c.total}),r(c);break}case U.Error:l(),n(new A(c.msg,c.error_code))}})}),Mi=(i,{publicKey:e,fileName:t,baseURL:s,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:l,store:c,signal:u,onProgress:h,source:p,integration:m,userAgent:g,retryThrottledRequestMaxTimes:E,pusherKey:v=T.pusherKey,metadata:S})=>Promise.resolve(ki(v)).then(()=>Ti(i,{publicKey:e,fileName:t,baseURL:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:l,store:c,signal:u,source:p,integration:m,userAgent:g,retryThrottledRequestMaxTimes:E,metadata:S})).catch(f=>{let C=Bt(v);return C==null||C.disconnect(),Promise.reject(f)}).then(f=>f.type===kt.FileInfo?f:Ii([({signal:C})=>Li({token:f.token,publicKey:e,baseURL:s,integration:m,userAgent:g,retryThrottledRequestMaxTimes:E,onProgress:h,signal:C}),({signal:C})=>Pi({token:f.token,pusherKey:v,signal:C,onProgress:h})],{signal:u})).then(f=>{if(f instanceof A)throw f;return f}).then(f=>Ft({file:f.uuid,publicKey:e,baseURL:s,integration:m,userAgent:g,retryThrottledRequestMaxTimes:E,onProgress:h,signal:u})).then(f=>new $(f,{baseCDN:r})),Ni=(i,{publicKey:e,fileName:t,baseURL:s,signal:r,onProgress:n,source:o,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,baseCDN:u})=>le(i,{publicKey:e,baseURL:s,signal:r,source:o,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c}).then(h=>new $(h,{baseCDN:u,fileName:t})).then(h=>(n&&n({isComputable:!0,value:1}),h)),ue=i=>i.length||i.size,Vi=(i,e=T.multipartMinFileSize)=>i>=e,$i=(i,e,t,s)=>{let r=s*e,n=Math.min(r+s,t);return i.slice(r,n)};function Fi(i,e,t){return s=>$i(i,s,e,t)}var Bi=(i,e)=>new Promise((t,s)=>{let r=[],n=!1,o=e.length,a=[...e],l=()=>{let c=e.length-a.length,u=a.shift();u&&u().then(h=>{n||(r[c]=h,o-=1,o?l():t(r))}).catch(h=>{n=!0,s(h)})};for(let c=0;c<i;c++)l()}),ji=(i,e,{publicKey:t,onProgress:s,signal:r,integration:n,multipartMaxAttempts:o})=>ae(({attempt:a,retry:l})=>xi(i,e,{publicKey:t,onProgress:s,signal:r,integration:n}).catch(c=>{if(a<o)return l();throw c})),zi=(i,{publicKey:e,fileName:t,fileSize:s,baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:l,onProgress:c,source:u,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,contentType:g,multipartChunkSize:E=T.multipartChunkSize,maxConcurrentRequests:v=T.maxConcurrentRequests,multipartMaxAttempts:S=T.multipartMaxAttempts,baseCDN:f,metadata:C})=>{let at=s||ue(i),j,J=(R,lt)=>{if(!c)return;j||(j=Array(R).fill(0));let Et=z=>z.reduce((ct,xe)=>ct+xe,0);return z=>{!z.isComputable||(j[lt]=z.value,c({isComputable:!0,value:Et(j)/R}))}};return Ai(at,{publicKey:e,contentType:g,fileName:t!=null?t:i.name,baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:l,source:u,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,metadata:C}).then(({uuid:R,parts:lt})=>{let Et=Fi(i,at,E);return Promise.all([R,Bi(v,lt.map((z,ct)=>()=>ji(Et(ct),z,{publicKey:e,onProgress:J(lt.length,ct),signal:l,integration:h,multipartMaxAttempts:S})))])}).then(([R])=>Si(R,{publicKey:e,baseURL:r,source:u,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m})).then(R=>R.isReady?R:Ft({file:R.uuid,publicKey:e,baseURL:r,source:u,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,onProgress:c,signal:l})).then(R=>new $(R,{baseCDN:f}))};function he(i,{publicKey:e,fileName:t,baseURL:s=T.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:l,source:c,integration:u,userAgent:h,retryThrottledRequestMaxTimes:p,contentType:m,multipartMinFileSize:g,multipartChunkSize:E,multipartMaxAttempts:v,maxConcurrentRequests:S,baseCDN:f=T.baseCDN,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:at,pusherKey:j,metadata:J}){if(yt(i)){let R=ue(i);return Vi(R,g)?zi(i,{publicKey:e,contentType:m,multipartChunkSize:E,multipartMaxAttempts:v,fileName:t,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:l,source:c,integration:u,userAgent:h,maxConcurrentRequests:S,retryThrottledRequestMaxTimes:p,baseCDN:f,metadata:J}):Ui(i,{publicKey:e,fileName:t,contentType:m,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:l,source:c,integration:u,userAgent:h,retryThrottledRequestMaxTimes:p,baseCDN:f,metadata:J})}if(si(i))return Mi(i,{publicKey:e,fileName:t,baseURL:s,baseCDN:f,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:at,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:l,source:c,integration:u,userAgent:h,retryThrottledRequestMaxTimes:p,pusherKey:j,metadata:J});if(ii(i))return Ni(i,{publicKey:e,fileName:t,baseURL:s,signal:a,onProgress:l,source:c,integration:u,userAgent:h,retryThrottledRequestMaxTimes:p,baseCDN:f});throw new TypeError(`File uploading from "${i}" is not supported`)}var de=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null},fileSize:{type:Number,value:null},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:$,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0}});var pe="blocks",fe="0.14.2";function me(i){return Vt({...i,libraryName:pe,libraryVersion:fe})}var _e="[Typed State] Wrong property name: ",Hi="[Typed State] Wrong property type: ",Ct=class{constructor(e,t){this.__typedSchema=e,this.__ctxId=t||Q.generate(),this.__schema=Object.keys(e).reduce((s,r)=>(s[r]=e[r].value,s),{}),this.__data=b.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(e,t){if(!this.__typedSchema.hasOwnProperty(e)){console.warn(_e+e);return}let s=this.__typedSchema[e];if((t==null?void 0:t.constructor)===s.type||t instanceof s.type||s.nullable&&t===null){this.__data.pub(e,t);return}console.warn(Hi+e)}setMultipleValues(e){for(let t in e)this.setValue(t,e[t])}getValue(e){if(!this.__typedSchema.hasOwnProperty(e)){console.warn(_e+e);return}return this.__data.read(e)}subscribe(e,t){return this.__data.sub(e,t)}remove(){b.deleteCtx(this.__ctxId)}};var vt=class{constructor(e){this.__typedSchema=e.typedSchema,this.__ctxId=e.ctxName||Q.generate(),this.__data=b.registerCtx({},this.__ctxId),this.__watchList=e.watchList||[],this.__handler=e.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(s,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[s]||(t[s]=new Set),t[s].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var s;let e=this.__added,t=this.__removed;this.__added.clear(),this.__removed.clear(),(s=this.__handler)==null||s.call(this,[...this.__items],e,t)})}add(e){let t=new Ct(this.__typedSchema);for(let s in e)t.setValue(s,e[s]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(s=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(s,()=>{this.__notifyObservers(s,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(e){return this.__data.read(e)}readProp(e,t){return this.read(e).getValue(t)}publishProp(e,t,s){this.read(e).setValue(t,s)}remove(e){this.__removed.add(this.__data.read(e)),this.__items.delete(e),this.notify(),this.__data.pub(e,null),delete this.__subsMap[e]}clearAll(){this.__items.forEach(e=>{this.remove(e)})}observe(e){this.__observers.add(e)}unobserve(e){this