UNPKG

@uploadcare/file-uploader

Version:

Building blocks for Uploadcare products integration

29 lines 303 kB
/** * @license * MIT License * * Copyright (c) 2025 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 On=Object.defineProperty;var kn=Object.getPrototypeOf;var $n=Reflect.get;var Mn=(r,t,e)=>t in r?On(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var u=(r,t,e)=>Mn(r,typeof t!="symbol"?t+"":t,e);var Z=(r,t,e)=>$n(kn(r),e,t);var Ln=Object.defineProperty,Un=(r,t,e)=>t in r?Ln(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,or=(r,t,e)=>(Un(r,typeof t!="symbol"?t+"":t,e),e);function Pn(r){let t=e=>{var i;for(let s in e)((i=e[s])==null?void 0:i.constructor)===Object&&(e[s]=t(e[s]));return{...e}};return t(r)}var T=class{constructor(r){r.constructor===Object?this.store=Pn(r):(this._storeIsProxy=!0,this.store=r),this.callbackMap=Object.create(null)}static warn(r,t){console.warn(`Symbiote Data: cannot ${r}. Prop name: `+t)}read(r){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(T.warn("read",r),null):this.store[r]}has(r){return this._storeIsProxy?this.store[r]!==void 0:this.store.hasOwnProperty(r)}add(r,t,e=!1){!e&&Object.keys(this.store).includes(r)||(this.store[r]=t,this.notify(r))}pub(r,t){if(!this._storeIsProxy&&!this.store.hasOwnProperty(r)){T.warn("publish",r);return}this.store[r]=t,this.notify(r)}multiPub(r){for(let t in r)this.pub(t,r[t])}notify(r){this.callbackMap[r]&&this.callbackMap[r].forEach(t=>{t(this.store[r])})}sub(r,t,e=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(T.warn("subscribe",r),null):(this.callbackMap[r]||(this.callbackMap[r]=new Set),this.callbackMap[r].add(t),e&&t(this.store[r]),{remove:()=>{this.callbackMap[r].delete(t),this.callbackMap[r].size||delete this.callbackMap[r]},callback:t})}static registerCtx(r,t=Symbol()){let e=T.globalStore.get(t);return e?console.warn('State: context UID "'+t+'" already in use'):(e=new T(r),T.globalStore.set(t,e)),e}static deleteCtx(r){T.globalStore.delete(r)}static getCtx(r,t=!0){return T.globalStore.get(r)||(t&&console.warn('State: wrong context UID - "'+r+'"'),null)}};T.globalStore=new Map;var x=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"}),bs="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Rn=bs.length-1,Te=class{static generate(r="XXXXXXXXX-XXX"){let t="";for(let e=0;e<r.length;e++)t+=r[e]==="-"?r[e]:bs.charAt(Math.random()*Rn);return t}};function _s(r,t,e){let i=!0,s,o=t.split(".");return o.forEach((n,a)=>{a<o.length-1?r=r[n]:s=n}),r?r[s]=e:i=!1,i}function Dn(r){return r.split("-").map((t,e)=>t&&e?t[0].toUpperCase()+t.slice(1):t).join("").split("_").map((t,e)=>t&&e?t.toUpperCase():t).join("")}function Fn(r,t){[...r.querySelectorAll(`[${x.REPEAT_ATTR}]`)].forEach(e=>{let i=e.getAttribute(x.REPEAT_ITEM_TAG_ATTR),s;if(i&&(s=window.customElements.get(i)),!s){s=class extends t.BaseComponent{constructor(){super(),i||(this.style.display="contents")}};let n=e.innerHTML;s.template=n,s.reg(i)}for(;e.firstChild;)e.firstChild.remove();let o=e.getAttribute(x.REPEAT_ATTR);t.sub(o,n=>{if(!n){for(;e.firstChild;)e.firstChild.remove();return}let a=[...e.children],l,c=h=>{h.forEach((p,f)=>{if(a[f])if(a[f].set$)setTimeout(()=>{a[f].set$(p)});else for(let m in p)a[f][m]=p[m];else{l||(l=new DocumentFragment);let m=new s;Object.assign(m.init$,p),l.appendChild(m)}}),l&&e.appendChild(l);let d=a.slice(h.length,a.length);for(let p of d)p.remove()};if(n.constructor===Array)c(n);else if(n.constructor===Object){let h=[];for(let d in n){let p=n[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),h.push(p)}c(h)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),e.removeAttribute(x.REPEAT_ATTR),e.removeAttribute(x.REPEAT_ITEM_TAG_ATTR)})}var ms="__default__";function Vn(r,t){if(t.shadowRoot)return;let e=[...r.querySelectorAll("slot")];if(!e.length)return;let i={};e.forEach(s=>{let o=s.getAttribute("name")||ms;i[o]={slot:s,fr:document.createDocumentFragment()}}),t.initChildren.forEach(s=>{var o;let n=ms;s instanceof Element&&s.hasAttribute("slot")&&(n=s.getAttribute("slot"),s.removeAttribute("slot")),(o=i[n])==null||o.fr.appendChild(s)}),Object.values(i).forEach(s=>{if(s.fr.childNodes.length)s.slot.parentNode.replaceChild(s.fr,s.slot);else if(s.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...s.slot.childNodes),s.slot.parentNode.replaceChild(o,s.slot)}else s.slot.remove()})}function Nn(r,t){[...r.querySelectorAll(`[${x.EL_REF_ATTR}]`)].forEach(e=>{let i=e.getAttribute(x.EL_REF_ATTR);t.ref[i]=e,e.removeAttribute(x.EL_REF_ATTR)})}function Bn(r,t){[...r.querySelectorAll(`[${x.BIND_ATTR}]`)].forEach(e=>{let s=e.getAttribute(x.BIND_ATTR).split(";");[...e.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=Dn(o.name.replace("-",""));s.push(n+":"+o.value),e.removeAttribute(o.name)}}),s.forEach(o=>{if(!o)return;let n=o.split(":").map(h=>h.trim()),a=n[0],l;a.indexOf(x.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(x.ATTR_BIND_PRFX,""));let c=n[1].split(",").map(h=>h.trim());for(let h of c){let d;h.startsWith("!!")?(d="double",h=h.replace("!!","")):h.startsWith("!")&&(d="single",h=h.replace("!","")),t.sub(h,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),l?(p==null?void 0:p.constructor)===Boolean?p?e.setAttribute(a,""):e.removeAttribute(a):e.setAttribute(a,p):_s(e,a,p)||(e[x.SET_LATER_KEY]||(e[x.SET_LATER_KEY]=Object.create(null)),e[x.SET_LATER_KEY][a]=p)})}}),e.removeAttribute(x.BIND_ATTR)})}var qt="{{",dt="}}",zn="skip-text";function Hn(r){let t,e=[],i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var o;return!((o=s.parentElement)!=null&&o.hasAttribute(zn))&&s.textContent.includes(qt)&&s.textContent.includes(dt)&&1}});for(;t=i.nextNode();)e.push(t);return e}var jn=function(r,t){Hn(r).forEach(i=>{let s=[],o;for(;i.textContent.includes(dt);)i.textContent.startsWith(qt)?(o=i.textContent.indexOf(dt)+dt.length,i.splitText(o),s.push(i)):(o=i.textContent.indexOf(qt),i.splitText(o)),i=i.nextSibling;s.forEach(n=>{let a=n.textContent.replace(qt,"").replace(dt,"");n.textContent="",t.sub(a,l=>{n.textContent=l})})})},Gn=[Fn,Vn,Nn,Bn,jn],Xt="'",qe='"',Wn=/\\([0-9a-fA-F]{1,6} ?)/g;function qn(r){return(r[0]===qe||r[0]===Xt)&&(r[r.length-1]===qe||r[r.length-1]===Xt)}function Xn(r){return(r[0]===qe||r[0]===Xt)&&(r=r.slice(1)),(r[r.length-1]===qe||r[r.length-1]===Xt)&&(r=r.slice(0,-1)),r}function Kn(r){let t="",e="";for(var i=0;i<r.length;i++){let s=r[i+1];r[i]==="\\"&&s==='"'?(t+='\\"',i++):r[i]==='"'&&e!=="\\"?t+='\\"':t+=r[i],e=r[i]}return t}function Zn(r){let t=r;qn(r)&&(t=Xn(t),t=t.replace(Wn,(e,i)=>String.fromCodePoint(parseInt(i.trim(),16))),t=t.replaceAll(`\\ `,"\\n"),t=Kn(t),t=qe+t+qe);try{return JSON.parse(t)}catch{throw new Error(`Failed to parse CSS property value: ${t}. Original input: ${r}`)}}var gs=0,We=null,be=null,xe=class extends HTMLElement{constructor(){super(),or(this,"updateCssData",()=>{var r;this.dropCssDataCache(),(r=this.__boundCssProps)==null||r.forEach(t=>{let e=this.getCssData(this.__extractCssName(t),!0);e!==null&&this.$[t]!==e&&(this.$[t]=e)})}),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 xe}initCallback(){}__initCallback(){var r;this.__initialized||(this.__initialized=!0,(r=this.initCallback)==null||r.call(this))}render(r,t=this.renderShadow){let e;if((t||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(x.USE_TPL);if(s){let o=this.getRootNode(),n=(o==null?void 0:o.querySelector(s))||document.querySelector(s);n?r=n.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(this,this);if(r||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(r==null?void 0:r.constructor)===DocumentFragment)e=r;else if((r==null?void 0:r.constructor)===String){let s=document.createElement("template");s.innerHTML=r,e=s.content.cloneNode(!0)}else this.constructor.__tpl&&(e=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(e,this)}let i=()=>{e&&(t&&this.shadowRoot.appendChild(e)||this.appendChild(e)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){t=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=i,this.shadowRoot.prepend(s)}else i()}addTemplateProcessor(r){this.tplProcessors.add(r)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Te.generate(),this.style.setProperty(x.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(x.CSS_CTX_PROP,!0)}get ctxName(){var r;let t=((r=this.getAttribute(x.CTX_NAME_ATTR))==null?void 0:r.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=t,t}get localCtx(){return this.__localCtx||(this.__localCtx=T.registerCtx({},this)),this.__localCtx}get nodeCtx(){return T.getCtx(this.ctxName,!1)||T.registerCtx({},this.ctxName)}static __parseProp(r,t){let e,i;if(r.startsWith(x.EXT_DATA_CTX_PRFX))e=t.nodeCtx,i=r.replace(x.EXT_DATA_CTX_PRFX,"");else if(r.includes(x.NAMED_DATA_CTX_SPLTR)){let s=r.split(x.NAMED_DATA_CTX_SPLTR);e=T.getCtx(s[0]),i=s[1]}else e=t.localCtx,i=r;return{ctx:e,name:i}}sub(r,t,e=!0){let i=o=>{this.isConnected&&t(o)},s=xe.__parseProp(r,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,i,e)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,i,e))})}notify(r){let t=xe.__parseProp(r,this);t.ctx.notify(t.name)}has(r){let t=xe.__parseProp(r,this);return t.ctx.has(t.name)}add(r,t,e=!1){let i=xe.__parseProp(r,this);i.ctx.add(i.name,t,e)}add$(r,t=!1){for(let e in r)this.add(e,r[e],t)}get $(){if(!this.__stateProxy){let r=Object.create(null);this.__stateProxy=new Proxy(r,{set:(t,e,i)=>{let s=xe.__parseProp(e,this);return s.ctx.pub(s.name,i),!0},get:(t,e)=>{let i=xe.__parseProp(e,this);return i.ctx.read(i.name)}})}return this.__stateProxy}set$(r,t=!1){for(let e in r){let i=r[e];t||![String,Number,Boolean].includes(i==null?void 0:i.constructor)?this.$[e]=i:this.$[e]!==i&&(this.$[e]=i)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(x.CTX_OWNER_ATTR)&&this.getAttribute(x.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let r=this.constructor.__attrDesc;if(r)for(let t of Object.values(r))Object.keys(this.init$).includes(t)||(this.init$[t]="");for(let t in this.init$)if(t.startsWith(x.EXT_DATA_CTX_PRFX))this.nodeCtx.add(t.replace(x.EXT_DATA_CTX_PRFX,""),this.init$[t],this.__ctxOwner);else if(t.includes(x.NAMED_DATA_CTX_SPLTR)){let e=t.split(x.NAMED_DATA_CTX_SPLTR),i=e[0].trim(),s=e[1].trim();if(i&&s){let o=T.getCtx(i,!1);o||(o=T.registerCtx({},i)),o.add(s,this.init$[t])}}else this.localCtx.add(t,this.init$[t]);for(let t in this.cssInit$)this.bindCssData(t,this.cssInit$[t]);this.__dataCtxInitialized=!0}connectedCallback(){var r;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let t=(r=this.getAttribute(x.CTX_NAME_ATTR))==null?void 0:r.trim();if(t&&this.style.setProperty(x.CSS_CTX_PROP,`'${t}'`),this.__initDataCtx(),this[x.SET_LATER_KEY]){for(let e in this[x.SET_LATER_KEY])_s(this,e,this[x.SET_LATER_KEY][e]);delete this[x.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let e of Gn)this.addTemplateProcessor(e);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let e=this.getRootNode();if(!e)return;if(e==null?void 0:e.querySelector(`link[${x.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(x.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},e.nodeType===Node.DOCUMENT_NODE?e.head.appendChild(s):e.prepend(s)}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 r of this.allSubs)r.remove(),this.allSubs.delete(r);for(let r of this.tplProcessors)this.tplProcessors.delete(r);be==null||be.delete(this.updateCssData),be!=null&&be.size||(We==null||We.disconnect(),We=null,be=null)},100)))}static reg(r,t=!1){r||(gs++,r=`${x.AUTO_TAG_PRFX}-${gs}`),this.__tag=r;let e=window.customElements.get(r);if(e){!t&&e!==this&&console.warn([`Element with tag name "${r}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(r,t?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(r){this.observedAttributes=Object.keys(r),this.__attrDesc=r}attributeChangedCallback(r,t,e){var i;if(t===e)return;let s=(i=this.constructor.__attrDesc)==null?void 0:i[r];s?this.__dataCtxInitialized?this.$[s]=e:this.init$[s]=e:this[r]=e}getCssData(r,t=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(r)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let e=this.__computedStyle.getPropertyValue(r).trim();try{this.__cssDataCache[r]=Zn(e)}catch{!t&&console.warn(`CSS Data error: ${r}`),this.__cssDataCache[r]=null}}return this.__cssDataCache[r]}__extractCssName(r){return r.split("--").map((t,e)=>e===0?"":t).join("--")}__initStyleAttrObserver(){be||(be=new Set),be.add(this.updateCssData),We||(We=new MutationObserver(r=>{r[0].type==="attributes"&&be.forEach(t=>{t()})}),We.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(r,t=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(r);let e=this.getCssData(this.__extractCssName(r),!0);e===null&&(e=t),this.add(r,e),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(r,t,e){let i="__"+r;this[i]=this[r],Object.defineProperty(this,r,{set:s=>{this[i]=s,e?window.setTimeout(()=>{t==null||t(s)}):t==null||t(s)},get:()=>this[i]}),this[r]=this[i]}static set shadowStyles(r){let t=new Blob([r],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(t)}static set rootStyles(r){if(!this.__rootStylesLink){let t=new Blob([r],{type:"text/css"}),e=URL.createObjectURL(t),i=document.createElement("link");i.href=e,i.rel="stylesheet",this.__rootStylesLink=i}}},Se=xe;or(Se,"template");var sr=class{static _print(r){console.warn(r)}static setDefaultTitle(r){this.defaultTitle=r}static setRoutingMap(r){Object.assign(this.appMap,r);for(let t in this.appMap)!this.defaultRoute&&this.appMap[t].default===!0?this.defaultRoute=t:!this.errorRoute&&this.appMap[t].error===!0&&(this.errorRoute=t)}static set routingEventName(r){this.__routingEventName=r}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let r={route:null,options:{}};return window.location.search.split(this.separator).forEach(e=>{if(e.includes("?"))r.route=e.replace("?","");else if(e.includes("=")){let i=e.split("=");r.options[i[0]]=decodeURI(i[1])}else r.options[e]=!0}),r}static notify(){let r=this.readAddressBar(),t=this.appMap[r.route];if(t&&t.title&&(document.title=t.title),r.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!t&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!t&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!t){this._print(`Route "${r.route}" not found...`);return}let e=new CustomEvent(sr.routingEventName,{detail:{route:r.route,options:Object.assign(t||{},r.options)}});window.dispatchEvent(e)}static reflect(r,t={}){let e=this.appMap[r];if(!e){this._print("Wrong route: "+r);return}let i="?"+r;for(let o in t)t[o]===!0?i+=this.separator+o:i+=this.separator+o+`=${t[o]}`;let s=e.title||this.defaultTitle||"";window.history.pushState(null,s,i),document.title=s}static applyRoute(r,t={}){this.reflect(r,t),this.notify()}static setSeparator(r){this._separator=r}static get separator(){return this._separator||"&"}static createRouterData(r,t){this.setRoutingMap(t);let e=T.registerCtx({route:null,options:null,title:null},r);return window.addEventListener(this.routingEventName,i=>{var s;e.multiPub({route:i.detail.route,options:i.detail.options,title:((s=i.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),sr.notify(),this.initPopstateListener(),e}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};sr.appMap=Object.create(null);function ht(r,t){for(let e in t)e.includes("-")?r.style.setProperty(e,t[e]):r.style[e]=t[e]}function Yn(r,t){for(let e in t)t[e].constructor===Boolean?t[e]?r.setAttribute(e,""):r.removeAttribute(e):r.setAttribute(e,t[e])}function nr(r={tag:"div"}){let t=document.createElement(r.tag);if(r.attributes&&Yn(t,r.attributes),r.styles&&ht(t,r.styles),r.properties)for(let e in r.properties)t[e]=r.properties[e];return r.processors&&r.processors.forEach(e=>{e(t)}),r.children&&r.children.forEach(e=>{let i=nr(e);t.appendChild(i)}),t}var vs="idb-store-ready",Qn="symbiote-db",Jn="symbiote-idb-update_",ea=class{_notifyWhenReady(r=null){window.dispatchEvent(new CustomEvent(vs,{detail:{dbName:this.name,storeName:this.storeName,event:r}}))}get _updEventName(){return Jn+this.name}_getUpdateEvent(r){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:r}})}_notifySubscribers(r){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,r),window.dispatchEvent(this._getUpdateEvent(r))}constructor(r,t){this.name=r,this.storeName=t,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=e=>{this.db=e.target.result,this.objStore=this.db.createObjectStore(t,{keyPath:"_key"}),this.objStore.transaction.oncomplete=i=>{this._notifyWhenReady(i)}},this.request.onsuccess=e=>{this.db=e.target.result,this._notifyWhenReady(e)},this.request.onerror=e=>{console.error(e)},this._subscriptionsMap={},this._updateHandler=e=>{e.key===this.name&&this._subscriptionsMap[e.newValue]&&this._subscriptionsMap[e.newValue].forEach(async s=>{s(await this.read(e.newValue))})},this._localUpdateHandler=e=>{this._updateHandler(e.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(r){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(r);return new Promise((i,s)=>{e.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?i(o.target.result._value):(i(null),console.warn(`IDB: cannot read "${r}"`))},e.onerror=o=>{s(o)}})}write(r,t,e=!1){let i={_key:r,_value:t},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(i);return new Promise((n,a)=>{o.onsuccess=l=>{e||this._notifySubscribers(r),n(l.target.result)},o.onerror=l=>{a(l)}})}delete(r,t=!1){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(r);return new Promise((s,o)=>{i.onsuccess=n=>{t||this._notifySubscribers(r),s(n)},i.onerror=n=>{o(n)}})}getAll(){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((e,i)=>{t.onsuccess=s=>{let o=s.target.result;e(o.map(n=>n._value))},t.onerror=s=>{i(s)}})}subscribe(r,t){this._subscriptionsMap[r]||(this._subscriptionsMap[r]=new Set);let e=this._subscriptionsMap[r];return e.add(t),{remove:()=>{e.delete(t),e.size||delete this._subscriptionsMap[r]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,ys.clear(this.name)}},ys=class{static get readyEventName(){return vs}static open(r=Qn,t="store"){let e=r+"/"+t;return this._reg[e]||(this._reg[e]=new ea(r,t)),this._reg[e]}static clear(r){window.indexedDB.deleteDatabase(r);for(let t in this._reg)t.split("/")[0]===r&&delete this._reg[t]}};or(ys,"_reg",Object.create(null));var ws=r=>{if(typeof r!="string"||!r)return"";let t=r.trim();return t.startsWith("-/")?t=t.slice(2):t.startsWith("/")&&(t=t.slice(1)),t.endsWith("/")&&(t=t.slice(0,t.length-1)),t},Kt=(...r)=>r.filter(t=>typeof t=="string"&&t).map(t=>ws(t)).join("/-/"),H=(...r)=>{let t=Kt(...r);return t?`-/${t}/`:""};function Zt(r){let t=new URL(r),e=t.pathname+t.search+t.hash,i=e.lastIndexOf("http"),s=e.lastIndexOf("/"),o="";return i>=0?o=e.slice(i):s>=0&&(o=e.slice(s+1)),o}function Yt(r){let t=new URL(r),{pathname:e}=t,i=e.indexOf("/"),s=e.indexOf("/",i+1);return e.substring(i+1,s)}function ar(r){let t=Cs(r),e=new URL(t),i=e.pathname.indexOf("/-/");return i===-1?"":e.pathname.substring(i).slice(1)}function lr(r){return ar(r).split("/-/").filter(Boolean).map(e=>ws(e))}function Cs(r){let t=new URL(r),e=Zt(r),i=Es(e)?As(e).pathname:e;return t.pathname=t.pathname.replace(i,""),t.search="",t.hash="",t.toString()}function Es(r){return r.startsWith("http")}function As(r){let t=new URL(r);return{pathname:t.origin+t.pathname||"",search:t.search||"",hash:t.hash||""}}var R=(r,t,e)=>{let i=new URL(Cs(r));if(e=e||Zt(r),i.pathname.startsWith("//")&&(i.pathname=i.pathname.replace("//","/")),Es(e)){let s=As(e);i.pathname=i.pathname+(t||"")+(s.pathname||""),i.search=s.search,i.hash=s.hash}else i.pathname=i.pathname+(t||"")+(e||"");return i.toString()},Ie=(r,t)=>{let e=new URL(r);return e.pathname=t+"/",e.toString()};var D=(r,t=",")=>r.trim().split(t).map(e=>e.trim()).filter(e=>e.length>0);var ee=Object.freeze({brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0,mirror:!1,flip:!1,crop:void 0}),Ts=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function ta(r,t){if(typeof t=="number"){let e=t;return ee[r]!==e?`${r}/${e}`:""}if(typeof t=="boolean"){let e=t;return ee[r]!==e?`${r}`:""}if(r==="filter"&&t){let{name:e,amount:i}=t;return ee.filter===i?"":`${r}/${e}/${i}`}if(r==="crop"&&t){let{dimensions:e,coords:i}=t;return`${r}/${e.join("x")}/${i.join(",")}`}return""}function Oe(r){return Kt(...Ts.filter(t=>typeof r[t]!="undefined"&&r[t]!==null).map(t=>{let e=r[t];return ta(t,e)}).filter(t=>!!t))}var Qt=Kt("format/auto","progressive/yes"),_e=([r])=>typeof r!="undefined"?Number(r):void 0,xs=()=>!0,ia=([r,t])=>({name:r,amount:typeof t!="undefined"?Number(t):100}),ra=([r,t])=>{if(!/\d+x\d+/.test(r)||!/\d+,\d+/.test(t))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:D(r,"x").map(Number),coords:D(t).map(Number)}},sa=Object.freeze({enhance:_e,brightness:_e,exposure:_e,gamma:_e,contrast:_e,saturation:_e,vibrance:_e,warmth:_e,filter:ia,mirror:xs,flip:xs,rotate:_e,crop:ra});function cr(r){let t={};for(let e of r){let[i,...s]=e.split("/");if(!Ts.includes(i))continue;let o=i,n=sa[o];try{let a=n(s);t[o]=a}catch(a){console.warn([`Failed to parse URL operation "${e}". It will be ignored.`,a instanceof Error?`Error message: "${a.message}"`:a,"If you need this functionality, please feel free to open an issue at https://github.com/uploadcare/blocks/issues/new"].join(` `))}}return t}var M=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),Y=[M.CROP,M.TUNING,M.FILTERS],Ss=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],Is=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],Os=["rotate","mirror","flip"],le=Object.freeze({brightness:{zero:ee.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:ee.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:ee.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:ee.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:ee.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:ee.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:ee.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:ee.enhance,range:[0,100],keypointsNumber:1},filter:{zero:ee.filter,range:[0,100],keypointsNumber:1}});var Q=r=>r?r.split(",").map(t=>t.trim()).filter(Boolean):[],ve=r=>r?r.join(","):"";var pt="https://ucarecdn.com",oa="https://upload.uploadcare.com",na="https://social.uploadcare.com",aa="https://ucarecd.net",te=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",externalSourcesEmbedCss:"",store:"auto",cameraMirror:!1,cameraCapture:"",sourceList:"local, url, camera, dropbox, gdrive",topLevelOrigin:"",cloudImageEditorTabs:ve(Y),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:pt,cdnCnamePrefixed:aa,baseUrl:oa,socialBaseUrl:na,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:10,retryNetworkErrorMaxTimes:3,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",debug:!1,metadata:null,localeName:"en",localeDefinitionOverride:null,secureUploadsExpireThreshold:10*60*1e3,secureUploadsSignatureResolver:null,secureDeliveryProxyUrlResolver:null,iconHrefResolver:null,fileValidators:[],collectionValidators:[],validationTimeout:15*1e3,validationConcurrency:100,cameraModes:"photo, video",defaultCameraMode:null,enableAudioRecording:!0,enableVideoRecording:null,maxVideoRecordingDuration:null,mediaRecorderOptions:null,filesViewMode:"list",gridShowFileNames:!1,cloudImageEditorAutoOpen:!1,cloudImageEditorMaskHref:null,testMode:!1,qualityInsights:!0});var ye=Object.freeze({INIT_SOLUTION:"init-solution",CHANGE_CONFIG:"change-config"}),w=Object.freeze({FILE_ADDED:"file-added",FILE_REMOVED:"file-removed",FILE_UPLOAD_START:"file-upload-start",FILE_UPLOAD_PROGRESS:"file-upload-progress",FILE_UPLOAD_SUCCESS:"file-upload-success",FILE_UPLOAD_FAILED:"file-upload-failed",FILE_URL_CHANGED:"file-url-changed",MODAL_OPEN:"modal-open",MODAL_CLOSE:"modal-close",DONE_CLICK:"done-click",UPLOAD_CLICK:"upload-click",ACTIVITY_CHANGE:"activity-change",COMMON_UPLOAD_START:"common-upload-start",COMMON_UPLOAD_PROGRESS:"common-upload-progress",COMMON_UPLOAD_SUCCESS:"common-upload-success",COMMON_UPLOAD_FAILED:"common-upload-failed",CHANGE:"change",GROUP_CREATED:"group-created",...ye}),Jt=class{constructor(t){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);u(this,"_debugPrint",null);this._debugPrint=t}bindTarget(t){this._targets.add(t)}unbindTarget(t){this._targets.delete(t)}_dispatch(t,e){var i;for(let s of this._targets)s.dispatchEvent(new CustomEvent(t,{detail:e}));(i=this._debugPrint)==null||i.call(this,()=>{let s=e&&typeof e=="object"?{...e}:e;return[`event "${t}"`,s]})}emit(t,e,{debounce:i}={}){if(typeof i!="number"&&!i){this._dispatch(t,typeof e=="function"?e():e);return}this._timeoutStore.has(t)&&window.clearTimeout(this._timeoutStore.get(t));let s=typeof i=="number"?i:20,o=window.setTimeout(()=>{this._dispatch(t,typeof e=="function"?e():e),this._timeoutStore.delete(t)},s);this._timeoutStore.set(t,o)}};function $(r,t){let e,i=(...s)=>{clearTimeout(e),e=setTimeout(()=>r(...s),t)};return i.cancel=()=>{clearTimeout(e)},i}var ks="--uploadcare-blocks-window-height",Ve=class{static registerClient(t){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(t)}static unregisterClient(t){this.clientsRegistry.delete(t),this.clientsRegistry.size===0&&this.detachTracker()}static attachTracker(){window.addEventListener("resize",this.flush,{passive:!0,capture:!0}),this.flush()}static detachTracker(){window.removeEventListener("resize",this.flush,{capture:!0}),document.documentElement.style.removeProperty(ks)}};u(Ve,"clientsRegistry",new Set),u(Ve,"flush",$(()=>{document.documentElement.style.setProperty(ks,`${window.innerHeight}px`)},100));var $s=r=>{var i;let t=new Intl.Locale(r),e="ltr";return typeof t.getTextInfo=="function"&&t.getTextInfo().direction?e=t.getTextInfo().direction:"textInfo"in t&&((i=t.textInfo)!=null&&i.direction)&&(e=t.textInfo.direction),e};var ei=(r,t)=>new Intl.PluralRules(r).select(t);var la=r=>r,ur="{{",Ls="}}",Ms="plural:";function ft(r,t,e={}){var n;let{openToken:i=ur,closeToken:s=Ls,transform:o=la}=e;for(let a in t){let l=(n=t[a])==null?void 0:n.toString();r=r.replaceAll(i+a+s,typeof l=="string"?o(l):l)}return r}function Us(r){let t=[],e=r.indexOf(ur);for(;e!==-1;){let i=r.indexOf(Ls,e),s=r.substring(e+2,i);if(s.startsWith(Ms)){let o=r.substring(e+2,i).replace(Ms,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));t.push({variable:s,pluralKey:n,countVariable:a})}e=r.indexOf(ur,i)}return t}var Ps=({element:r,attribute:t,onSuccess:e,onTimeout:i,timeout:s=300})=>{let o=r.getAttribute(t);if(o!==null){e(o);return}let n=new MutationObserver(c=>{let h=c[c.length-1];l(h)});n.observe(r,{attributes:!0,attributeFilter:[t]});let a=setTimeout(()=>{n.disconnect(),i()},s),l=c=>{let h=r.getAttribute(t);c.type==="attributes"&&c.attributeName===t&&h!==null&&(clearTimeout(a),n.disconnect(),e(h))}};function Rs(r){return Object.prototype.toString.call(r)==="[object Object]"}var ca=/\W|_/g;function ua(r){return r.split(ca).map((t,e)=>t.charAt(0)[e>0?"toUpperCase":"toLowerCase"]()+t.slice(1)).join("")}function Ds(r,{ignoreKeys:t}={ignoreKeys:[]}){return Array.isArray(r)?r.map(e=>Ee(e,{ignoreKeys:t})):r}function Ee(r,{ignoreKeys:t}={ignoreKeys:[]}){if(Array.isArray(r))return Ds(r,{ignoreKeys:t});if(!Rs(r))return r;let e={};for(let i of Object.keys(r)){let s=r[i];if(t.includes(i)){e[i]=s;continue}Rs(s)?s=Ee(s,{ignoreKeys:t}):Array.isArray(s)&&(s=Ds(s,{ignoreKeys:t})),e[ua(i)]=s}return e}var da=r=>new Promise(t=>setTimeout(t,r));function br({libraryName:r,libraryVersion:t,userAgent:e,publicKey:i="",integration:s=""}){let o="JavaScript";if(typeof e=="string")return e;if(typeof e=="function")return e({publicKey:i,libraryName:r,libraryVersion:t,languageName:o,integration:s});let n=[r,t,i].filter(Boolean).join("/"),a=[o,s].filter(Boolean).join("; ");return`${n} (${a})`}var ha={factor:2,time:100};function pa(r,t=ha){let e=0;function i(s){let o=Math.round(t.time*t.factor**e);return s({attempt:e,retry:a=>da(a!=null?a:o).then(()=>(e+=1,i(s)))})}return i(r)}var Ne=class extends Error{},Xe=class r extends Ne{constructor(e){super();u(this,"originalProgressEvent");this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,r.prototype),this.originalProgressEvent=e}},ti=(r,t)=>{r&&(r.aborted?Promise.resolve().then(t):r.addEventListener("abort",()=>t(),{once:!0}))},ke=class r extends Ne{constructor(e="Request canceled"){super(e);u(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,r.prototype)}},fa=500,Vs=({check:r,interval:t=fa,timeout:e,signal:i})=>new Promise((s,o)=>{let n,a;ti(i,()=>{n&&clearTimeout(n),o(new ke("Poll cancelled"))}),e&&(a=setTimeout(()=>{n&&clearTimeout(n),o(new ke("Timed out"))},e));let l=()=>{try{Promise.resolve(r(i)).then(c=>{c?(a&&clearTimeout(a),s(c)):n=setTimeout(l,t)}).catch(c=>{a&&clearTimeout(a),o(c)})}catch(c){a&&clearTimeout(a),o(c)}};n=setTimeout(l,0)}),I={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},ii="application/octet-stream",Ns="original",Me=({method:r,url:t,data:e,headers:i={},signal:s,onProgress:o})=>new Promise((n,a)=>{let l=new XMLHttpRequest,c=(r==null?void 0:r.toUpperCase())||"GET",h=!1;l.open(c,t,!0),i&&Object.entries(i).forEach(d=>{let[p,f]=d;typeof f!="undefined"&&!Array.isArray(f)&&l.setRequestHeader(p,f)}),l.responseType="text",ti(s,()=>{h=!0,l.abort(),a(new ke)}),l.onload=()=>{if(l.status!=200)a(new Error(`Error ${l.status}: ${l.statusText}`));else{let d={method:c,url:t,data:e,headers:i||void 0,signal:s,onProgress:o},p=l.getAllResponseHeaders().trim().split(/[\r\n]+/),f={};p.forEach(function(_){let v=_.split(": "),E=v.shift(),C=v.join(": ");E&&typeof E!="undefined"&&(f[E]=C)});let m=l.response,b=l.status;n({request:d,data:m,headers:f,status:b})}},l.onerror=d=>{h||a(new Xe(d))},o&&typeof o=="function"&&(l.upload.onprogress=d=>{d.lengthComputable?o({isComputable:!0,value:d.loaded/d.total}):o({isComputable:!1})}),e?l.send(e):l.send()});function ma(r,...t){return r}var ga=({name:r})=>r?[r]:[],ba=ma,_a=()=>new FormData,Bs=r=>!1,ri=r=>typeof Blob!="undefined"&&r instanceof Blob,si=r=>typeof File!="undefined"&&r instanceof File,oi=r=>!!r&&typeof r=="object"&&!Array.isArray(r)&&"uri"in r&&typeof r.uri=="string",Ke=r=>ri(r)||si(r)||Bs()||oi(r),va=r=>typeof r=="string"||typeof r=="number"||typeof r=="undefined",ya=r=>!!r&&typeof r=="object"&&!Array.isArray(r),wa=r=>!!r&&typeof r=="object"&&"data"in r&&Ke(r.data);function zs(r,t,e){if(Array.isArray(e))for(let i of e)zs(r,`${t}[]`,i);else if(wa(e)){let{name:i,contentType:s}=e,o=ba(e.data,i,s!=null?s:ii),n=ga({name:i,contentType:s});r.push([t,o,...n])}else if(ya(e))for(let[i,s]of Object.entries(e))typeof s!="undefined"&&r.push([`${t}[${i}]`,String(s)]);else va(e)&&e&&r.push([t,e.toString()])}function Ca(r){let t=[];for(let[e,i]of Object.entries(r))zs(t,e,i);return t}function ni(r){let t=_a(),e=Ca(r);for(let i of e){let[s,o,...n]=i;t.append(s,o,...n)}return t}var j=class r extends Ne{constructor(e,i,s,o,n){super();u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadError",this.message=e,this.code=i,this.request=s,this.response=o,this.headers=n,Object.setPrototypeOf(this,r.prototype)}},Ea=r=>{let t=new URLSearchParams;for(let[e,i]of Object.entries(r))i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).filter(s=>{var o;return(o=s[1])!=null?o:!1}).forEach(s=>t.set(`${e}[${s[0]}]`,String(s[1]))):Array.isArray(i)?i.forEach(s=>{t.append(`${e}[]`,s)}):typeof i=="string"&&i?t.set(e,i):typeof i=="number"&&t.set(e,i.toString());return t.toString()},we=(r,t,e)=>{let i=new URL(r);return i.pathname=(i.pathname+t).replace("//","/"),e&&(i.search=Ea(e)),i.toString()},Aa="6.18.0",xa="UploadcareUploadClient",Ta=Aa;function Be(r){return br({libraryName:xa,libraryVersion:Ta,...r})}var Sa="RequestThrottledError",Fs=15e3,Ia=1e3;function Oa(r){let{headers:t}=r||{};if(!t||typeof t["retry-after"]!="string")return Fs;let e=parseInt(t["retry-after"],10);return Number.isFinite(e)?e*1e3:Fs}function Le(r,t){let{retryThrottledRequestMaxTimes:e,retryNetworkErrorMaxTimes:i}=t;return pa(({attempt:s,retry:o})=>r().catch(n=>{if("response"in n&&(n==null?void 0:n.code)===Sa&&s<e)return o(Oa(n));if(n instanceof Xe&&s<i)return o((s+1)*Ia);throw n}))}var Hs=r=>{let t="";return(ri(r)||si(r)||oi(r))&&(t=r.type),t||ii},js=r=>{let t="";return si(r)&&r.name?t=r.name:ri(r)||Bs()?t="":oi(r)&&r.name&&(t=r.name),t||Ns};function _r(r){return typeof r=="undefined"||r==="auto"?"auto":r?"1":"0"}function ka(r,{publicKey:t,fileName:e,contentType:i,baseURL:s=I.baseURL,secureSignature:o,secureExpire:n,store:a,signal:l,onProgress:c,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=I.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=I.retryNetworkErrorMaxTimes,metadata:b}){return Le(()=>Me({method:"POST",url:we(s,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Be({publicKey:t,integration:d,userAgent:p})},data:ni({file:{data:r,name:e||js(r),contentType:i||Hs(r)},UPLOADCARE_PUB_KEY:t,UPLOADCARE_STORE:_r(a),signature:o,expire:n,source:h,metadata:b}),signal:l,onProgress:c}).then(({data:_,headers:v,request:E})=>{let C=Ee(JSON.parse(_));if("error"in C)throw new j(C.error.content,C.error.errorCode,E,C,v);return C}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var pr;(function(r){r.Token="token",r.FileInfo="file_info"})(pr||(pr={}));function $a(r,{publicKey:t,baseURL:e=I.baseURL,store:i,fileName:s,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,source:c="url",signal:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=I.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=I.retryNetworkErrorMaxTimes,metadata:b}){return Le(()=>Me({method:"POST",headers:{"X-UC-User-Agent":Be({publicKey:t,integration:d,userAgent:p})},url:we(e,"/from_url/",{jsonerrors:1,pub_key:t,source_url:r,store:_r(i),filename:s,check_URL_duplicates:o?1:void 0,save_URL_duplicates:n?1:void 0,signature:a,expire:l,source:c,metadata:b}),signal:h}).then(({data:_,headers:v,request:E})=>{let C=Ee(JSON.parse(_));if("error"in C)throw new j(C.error.content,C.error.errorCode,E,C,v);return C}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var J;(function(r){r.Unknown="unknown",r.Waiting="waiting",r.Progress="progress",r.Error="error",r.Success="success"})(J||(J={}));var Ma=r=>"status"in r&&r.status===J.Error;function La(r,{publicKey:t,baseURL:e=I.baseURL,signal:i,integration:s,userAgent:o,retryThrottledRequestMaxTimes:n=I.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=I.retryNetworkErrorMaxTimes}={}){return Le(()=>Me({method:"GET",headers:t?{"X-UC-User-Agent":Be({publicKey:t,integration:s,userAgent:o})}:void 0,url:we(e,"/from_url/status/",{jsonerrors:1,token:r}),signal:i}).then(({data:l,headers:c,request:h})=>{let d=Ee(JSON.parse(l));if("error"in d&&!Ma(d))throw new j(d.error.content,d.error.errorCode,h,d,c);return d}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:n})}function Ua(r,{publicKey:t,baseURL:e=I.baseURL,jsonpCallback:i,secureSignature:s,secureExpire:o,signal:n,source:a,integration:l,userAgent:c,retryThrottledRequestMaxTimes:h=I.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=I.retryNetworkErrorMaxTimes}){return Le(()=>Me({method:"POST",headers:{"X-UC-User-Agent":Be({publicKey:t,integration:l,userAgent:c})},url:we(e,"/group/",{jsonerrors:1}),data:ni({files:r,callback:i,pub_key:t,signature:s,expire:o,source:a}),signal:n}).then(({data:p,headers:f,request:m})=>{let b=Ee(JSON.parse(p));if("error"in b)throw new j(b.error.content,b.error.errorCode,m,b,f);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function Gs(r,{publicKey:t,baseURL:e=I.baseURL,signal:i,source:s,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=I.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=I.retryNetworkErrorMaxTimes}){return Le(()=>Me({method:"GET",headers:{"X-UC-User-Agent":Be({publicKey:t,integration:o,userAgent:n})},url:we(e,"/info/",{jsonerrors:1,pub_key:t,file_id:r,source:s}),signal:i}).then(({data:c,headers:h,request:d})=>{let p=Ee(JSON.parse(c));if("error"in p)throw new j(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function Pa(r,{publicKey:t,contentType:e,fileName:i,multipartChunkSize:s=I.multipartChunkSize,baseURL:o="",secureSignature:n,secureExpire:a,store:l,signal:c,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=I.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=I.retryNetworkErrorMaxTimes,metadata:b}){return Le(()=>Me({method:"POST",url:we(o,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Be({publicKey:t,integration:d,userAgent:p})},data:ni({filename:i||Ns,size:r,content_type:e||ii,part_size:s,UPLOADCARE_STORE:_r(l),UPLOADCARE_PUB_KEY:t,signature:n,expire:a,source:h,metadata:b}),signal:c}).then(({data:_,headers:v,request:E})=>{let C=Ee(JSON.parse(_));if("error"in C)throw new j(C.error.content,C.error.errorCode,E,C,v);return C.parts=Object.keys(C.parts).map(P=>C.parts[Number(P)]),C}),{retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})}function Ra(r,t,{contentType:e,signal:i,onProgress:s,retryThrottledRequestMaxTimes:o=I.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:n=I.retryNetworkErrorMaxTimes}){return Le(()=>Me({method:"PUT",url:t,data:r,onProgress:s,signal:i,headers:{"Content-Type":e||ii}}).then(a=>(s&&s({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n})}function Da(r,{publicKey:t,baseURL:e=I.baseURL,source:i="local",signal:s,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=I.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=I.retryNetworkErrorMaxTimes}){return Le(()=>Me({method:"POST",url:we(e,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Be({publicKey:t,integration:o,userAgent:n})},data:ni({uuid:r,UPLOADCARE_PUB_KEY:t,source:i}),signal:s}).then(({data:c,headers:h,request:d})=>{let p=Ee(JSON.parse(c));if("error"in p)throw new j(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function vr(r,{publicKey:t,baseURL:e,source:i,integration:s,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a,signal:l,onProgress:c}){return Vs({check:h=>Gs(r,{publicKey:t,baseURL:e,signal:h,source:i,integration:s,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:l})}function Fa(r){return"defaultEffects"in r}var Ce=class{constructor(t,{baseCDN:e=I.baseCDN,fileName:i}={}){u(this,"uuid");u(this,"name");u(this,"size");u(this,"isStored");u(this,"isImage");u(this,"mimeType");u(this,"cdnUrl");u(this,"s3Url");u(this,"originalFilename");u(this,"imageInfo");u(this,"videoInfo");u(this,"contentInfo");u(this,"metadata");u(this,"s3Bucket");u(this,"defaultEffects",null);let{uuid:s,s3Bucket:o}=t,n=we(e,`${s}/`),a=o?we(`https://${o}.s3.amazonaws.com/`,`${s}/${t.filename}`):null;this.uuid=s,this.name=i||t.filename,this.size=t.size,this.isStored=t.isStored,this.isImage=t.isImage,this.mimeType=t.mimeType,this.cdnUrl=n,this.originalFilename=t.originalFilename,this.imageInfo=t.imageInfo,this.videoInfo=t.videoInfo,this.contentInfo=t.contentInfo,this.metadata=t.metadata||null,this.s3Bucket=o||null,this.s3Url=a,Fa(t)&&(this.defaultEffects=t.defaultEffects)}},Va=(r,{publicKey:t,fileName:e,baseURL:i,secureSignature:s,secureExpire:o,store:n,contentType:a,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:_})=>ka(r,{publicKey:t,fileName:e,contentType:a,baseURL:i,secureSignature:s,secureExpire:o,store:n,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:_}).then(({file:v})=>vr(v,{publicKey:t,baseURL:i,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:c,signal:l})).then(v=>new Ce(v,{baseCDN:b})),Na=(r,{publicKey:t,fileName:e,baseURL:i,signal:s,onProgress:o,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h,baseCDN:d})=>Gs(r,{publicKey:t,baseURL:i,signal:s,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h}).then(p=>new Ce(p,{baseCDN:d,fileName:e})).then(p=>(o&&o({isComputable:!0,value:1}),p)),Ba=(r,{signal:t}={})=>{let e=null,i=null,s=r.map(()=>new AbortController),o=n=>()=>{i=n,s.forEach((a,l)=>l!==n&&a.abort())};return ti(t,()=>{s.forEach(n=>n.abort())}),Promise.all(r.map((n,a)=>{let l=o(a);return Promise.resolve().then(()=>n({stopRace:l,signal:s[a].signal})).then(c=>(l(),c)).catch(c=>(e=c,null))})).then(n=>{if(i===null)throw e;return n[i]})},za=window.WebSocket,fr=class{constructor(){u(this,"events",Object.create({}))}emit(t,e){var i;(i=this.events[t])==null||i.forEach(s=>s(e))}on(t,e){this.events[t]=this.events[t]||[],this.events[t].push(e)}off(t,e){e?this.events[t]=this.events[t].filter(i=>i!==e):this.events[t]=[]}},Ha=(r,t)=>r==="success"?{status:J.Success,...t}:r==="progress"?{status:J.Progress,...t}:{status:J.Error,...t},mr=class{constructor(t,e=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new fr);u(this,"disconnectTimeoutId",null);this.key=t,this.disconnectTime=e}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let t=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new za(t),this.ws.addEventListener("error",e=>{this.emmitter.emit("error",new Error(e.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(e=>this.send(e.event,e.data)),this.queue=[]}),this.ws.addEventListener("message",e=>{let i=JSON.parse(e.data.toString());switch(i.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(i.channel,Ha(i.event,JSON.parse(i.data)))}})}}disconnect(){let t=()=>{var e;(e=this.ws)==null||e.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{t()},this.disconnectTime):t()}send(t,e){var s;let i=JSON.stringify({event:t,data:e});(s=this.ws)==null||s.send(i)}subscribe(t,e){this.subscribers+=1,this.connect();let i=`task-status-${t}`,s={event:"pusher:subscribe",data:{channel:i}};this.emmitter.on(i,e),this.isConnected?this.send(s.event,s.data):this.queue.push(s)}unsubscribe(t){this.subscribers-=1;let e=`task-status-${t}`,i={event:"pusher:unsubscribe",data:{channel:e}};this.emmitter.off(e),this.isConnected?this.send(i.event,i.data):this.queue=this.queue.filter(s=>s.data.channel!==e),this.subscribers===0&&this.disconnect()}onError(t){return this.emmitter.on("error",t),()=>this.emmitter.off("error",t)}},dr=null,yr=r=>{if(!dr){let t=typeof window=="undefined"?0:3e4;dr=new mr(r,t)}return dr},ja=r=>{yr(r).connect()};function Ga({token:r,publicKey:t,baseURL:e,integration:i,userAgent:s,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,onProgress:a,signal:l}){return Vs({check:c=>La(r,{publicKey:t,baseURL:e,integration:i,userAgent:s,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,signal:c}).then(h=>{switch(h.status){case J.Error:return new j(h.error,h.errorCode);case J.Waiting:return!1;case J.Unknown:return new j(`Token "${r}" was not found.`);case J.Progress:return a&&(h.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:h.done/h.total})),!1;case J.Success:return a&&a({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:l})}var Wa=({token:r,pusherKey:t,signal:e,onProgress:i})=>new Promise((s,o)=>{let n=yr(t),a=n.onError(o),l=()=>{a(),n.unsubscribe(r)};ti(e,()=>{l(),o(new ke("pusher cancelled"))}),n.subscribe(r,c=>{switch(c.status){case J.Progress:{i&&(c.total==="unknown"?i({isComputable:!1}):i({isComputable:!0,value:c.done/c.total}));break}case J.Success:{l(),i&&i({isComputable:!0,value:c.done/c.total}),s(c);break}case J.Error:l(),o(new j(c.msg,c.error_code))}})}),qa=(r,{publicKey:t,fileName:e,baseURL:i,baseCDN:s,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:c,signal:h,onProgress:d,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,pusherKey:_=I.pusherKey,metadata:v})=>Promise.resolve(ja(_)).then(()=>$a(r,{publicKey:t,fileName:e,baseURL:i,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:c,signal:h,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:v})).catch(E=>{let C=yr(_);return C==null||C.disconnect(),Promise.reject(E)}).then(E=>E.type===pr.FileInfo?E:Ba([({signal:C})=>Ga({token:E.token,publicKey:t,baseURL:i,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:C}),({signal:C})=>Wa({token:E.token,pusherKey:_,s