@uploadcare/file-uploader
Version: 
Building blocks for Uploadcare products integration
29 lines • 299 kB
JavaScript
/**
 * @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 _n=Object.defineProperty,wn=(i,e,t)=>e in i?_n(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ki=(i,e,t)=>(wn(i,typeof e!="symbol"?e+"":e,t),t);function Cn(i){let e=t=>{var r;for(let o in t)((r=t[o])==null?void 0:r.constructor)===Object&&(t[o]=e(t[o]));return{...t}};return e(i)}var T=class{constructor(i){i.constructor===Object?this.store=Cn(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)?(T.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)){T.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)?(T.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=T.globalStore.get(e);return t?console.warn('State: context UID "'+e+'" already in use'):(t=new T(i),T.globalStore.set(e,t)),t}static deleteCtx(i){T.globalStore.delete(i)}static getCtx(i,e=!0){return T.globalStore.get(i)||(e&&console.warn('State: wrong context UID - "'+i+'"'),null)}};T.globalStore=new Map;var C=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"}),ao="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",En=ao.length-1,Ce=class{static generate(i="XXXXXXXXX-XXX"){let e="";for(let t=0;t<i.length;t++)e+=i[t]==="-"?i[t]:ao.charAt(Math.random()*En);return e}};function lo(i,e,t){let r=!0,o,s=e.split(".");return s.forEach((n,a)=>{a<s.length-1?i=i[n]:o=n}),i?i[o]=t:r=!1,r}function Tn(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 xn(i,e){[...i.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),o;if(r&&(o=window.customElements.get(r)),!o){o=class extends e.BaseComponent{constructor(){super(),r||(this.style.display="contents")}};let n=t.innerHTML;o.template=n,o.reg(r)}for(;t.firstChild;)t.firstChild.remove();let s=t.getAttribute(C.REPEAT_ATTR);e.sub(s,n=>{if(!n){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],l,c=d=>{d.forEach((p,m)=>{if(a[m])if(a[m].set$)setTimeout(()=>{a[m].set$(p)});else for(let h in p)a[m][h]=p[h];else{l||(l=new DocumentFragment);let h=new o;Object.assign(h.init$,p),l.appendChild(h)}}),l&&t.appendChild(l);let u=a.slice(d.length,a.length);for(let p of u)p.remove()};if(n.constructor===Array)c(n);else if(n.constructor===Object){let d=[];for(let u in n){let p=n[u];Object.defineProperty(p,"_KEY_",{value:u,enumerable:!0}),d.push(p)}c(d)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var so="__default__";function An(i,e){if(e.shadowRoot)return;let t=[...i.querySelectorAll("slot")];if(!t.length)return;let r={};t.forEach(o=>{let s=o.getAttribute("name")||so;r[s]={slot:o,fr:document.createDocumentFragment()}}),e.initChildren.forEach(o=>{var s;let n=so;o instanceof Element&&o.hasAttribute("slot")&&(n=o.getAttribute("slot"),o.removeAttribute("slot")),(s=r[n])==null||s.fr.appendChild(o)}),Object.values(r).forEach(o=>{if(o.fr.childNodes.length)o.slot.parentNode.replaceChild(o.fr,o.slot);else if(o.slot.childNodes.length){let s=document.createDocumentFragment();s.append(...o.slot.childNodes),o.slot.parentNode.replaceChild(s,o.slot)}else o.slot.remove()})}function Sn(i,e){[...i.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.EL_REF_ATTR);e.ref[r]=t,t.removeAttribute(C.EL_REF_ATTR)})}function In(i,e){[...i.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let o=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(s=>{if(s.name.startsWith("-")&&s.value){let n=Tn(s.name.replace("-",""));o.push(n+":"+s.value),t.removeAttribute(s.name)}}),o.forEach(s=>{if(!s)return;let n=s.split(":").map(d=>d.trim()),a=n[0],l;a.indexOf(C.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(C.ATTR_BIND_PRFX,""));let c=n[1].split(",").map(d=>d.trim());for(let d of c){let u;d.startsWith("!!")?(u="double",d=d.replace("!!","")):d.startsWith("!")&&(u="single",d=d.replace("!","")),e.sub(d,p=>{u==="double"?p=!!p:u==="single"&&(p=!p),l?p?.constructor===Boolean?p?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,p):lo(t,a,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][a]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var Ut="{{",nt="}}",kn="skip-text";function On(i){let e,t=[],r=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode:o=>{var s;return!((s=o.parentElement)!=null&&s.hasAttribute(kn))&&o.textContent.includes(Ut)&&o.textContent.includes(nt)&&1}});for(;e=r.nextNode();)t.push(e);return t}var Mn=function(i,e){On(i).forEach(r=>{let o=[],s;for(;r.textContent.includes(nt);)r.textContent.startsWith(Ut)?(s=r.textContent.indexOf(nt)+nt.length,r.splitText(s),o.push(r)):(s=r.textContent.indexOf(Ut),r.splitText(s)),r=r.nextSibling;o.forEach(n=>{let a=n.textContent.replace(Ut,"").replace(nt,"");n.textContent="",e.sub(a,l=>{n.textContent=l})})})},Ln=[xn,An,Sn,In,Mn],$t="'",He='"',Rn=/\\([0-9a-fA-F]{1,6} ?)/g;function Pn(i){return(i[0]===He||i[0]===$t)&&(i[i.length-1]===He||i[i.length-1]===$t)}function Un(i){return(i[0]===He||i[0]===$t)&&(i=i.slice(1)),(i[i.length-1]===He||i[i.length-1]===$t)&&(i=i.slice(0,-1)),i}function $n(i){let e="",t="";for(var r=0;r<i.length;r++){let o=i[r+1];i[r]==="\\"&&o==='"'?(e+='\\"',r++):i[r]==='"'&&t!=="\\"?e+='\\"':e+=i[r],t=i[r]}return e}function Dn(i){let e=i;Pn(i)&&(e=Un(e),e=e.replace(Rn,(t,r)=>String.fromCodePoint(parseInt(r.trim(),16))),e=e.replaceAll(`\\
`,"\\n"),e=$n(e),e=He+e+He);try{return JSON.parse(e)}catch{throw new Error(`Failed to parse CSS property value: ${e}. Original input: ${i}`)}}var no=0,ze=null,ue=null,we=class extends HTMLElement{constructor(){super(),Ki(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 we}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 o=this.getAttribute(C.USE_TPL);if(o){let s=this.getRootNode(),n=s?.querySelector(o)||document.querySelector(o);n?i=n.content.cloneNode(!0):console.warn(`Symbiote template "${o}" is not found...`)}}if(this.processInnerHtml)for(let o of this.tplProcessors)o(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?.constructor===DocumentFragment)t=i;else if(i?.constructor===String){let o=document.createElement("template");o.innerHTML=i,t=o.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let o of this.tplProcessors)o(t,this)}let r=()=>{t&&(e&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){e=!0;let o=document.createElement("link");o.rel="stylesheet",o.href=this.constructor.__shadowStylesUrl,o.onload=r,this.shadowRoot.prepend(o)}else r()}addTemplateProcessor(i){this.tplProcessors.add(i)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Ce.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var i;let e=((i=this.getAttribute(C.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=T.registerCtx({},this)),this.__localCtx}get nodeCtx(){return T.getCtx(this.ctxName,!1)||T.registerCtx({},this.ctxName)}static __parseProp(i,e){let t,r;if(i.startsWith(C.EXT_DATA_CTX_PRFX))t=e.nodeCtx,r=i.replace(C.EXT_DATA_CTX_PRFX,"");else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let o=i.split(C.NAMED_DATA_CTX_SPLTR);t=T.getCtx(o[0]),r=o[1]}else t=e.localCtx,r=i;return{ctx:t,name:r}}sub(i,e,t=!0){let r=s=>{this.isConnected&&e(s)},o=we.__parseProp(i,this);o.ctx.has(o.name)?this.allSubs.add(o.ctx.sub(o.name,r,t)):window.setTimeout(()=>{this.allSubs.add(o.ctx.sub(o.name,r,t))})}notify(i){let e=we.__parseProp(i,this);e.ctx.notify(e.name)}has(i){let e=we.__parseProp(i,this);return e.ctx.has(e.name)}add(i,e,t=!1){let r=we.__parseProp(i,this);r.ctx.add(r.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,r)=>{let o=we.__parseProp(t,this);return o.ctx.pub(o.name,r),!0},get:(e,t)=>{let r=we.__parseProp(t,this);return r.ctx.read(r.name)}})}return this.__stateProxy}set$(i,e=!1){for(let t in i){let r=i[t];e||![String,Number,Boolean].includes(r?.constructor)?this.$[t]=r:this.$[t]!==r&&(this.$[t]=r)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.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(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(e.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[e],this.__ctxOwner);else if(e.includes(C.NAMED_DATA_CTX_SPLTR)){let t=e.split(C.NAMED_DATA_CTX_SPLTR),r=t[0].trim(),o=t[1].trim();if(r&&o){let s=T.getCtx(r,!1);s||(s=T.registerCtx({},r)),s.add(o,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(C.CTX_NAME_ATTR))==null?void 0:i.trim();if(e&&this.style.setProperty(C.CSS_CTX_PROP,`'${e}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])lo(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Ln)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t?.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let o=this.constructor.__rootStylesLink.cloneNode(!0);o.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),o.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(o):t.prepend(o)}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);ue?.delete(this.updateCssData),ue?.size||(ze?.disconnect(),ze=null,ue=null)},100)))}static reg(i,e=!1){i||(no++,i=`${C.AUTO_TAG_PRFX}-${no}`),this.__tag=i;let t=window.customElements.get(i);if(t){!e&&t!==this&&console.warn([`Element with tag name "${i}" 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(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 r;if(e===t)return;let o=(r=this.constructor.__attrDesc)==null?void 0:r[i];o?this.__dataCtxInitialized?this.$[o]=t:this.init$[o]=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();try{this.__cssDataCache[i]=Dn(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(){ue||(ue=new Set),ue.add(this.updateCssData),ze||(ze=new MutationObserver(i=>{i[0].type==="attributes"&&ue.forEach(e=>{e()})}),ze.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 r="__"+i;this[r]=this[i],Object.defineProperty(this,i,{set:o=>{this[r]=o,t?window.setTimeout(()=>{e?.(o)}):e?.(o)},get:()=>this[r]}),this[i]=this[r]}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),r=document.createElement("link");r.href=t,r.rel="stylesheet",this.__rootStylesLink=r}}},Ee=we;Ki(Ee,"template");var ji=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 r=t.split("=");i.options[r[0]]=decodeURI(r[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(ji.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 r="?"+i;for(let s in e)e[s]===!0?r+=this.separator+s:r+=this.separator+s+`=${e[s]}`;let o=t.title||this.defaultTitle||"";window.history.pushState(null,o,r),document.title=o}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=T.registerCtx({route:null,options:null,title:null},i);return window.addEventListener(this.routingEventName,r=>{var o;t.multiPub({route:r.detail.route,options:r.detail.options,title:((o=r.detail.options)==null?void 0:o.title)||this.defaultTitle||""})}),ji.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}};ji.appMap=Object.create(null);function at(i,e){for(let t in e)t.includes("-")?i.style.setProperty(t,e[t]):i.style[t]=e[t]}function Fn(i,e){for(let t in e)e[t].constructor===Boolean?e[t]?i.setAttribute(t,""):i.removeAttribute(t):i.setAttribute(t,e[t])}function Gi(i={tag:"div"}){let e=document.createElement(i.tag);if(i.attributes&&Fn(e,i.attributes),i.styles&&at(e,i.styles),i.properties)for(let t in i.properties)e[t]=i.properties[t];return i.processors&&i.processors.forEach(t=>{t(e)}),i.children&&i.children.forEach(t=>{let r=Gi(t);e.appendChild(r)}),e}var co="idb-store-ready",Vn="symbiote-db",Nn="symbiote-idb-update_",Bn=class{_notifyWhenReady(i=null){window.dispatchEvent(new CustomEvent(co,{detail:{dbName:this.name,storeName:this.storeName,event:i}}))}get _updEventName(){return Nn+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=r=>{this._notifyWhenReady(r)}},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 o=>{o(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((r,o)=>{t.onsuccess=s=>{var n;(n=s.target.result)!=null&&n._value?r(s.target.result._value):(r(null),console.warn(`IDB: cannot read "${i}"`))},t.onerror=s=>{o(s)}})}write(i,e,t=!1){let r={_key:i,_value:e},s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(r);return new Promise((n,a)=>{s.onsuccess=l=>{t||this._notifySubscribers(i),n(l.target.result)},s.onerror=l=>{a(l)}})}delete(i,e=!1){let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(i);return new Promise((o,s)=>{r.onsuccess=n=>{e||this._notifySubscribers(i),o(n)},r.onerror=n=>{s(n)}})}getAll(){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,r)=>{e.onsuccess=o=>{let s=o.target.result;t(s.map(n=>n._value))},e.onerror=o=>{r(o)}})}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,uo.clear(this.name)}},uo=class{static get readyEventName(){return co}static open(i=Vn,e="store"){let t=i+"/"+e;return this._reg[t]||(this._reg[t]=new Bn(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]}};Ki(uo,"_reg",Object.create(null));var pe=Object.freeze({INIT_SOLUTION:"init-solution",CHANGE_CONFIG:"change-config"}),b=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",...pe}),Dt=class{_timeoutStore=new Map;_targets=new Set;_debugPrint=null;constructor(e){this._debugPrint=e}bindTarget(e){this._targets.add(e)}unbindTarget(e){this._targets.delete(e)}_dispatch(e,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(e,{detail:t}));this._debugPrint?.(()=>{let r=t&&typeof t=="object"?{...t}:t;return[`event "${e}"`,r]})}emit(e,t,r={}){let{debounce:o}=r;if(typeof o!="number"&&!o){this._dispatch(e,typeof t=="function"?t():t);return}this._timeoutStore.has(e)&&window.clearTimeout(this._timeoutStore.get(e));let s=typeof o=="number"?o:20,n=window.setTimeout(()=>{this._dispatch(e,typeof t=="function"?t():t),this._timeoutStore.delete(e)},s);this._timeoutStore.set(e,n)}};function O(i,e){let t,r=((...o)=>{t&&clearTimeout(t),t=setTimeout(()=>i(...o),e)});return r.cancel=()=>{t&&clearTimeout(t)},r}var W=i=>i?i.split(",").map(e=>e.trim()).filter(Boolean):[],he=i=>i.join(",");var po=i=>{if(typeof i!="string"||!i)return"";let e=i.trim();return e.startsWith("-/")?e=e.slice(2):e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,e.length-1)),e},Ft=(...i)=>i.filter(e=>typeof e=="string"&&!!e).map(e=>po(e)).join("/-/"),B=(...i)=>{let e=Ft(...i);return e?`-/${e}/`:""};function Vt(i){let e=new URL(i),t=e.pathname+e.search+e.hash,r=t.lastIndexOf("http"),o=t.lastIndexOf("/"),s="";return r>=0?s=t.slice(r):o>=0&&(s=t.slice(o+1)),s}function Nt(i){let e=new URL(i),{pathname:t}=e,r=t.indexOf("/"),o=t.indexOf("/",r+1);return t.substring(r+1,o)}function Wi(i){let e=ho(i),t=new URL(e),r=t.pathname.indexOf("/-/");return r===-1?"":t.pathname.substring(r).slice(1)}function qi(i){return Wi(i).split("/-/").filter(Boolean).map(t=>po(t))}function ho(i){let e=new URL(i),t=Vt(i),r=mo(t)?fo(t).pathname:t;return e.pathname=e.pathname.replace(r,""),e.search="",e.hash="",e.toString()}function mo(i){return i.startsWith("http")}function fo(i){let e=new URL(i);return{pathname:`${e.origin}${e.pathname??""}`,search:e.search??"",hash:e.hash??""}}var P=(i,e,t)=>{let r=new URL(ho(i)),o=t??Vt(i),s=e??"";if(r.pathname.startsWith("//")&&(r.pathname=r.pathname.replace("//","/")),o&&mo(o)){let n=fo(o);r.pathname=`${r.pathname}${s}${n.pathname||""}`,r.search=n.search,r.hash=n.hash}else r.pathname=`${r.pathname}${s}${o||""}`;return r.toString()},Te=(i,e)=>{let t=new URL(i);return t.pathname=`${e}/`,t.toString()};var U=(i,e=",")=>i.trim().split(e).map(t=>t.trim()).filter(t=>t.length>0);var lt=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}),vo=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function zn(i,e){if(typeof e=="number"){let t=e;return lt[i]!==t?`${i}/${t}`:""}if(typeof e=="boolean"){let t=e;return lt[i]!==t?`${i}`:""}if(i==="filter"&&e){let{name:t,amount:r}=e;return lt.filter===r?"":`${i}/${t}/${r}`}if(i==="crop"&&e){let{dimensions:t,coords:r}=e;return`${i}/${t.join("x")}/${r.join(",")}`}return""}function xe(i){return Ft(...vo.filter(e=>typeof i[e]<"u"&&i[e]!==null).map(e=>{let t=i[e];return zn(e,t)}).filter(e=>!!e))}var Bt=Ft("format/auto","progressive/yes"),me=([i])=>typeof i<"u"?Number(i):void 0,go=()=>!0,Hn=([i,e])=>({name:i,amount:typeof e<"u"?Number(e):100}),jn=([i,e])=>{if(!/\d+x\d+/.test(i)||!/\d+,\d+/.test(e))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:U(i,"x").map(Number),coords:U(e).map(Number)}},Kn=Object.freeze({enhance:me,brightness:me,exposure:me,gamma:me,contrast:me,saturation:me,vibrance:me,warmth:me,filter:Hn,mirror:go,flip:go,rotate:me,crop:i=>{let[e,t]=i,{dimensions:r,coords:o}=jn([e,t]);return{dimensions:r,coords:o}}});function Xi(i){let e={};for(let t of i){let[r,...o]=t.split("/");if(!r||!vo.includes(r))continue;let s=r,n=Kn[s];try{let a=n(o);e[s]=a}catch(a){console.warn([`Failed to parse URL operation "${t}". 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 e}var M=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),q=Object.freeze([M.CROP,M.TUNING,M.FILTERS]),yo=Object.freeze(["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"]),bo=Object.freeze(["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"]),_o=Object.freeze(["rotate","mirror","flip"]),fe=lt,ie=Object.freeze({brightness:{zero:fe.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:fe.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:fe.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:fe.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:fe.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:fe.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:fe.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:fe.enhance,range:[0,100],keypointsNumber:1},filter:{zero:fe.filter,range:[0,100],keypointsNumber:1}});var ct="https://ucarecdn.com",Gn="https://upload.uploadcare.com",Wn="https://social.uploadcare.com",qn="https://ucarecd.net",Xn={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:he(q),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:ct,cdnCnamePrefixed:qn,baseUrl:Gn,socialBaseUrl:Wn,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:600*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},Z=Object.freeze(Xn);var wo=i=>{let e=new Intl.Locale(i),t="ltr",r=e.getTextInfo?.().direction;return r?t=r:e.textInfo?.direction&&(t=e.textInfo.direction),t};var zt=(i,e)=>new Intl.PluralRules(i).select(e);var Zn=i=>i;var Co="plural:";function dt(i,e={},t={}){let{openToken:r="{{",closeToken:o="}}",transform:s=Zn}=t;for(let n in e){let a=e[n],l=a?.toString(),c=typeof l=="string"?s(l):String(l);i=i.replaceAll(r+n+o,c)}return i}function Eo(i){let e=[],t=i.indexOf("{{");for(;t!==-1;){let r=i.indexOf("}}",t);if(r===-1)break;let o=i.substring(t+2,r);if(o.startsWith(Co)){let s=i.substring(t+2,r).replace(Co,""),n=s.substring(0,s.indexOf("(")),a=s.substring(s.indexOf("(")+1,s.indexOf(")"));e.push({variable:o,pluralKey:n,countVariable:a})}t=i.indexOf("{{",r)}return e}var To="--uploadcare-blocks-window-height",ut=class i{static clientsRegistry=new Set;static flush=O(()=>{document.documentElement.style.setProperty(To,`${window.innerHeight}px`)},100);static registerClient(e){i.clientsRegistry.size===0&&i.attachTracker(),i.clientsRegistry.add(e)}static unregisterClient(e){i.clientsRegistry.delete(e),i.clientsRegistry.size===0&&i.detachTracker()}static attachTracker(){window.addEventListener("resize",i.flush,{passive:!0,capture:!0}),i.flush()}static detachTracker(){window.removeEventListener("resize",i.flush,{capture:!0}),document.documentElement.style.removeProperty(To)}};var xo=({element:i,attribute:e,onSuccess:t,onTimeout:r,timeout:o=300})=>{let s=i.getAttribute(e);if(s!==null){t(s);return}let n=new MutationObserver(c=>{let d=c[c.length-1];d&&l(d)});n.observe(i,{attributes:!0,attributeFilter:[e]});let a=window.setTimeout(()=>{n.disconnect(),r()},o),l=c=>{let d=i.getAttribute(e);c.type==="attributes"&&c.attributeName===e&&d!==null&&(window.clearTimeout(a),n.disconnect(),t(d))}};function Ao(i){return Object.prototype.toString.call(i)==="[object Object]"}var Yn=/\W|_/g;function Qn(i){return i.split(Yn).map((e,t)=>e.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+e.slice(1)).join("")}function So(i,{ignoreKeys:e}={ignoreKeys:[]}){return Array.isArray(i)?i.map(t=>ye(t,{ignoreKeys:e})):i}function ye(i,{ignoreKeys:e}={ignoreKeys:[]}){if(Array.isArray(i))return So(i,{ignoreKeys:e});if(!Ao(i))return i;let t={};for(let r of Object.keys(i)){let o=i[r];if(e.includes(r)){t[r]=o;continue}Ao(o)?o=ye(o,{ignoreKeys:e}):Array.isArray(o)&&(o=So(o,{ignoreKeys:e})),t[Qn(r)]=o}return t}var Jn=i=>new Promise(e=>setTimeout(e,i));function ir({libraryName:i,libraryVersion:e,userAgent:t,publicKey:r="",integration:o=""}){let s="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:r,libraryName:i,libraryVersion:e,languageName:s,integration:o});let n=[i,e,r].filter(Boolean).join("/"),a=[s,o].filter(Boolean).join("; ");return`${n} (${a})`}var ea={factor:2,time:100};function ta(i,e=ea){let t=0;function r(o){let s=Math.round(e.time*e.factor**t);return o({attempt:t,retry:a=>Jn(a??s).then(()=>(t+=1,r(o)))})}return r(i)}var $e=class extends Error{},je=class i extends $e{originalProgressEvent;constructor(e){super(),this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,i.prototype),this.originalProgressEvent=e}},Ht=(i,e)=>{i&&(i.aborted?Promise.resolve().then(e):i.addEventListener("abort",()=>e(),{once:!0}))},Ae=class i extends $e{isCancel=!0;constructor(e="Request canceled"){super(e),this.name="CancelError",Object.setPrototypeOf(this,i.prototype)}},ia=500,ko=({check:i,interval:e=ia,timeout:t,signal:r})=>new Promise((o,s)=>{let n,a;Ht(r,()=>{n&&clearTimeout(n),s(new Ae("Poll cancelled"))}),t&&(a=setTimeout(()=>{n&&clearTimeout(n),s(new Ae("Timed out"))},t));let l=()=>{try{Promise.resolve(i(r)).then(c=>{c?(a&&clearTimeout(a),o(c)):n=setTimeout(l,e)}).catch(c=>{a&&clearTimeout(a),s(c)})}catch(c){a&&clearTimeout(a),s(c)}};n=setTimeout(l,0)}),S={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"},jt="application/octet-stream",Oo="original",Ie=({method:i,url:e,data:t,headers:r={},signal:o,onProgress:s})=>new Promise((n,a)=>{let l=new XMLHttpRequest,c=i?.toUpperCase()||"GET",d=!1;l.open(c,e,!0),r&&Object.entries(r).forEach(u=>{let[p,m]=u;typeof m<"u"&&!Array.isArray(m)&&l.setRequestHeader(p,m)}),l.responseType="text",Ht(o,()=>{d=!0,l.abort(),a(new Ae)}),l.onload=()=>{if(l.status!=200)a(new Error(`Error ${l.status}: ${l.statusText}`));else{let u={method:c,url:e,data:t,headers:r||void 0,signal:o,onProgress:s},p=l.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function(v){let A=v.split(": "),E=A.shift(),x=A.join(": ");E&&typeof E<"u"&&(m[E]=x)});let h=l.response,g=l.status;n({request:u,data:h,headers:m,status:g})}},l.onerror=u=>{d||a(new je(u))},s&&typeof s=="function"&&(l.upload.onprogress=u=>{u.lengthComputable?s({isComputable:!0,value:u.loaded/u.total}):s({isComputable:!1})}),t?l.send(t):l.send()});function ra(i,...e){return i}var oa=({name:i})=>i?[i]:[],sa=ra,na=()=>new FormData,Mo=i=>!1,Kt=i=>typeof Blob<"u"&&i instanceof Blob,Gt=i=>typeof File<"u"&&i instanceof File,Wt=i=>!!i&&typeof i=="object"&&!Array.isArray(i)&&"uri"in i&&typeof i.uri=="string",Ke=i=>Kt(i)||Gt(i)||Mo()||Wt(i),aa=i=>typeof i=="string"||typeof i=="number"||typeof i>"u",la=i=>!!i&&typeof i=="object"&&!Array.isArray(i),ca=i=>!!i&&typeof i=="object"&&"data"in i&&Ke(i.data);function Lo(i,e,t){if(Array.isArray(t))for(let r of t)Lo(i,`${e}[]`,r);else if(ca(t)){let{name:r,contentType:o}=t,s=sa(t.data,r,o??jt),n=oa({name:r,contentType:o});i.push([e,s,...n])}else if(la(t))for(let[r,o]of Object.entries(t))typeof o<"u"&&i.push([`${e}[${r}]`,String(o)]);else aa(t)&&t&&i.push([e,t.toString()])}function da(i){let e=[];for(let[t,r]of Object.entries(i))Lo(e,t,r);return e}function qt(i){let e=na(),t=da(i);for(let r of t){let[o,s,...n]=r;e.append(o,s,...n)}return e}var z=class i extends $e{code;request;response;headers;constructor(e,t,r,o,s){super(),this.name="UploadError",this.message=e,this.code=t,this.request=r,this.response=o,this.headers=s,Object.setPrototypeOf(this,i.prototype)}},ua=i=>{let e=new URLSearchParams;for(let[t,r]of Object.entries(i))r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(o=>o[1]??!1).forEach(o=>e.set(`${t}[${o[0]}]`,String(o[1]))):Array.isArray(r)?r.forEach(o=>{e.append(`${t}[]`,o)}):typeof r=="string"&&r?e.set(t,r):typeof r=="number"&&e.set(t,r.toString());return e.toString()},ge=(i,e,t)=>{let r=new URL(i);return r.pathname=(r.pathname+e).replace("//","/"),t&&(r.search=ua(t)),r.toString()},pa="6.18.0",ha="UploadcareUploadClient",ma=pa;function De(i){return ir({libraryName:ha,libraryVersion:ma,...i})}var fa="RequestThrottledError",Io=15e3,ga=1e3;function va(i){let{headers:e}=i||{};if(!e||typeof e["retry-after"]!="string")return Io;let t=parseInt(e["retry-after"],10);return Number.isFinite(t)?t*1e3:Io}function ke(i,e){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:r}=e;return ta(({attempt:o,retry:s})=>i().catch(n=>{if("response"in n&&n?.code===fa&&o<t)return s(va(n));if(n instanceof je&&o<r)return s((o+1)*ga);throw n}))}var Ro=i=>{let e="";return(Kt(i)||Gt(i)||Wt(i))&&(e=i.type),e||jt},Po=i=>{let e="";return Gt(i)&&i.name?e=i.name:Kt(i)||Mo()?e="":Wt(i)&&i.name&&(e=i.name),e||Oo};function rr(i){return typeof i>"u"||i==="auto"?"auto":i?"1":"0"}function ya(i,{publicKey:e,fileName:t,contentType:r,baseURL:o=S.baseURL,secureSignature:s,secureExpire:n,store:a,signal:l,onProgress:c,source:d="local",integration:u,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:h=S.retryNetworkErrorMaxTimes,metadata:g}){return ke(()=>Ie({method:"POST",url:ge(o,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":De({publicKey:e,integration:u,userAgent:p})},data:qt({file:{data:i,name:t||Po(i),contentType:r||Ro(i)},UPLOADCARE_PUB_KEY:e,UPLOADCARE_STORE:rr(a),signature:s,expire:n,source:d,metadata:g}),signal:l,onProgress:c}).then(({data:v,headers:A,request:E})=>{let x=ye(JSON.parse(v));if("error"in x)throw new z(x.error.content,x.error.errorCode,E,x,A);return x}),{retryNetworkErrorMaxTimes:h,retryThrottledRequestMaxTimes:m})}var Qi;(function(i){i.Token="token",i.FileInfo="file_info"})(Qi||(Qi={}));function ba(i,{publicKey:e,baseURL:t=S.baseURL,store:r,fileName:o,checkForUrlDuplicates:s,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,source:c="url",signal:d,integration:u,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:h=S.retryNetworkErrorMaxTimes,metadata:g}){return ke(()=>Ie({method:"POST",headers:{"X-UC-User-Agent":De({publicKey:e,integration:u,userAgent:p})},url:ge(t,"/from_url/",{jsonerrors:1,pub_key:e,source_url:i,store:rr(r),filename:o,check_URL_duplicates:s?1:void 0,save_URL_duplicates:n?1:void 0,signature:a,expire:l,source:c,metadata:g}),signal:d}).then(({data:v,headers:A,request:E})=>{let x=ye(JSON.parse(v));if("error"in x)throw new z(x.error.content,x.error.errorCode,E,x,A);return x}),{retryNetworkErrorMaxTimes:h,retryThrottledRequestMaxTimes:m})}var X;(function(i){i.Unknown="unknown",i.Waiting="waiting",i.Progress="progress",i.Error="error",i.Success="success"})(X||(X={}));var _a=i=>"status"in i&&i.status===X.Error;function wa(i,{publicKey:e,baseURL:t=S.baseURL,signal:r,integration:o,userAgent:s,retryThrottledRequestMaxTimes:n=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=S.retryNetworkErrorMaxTimes}={}){return ke(()=>Ie({method:"GET",headers:e?{"X-UC-User-Agent":De({publicKey:e,integration:o,userAgent:s})}:void 0,url:ge(t,"/from_url/status/",{jsonerrors:1,token:i}),signal:r}).then(({data:l,headers:c,request:d})=>{let u=ye(JSON.parse(l));if("error"in u&&!_a(u))throw new z(u.error.content,u.error.errorCode,d,u,c);return u}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:n})}function Ca(i,{publicKey:e,baseURL:t=S.baseURL,jsonpCallback:r,secureSignature:o,secureExpire:s,signal:n,source:a,integration:l,userAgent:c,retryThrottledRequestMaxTimes:d=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:u=S.retryNetworkErrorMaxTimes}){return ke(()=>Ie({method:"POST",headers:{"X-UC-User-Agent":De({publicKey:e,integration:l,userAgent:c})},url:ge(t,"/group/",{jsonerrors:1}),data:qt({files:i,callback:r,pub_key:e,signature:o,expire:s,source:a}),signal:n}).then(({data:p,headers:m,request:h})=>{let g=ye(JSON.parse(p));if("error"in g)throw new z(g.error.content,g.error.errorCode,h,g,m);return g}),{retryNetworkErrorMaxTimes:u,retryThrottledRequestMaxTimes:d})}function Uo(i,{publicKey:e,baseURL:t=S.baseURL,signal:r,source:o,integration:s,userAgent:n,retryThrottledRequestMaxTimes:a=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=S.retryNetworkErrorMaxTimes}){return ke(()=>Ie({method:"GET",headers:{"X-UC-User-Agent":De({publicKey:e,integration:s,userAgent:n})},url:ge(t,"/info/",{jsonerrors:1,pub_key:e,file_id:i,source:o}),signal:r}).then(({data:c,headers:d,request:u})=>{let p=ye(JSON.parse(c));if("error"in p)throw new z(p.error.content,p.error.errorCode,u,p,d);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function Ea(i,{publicKey:e,contentType:t,fileName:r,multipartChunkSize:o=S.multipartChunkSize,baseURL:s="",secureSignature:n,secureExpire:a,store:l,signal:c,source:d="local",integration:u,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:h=S.retryNetworkErrorMaxTimes,metadata:g}){return ke(()=>Ie({method:"POST",url:ge(s,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":De({publicKey:e,integration:u,userAgent:p})},data:qt({filename:r||Oo,size:i,content_type:t||jt,part_size:o,UPLOADCARE_STORE:rr(l),UPLOADCARE_PUB_KEY:e,signature:n,expire:a,source:d,metadata:g}),signal:c}).then(({data:v,headers:A,request:E})=>{let x=ye(JSON.parse(v));if("error"in x)throw new z(x.error.content,x.error.errorCode,E,x,A);return x.parts=Object.keys(x.parts).map(Y=>x.parts[Number(Y)]),x}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:h})}function Ta(i,e,{contentType:t,signal:r,onProgress:o,retryThrottledRequestMaxTimes:s=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:n=S.retryNetworkErrorMaxTimes}){return ke(()=>Ie({method:"PUT",url:e,data:i,onProgress:o,signal:r,headers:{"Content-Type":t||jt}}).then(a=>(o&&o({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:s,retryNetworkErrorMaxTimes:n})}function xa(i,{publicKey:e,baseURL:t=S.baseURL,source:r="local",signal:o,integration:s,userAgent:n,retryThrottledRequestMaxTimes:a=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=S.retryNetworkErrorMaxTimes}){return ke(()=>Ie({method:"POST",url:ge(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":De({publicKey:e,integration:s,userAgent:n})},data:qt({uuid:i,UPLOADCARE_PUB_KEY:e,source:r}),signal:o}).then(({data:c,headers:d,request:u})=>{let p=ye(JSON.parse(c));if("error"in p)throw new z(p.error.content,p.error.errorCode,u,p,d);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function or(i,{publicKey:e,baseURL:t,source:r,integration:o,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a,signal:l,onProgress:c}){return ko({check:d=>Uo(i,{publicKey:e,baseURL:t,signal:d,source:r,integration:o,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a}).then(u=>u.isReady?u:(c&&c({isComputable:!0,value:1}),!1)),signal:l})}function Aa(i){return"defaultEffects"in i}var ve=class{uuid;name;size;isStored;isImage;mimeType;cdnUrl;s3Url;originalFilename;imageInfo;videoInfo;contentInfo;metadata;s3Bucket;defaultEffects=null;constructor(e,{baseCDN:t=S.baseCDN,fileName:r}={}){let{uuid:o,s3Bucket:s}=e,n=ge(t,`${o}/`),a=s?ge(`https://${s}.s3.amazonaws.com/`,`${o}/${e.filename}`):null;this.uuid=o,this.name=r||e.filename,this.size=e.size,this.isStored=e.isStored,this.isImage=e.isImage,this.mimeType=e.mimeType,this.cdnUrl=n,this.originalFilename=e.originalFilename,this.imageInfo=e.imageInfo,this.videoInfo=e.videoInfo,this.contentInfo=e.contentInfo,this.metadata=e.metadata||null,this.s3Bucket=s||null,this.s3Url=a,Aa(e)&&(this.defaultEffects=e.defaultEffects)}},Sa=(i,{publicKey:e,fileName:t,baseURL:r,secureSignature:o,secureExpire:s,store:n,contentType:a,signal:l,onProgress:c,source:d,integration:u,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:h,baseCDN:g,metadata:v})=>ya(i,{publicKey:e,fileName:t,contentType:a,baseURL:r,secureSignature:o,secureExpire:s,store:n,signal:l,onProgress:c,source:d,integration:u,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:h,metadata:v}).then(({file:A})=>or(A,{publicKey:e,baseURL:r,source:d,integration:u,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:h,onProgress:c,signal:l})).then(A=>new ve(A,{baseCDN:g})),Ia=(i,{publicKey:e,fileName:t,baseURL:r,signal:o,onProgress:s,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:d,baseCDN:u})=>Uo(i,{publicKey:e,baseURL:r,signal:o,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:d}).then(p=>new ve(p,{baseCDN:u,fileName:t})).then(p=>(s&&s({isComputable:!0,value:1}),p)),ka=(i,{signal:e}={})=>{let t=null,r=null,o=i.map(()=>new AbortController),s=n=>()=>{r=n,o.forEach((a,l)=>l!==n&&a.abort())};return Ht(e,()=>{o.forEach(n=>n.abort())}),Promise.all(i.map((n,a)=>{let l=s(a);return Promise.resolve().then(()=>n({stopRace:l,signal:o[a].signal})).then(c=>(l(),c)).catch(c=>(t=c,null))})).then(n=>{if(r===null)throw t;return n[r]})},Oa=window.WebSocket,Ji=class{events=Object.create({});emit(e,t){this.events[e]?.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(r=>r!==t):this.events[e]=[]}},Ma=(i,e)=>i==="success"?{status:X.Success,...e}:i==="progress"?{status:X.Progress,...e}:{status:X.Error,...e},er=class{key;disconnectTime;ws=void 0;queue=[];isConnected=!1;subscribers=0;emmitter=new Ji;disconnectTimeoutId=null;constructor(e,t=3e4){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 Oa(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 r=JSON.parse(t.data.toString());switch(r.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(r.channel,Ma(r.event,JSON.parse(r.data)))}})}}disconnect(){let e=()=>{this.ws?.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{e()},this.disconnectTime):e()}send(e,t){let r=JSON.stringify({event:e,data:t});this.ws?.send(r)}subscribe(e,t){this.subscribers+=1,this.connect();let r=`task-status-${e}`,o={event:"pusher:subscribe",data:{channel:r}};this.emmitter.on(r,t),this.isConnected?this.send(o.event,o.data):this.queue.push(o)}unsubscribe(e){this.subscribers-=1;let t=`task-status-${e}`,r={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(r.event,r.data):this.queue=this.queue.filter(o=>o.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(e){return this.emmitter.on("error",e),()=>this.emmitter.off("error",e)}},Zi=null,sr=i=>{if(!Zi){let e=typeof window>"u"?0:3e4;Zi=new er(i,e)}return Zi},La=i=>{sr(i).connect()};function Ra({token:i,publicKey:e,baseURL:t,integration:r,userAgent:o,retryThrottledRequestMaxTimes:s,retryNetworkErrorMaxTimes:n,onProgress:a,signal:l}){return ko({check:c=>wa(i,{publicKey:e,baseURL:t,integration:r,userAgent:o,retryThrottledRequestMaxTimes:s,retryNetworkErrorMaxTimes:n,signal:c}).then(d=>{switch(d.status){case X.Error:return new z(d.error,d.errorCode);case X.Waiting:return!1;case X.Unknown:return new z(`Token "${i}" was not found.`);case X.Progress:return a&&(d.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:d.done/d.total})),!1;case X.Success:return a&&a({isComputable:!0,value:d.done/d.total}),d;default:throw new Error("Unknown status")}}),signal:l})}var Pa=({token:i,pusherKey:e,signal:t,onProgress:r})=>new Promise((o,s)=>{let n=sr(e),a=n.onError(s),l=()=>{a(),n.unsubscribe(i)};Ht(t,()=>{l(),s(new Ae("pusher cancelled"))}),n.subscribe(i,c=>{switch(c.status){case X.Progress:{r&&(c.total==="unknown"?r({isComputable:!1}):r({isComputable:!0,value:c.done/c.total}));break}case X.Success:{l(),r&&r({isComputable:!0,value:c.done/c.total}),o(c);break}case X.Error:l(),s(new z(c.msg,c.error_code))}})}),Ua=(i,{publicKey:e,fileName:t,baseURL:r,baseCDN:o,checkForUrlDuplicates:s,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:c,signal:d,onProgress:u,source:p,integration:m,userAgent:h,retryThrottledRequestMaxTimes:g,pusherKey:v=S.pusherKey,metadata:A})=>Promise.resolve(La(v)).then(()=>ba(i,{publicKey:e,fileName:t,baseURL:r,checkForUrlDuplicates:s,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:c,signal:d,source:p,integration:m,userAgent:h,retryThrottledRequestMaxTimes:g,metadata:A})).catch(E=>(sr(v)?.disconnect(),Promise.reject(E))).then(E=>E.type===Qi.FileInfo?E:ka([({signal:x})=>Ra({token:E.token,publicKey:e,baseURL:r,integration:m,userAgent:h,retryThrottledRequestMaxTimes:g,onProgress:u,signal:x}),({signal:x})=>Pa({token:E.token,pusherKey:v,signal:x,onProgress:u})],{signal:d})).then(E=>{if(E instanceof z)throw E;return E}).then(E=>or(E.uuid,{publicKey:e,baseURL:r,integration:m,userAgent:h,retryThrottledRequestMaxTimes:g,onProgress:u,signal:d})).then(E=>new ve(E,{baseCDN:o})),Yi=new WeakMap,$a=async i=>{if(Yi.has(i))return Yi.get(i);let e=await fetch(i.uri).then(t=>t.blob());return Yi.set(i,e),e},$o=async i=>{if(Gt(i)||Kt(i))return i.size;if(Wt(i))return(await $a(i)).size;throw new Error("Unknown file type. Cannot determine file size.")},Da=(i,e=S.multipartMinFileSize)=>i>=e,Do=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!Ke(i)&&t.test(i)},nr=i=>{let e="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(e);return!Ke(i)&&t.test(i)},Fa=(i,e)=>new Promise((t,r)=>{let o=[],s=!1,n=e.length,a=[...e],l=()=>{let c=e.length-a.length,d=a.shift();d&&