diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c9ccc52d..3239790d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.30.5](https://github.com/uploadcare/blocks/compare/v0.30.4...v0.30.5) (2023-12-07) + +### Bug Fixes + +- **activity-block:** check for the `*modalActive` key presence in state before subscribing it ([0e50b4f](https://github.com/uploadcare/blocks/commit/0e50b4f6dc2664eea7a7f12742660385a50610fd)) +- destroy upload collection when the last block in context is being destroyed ([42e501a](https://github.com/uploadcare/blocks/commit/42e501a85d089b4863950482fd89d240102aeb7d)) + ## [0.30.4](https://github.com/uploadcare/blocks/compare/v0.30.3...v0.30.4) (2023-12-06) ### Bug Fixes diff --git a/env.js b/env.js index aa67ad475..645583290 100644 --- a/env.js +++ b/env.js @@ -1,3 +1,3 @@ /** Do not edit this file manually. It's generated during build process. */ export const PACKAGE_NAME = 'blocks'; -export const PACKAGE_VERSION = '0.30.4'; +export const PACKAGE_VERSION = '0.30.5'; diff --git a/get-started/configuration/index.html b/get-started/configuration/index.html index 1a8698ede..9da8dcaa3 100644 --- a/get-started/configuration/index.html +++ b/get-started/configuration/index.html @@ -86,7 +86,7 @@
You can redefine styling or any other setting using custom CSS file. It's easy to discover proper elements and their selectors using developer tools in your browser.
Custom CSS-file example:
-@import url('https://unpkg.com/@uploadcare/blocks@0.30.4/web/file-uploader-regular.min.css');
+@import url('https://unpkg.com/@uploadcare/blocks@0.30.5/web/file-uploader-regular.min.css');
lr-modal {
border: 2px solid #f00;
diff --git a/get-started/installation/index.html b/get-started/installation/index.html
index f82103ec3..564a4b83e 100644
--- a/get-started/installation/index.html
+++ b/get-started/installation/index.html
@@ -82,12 +82,12 @@ Script tag approach
Connect script to your document:
-<script src="https://unpkg.com/@uploadcare/blocks@0.30.4/web/blocks-browser.min.js" type="module"></script>
+<script src="https://unpkg.com/@uploadcare/blocks@0.30.5/web/blocks-browser.min.js" type="module"></script>
Then you can use blocks in your application markup.
File uploader example:
<lr-file-uploader-regular
- css-src="https://unpkg.com/@uploadcare/blocks@0.30.4/web/file-uploader-regular.min.css"
+ css-src="https://unpkg.com/@uploadcare/blocks@0.30.5/web/file-uploader-regular.min.css"
>
</lr-file-uploader-regular>
@@ -98,20 +98,20 @@ Dynamic script connection (type
Then use connectBlocksFrom
function to connect blocks:
import { connectBlocksFrom } from '@uploadcare/blocks/abstract/connectBlocksFrom.js';
-connectBlocksFrom('https://unpkg.com/@uploadcare/blocks@0.30.4/web/blocks-browser.min.js');
+connectBlocksFrom('https://unpkg.com/@uploadcare/blocks@0.30.5/web/blocks-browser.min.js');
That's it! Now you can use components for placing into html, like this:
<lr-file-uploader-inline
- css-src="https://unpkg.com/@uploadcare/blocks@0.30.4/web/file-uploader-inline.min.css"
+ css-src="https://unpkg.com/@uploadcare/blocks@0.30.5/web/file-uploader-inline.min.css"
class="my-config-class"
></lr-file-uploader-inline>
You may need to implement some logic, which depends on connected blocks or get access directly to the imported components. Since connectBlocksFrom
returns Promise
, place all you need using .then()
import { connectBlocksFrom } from '@uploadcare/blocks/abstract/connectBlocksFrom.js';
-const STYLES = 'https://unpkg.com/@uploadcare/blocks@0.30.4/web/file-uploader-regular.min.css';
+const STYLES = 'https://unpkg.com/@uploadcare/blocks@0.30.5/web/file-uploader-regular.min.css';
-connectBlocksFrom('https://unpkg.com/@uploadcare/blocks@0.30.4/web/blocks-browser.min.js').then(
+connectBlocksFrom('https://unpkg.com/@uploadcare/blocks@0.30.5/web/blocks-browser.min.js').then(
(blocks) => {
if (!blocks) {
return; // To avoid errors in SSR case
diff --git a/index.html b/index.html
index f9602b1f6..9360b0e53 100644
--- a/index.html
+++ b/index.html
@@ -108,19 +108,19 @@ Typescript support
🚀 Getting started
From CDN
-- Connect Uploadcare Blocks directly from your document replacing
0.30.4
with the latest version of the package:
+- Connect Uploadcare Blocks directly from your document replacing
0.30.5
with the latest version of the package:
<script type="module">
- import * as LR from 'https://cdn.jsdelivr.net/npm/@uploadcare/blocks@0.30.4/web/blocks.min.js';
+ import * as LR from 'https://cdn.jsdelivr.net/npm/@uploadcare/blocks@0.30.5/web/blocks.min.js';
LR.registerBlocks(LR);
</script>
-- Start using Uploadcare Blocks in your application markup (don't forget to specify
0.30.4
with the latest one):
+- Start using Uploadcare Blocks in your application markup (don't forget to specify
0.30.5
with the latest one):
<lr-file-uploader-regular
- css-src="https://cdn.jsdelivr.net/npm/@uploadcare/blocks@0.30.4/web/lr-file-uploader-regular.min.css"
+ css-src="https://cdn.jsdelivr.net/npm/@uploadcare/blocks@0.30.5/web/lr-file-uploader-regular.min.css"
ctx-name="my-uploader"
>
</lr-file-uploader-regular>
@@ -138,10 +138,10 @@ From NPM
LR.registerBlocks(LR);
-- Start using Uploadcare Blocks in your application markup and replace
0.30.4
with the latest version of the package:
+- Start using Uploadcare Blocks in your application markup and replace
0.30.5
with the latest version of the package:
<lr-file-uploader-inline
- css-src="https://cdn.jsdelivr.net/npm/@uploadcare/blocks@0.30.4/web/lr-file-uploader-inline.min.css"
+ css-src="https://cdn.jsdelivr.net/npm/@uploadcare/blocks@0.30.5/web/lr-file-uploader-inline.min.css"
ctx-name="my-uploader"
>
</lr-file-uploader-inline>
diff --git a/package-lock.json b/package-lock.json
index 503528be6..5abff15c2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@uploadcare/blocks",
- "version": "0.30.4",
+ "version": "0.30.5",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@uploadcare/blocks",
- "version": "0.30.4",
+ "version": "0.30.5",
"license": "MIT",
"dependencies": {
"@symbiotejs/symbiote": "^1.11.7",
diff --git a/package.json b/package.json
index a8a1004cb..f8730accb 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@uploadcare/blocks",
- "version": "0.30.4",
+ "version": "0.30.5",
"description": "Building blocks for Uploadcare products integration",
"keywords": [
"web components",
diff --git a/solutions/adaptive-image/index.html b/solutions/adaptive-image/index.html
index 4c08ecad0..688cf71f1 100644
--- a/solutions/adaptive-image/index.html
+++ b/solutions/adaptive-image/index.html
@@ -72,7 +72,7 @@ 💎 Solution benefits
Quick start
Connect script:
-<script src="https://unpkg.com/@uploadcare/blocks@0.30.4/web/lr-img.min.js" type="module"></script>
+<script src="https://unpkg.com/@uploadcare/blocks@0.30.5/web/lr-img.min.js" type="module"></script>
Add basic settings:
lr-img {
diff --git a/solutions/file-uploader/index.html b/solutions/file-uploader/index.html
index 0fefa5679..0f48c389c 100644
--- a/solutions/file-uploader/index.html
+++ b/solutions/file-uploader/index.html
@@ -115,7 +115,7 @@ 🛠Configuration
General
All configurations, localization texts, icons, and styling are placed into CSS file (if you aren't familiar with this concept, read about blocks configuration), so you should connect the default one (or create your own):
<style>
- @import url(https://unpkg.com/@uploadcare/blocks@0.30.4/web/file-uploader-regular.min.css);
+ @import url(https://unpkg.com/@uploadcare/blocks@0.30.5/web/file-uploader-regular.min.css);
.my-settings {
--ctx-name: 'my-uploader';
--cfg-pubkey: 'demopublickey';
@@ -431,7 +431,7 @@ Component styles
Shadow DOM
If you need additional isolation and styling security levels, you can get it with Shadow DOM.
To enable it and encapsulate all styles into separated scope, use the css-src
attribute:
-<lr-uploader css-src="https://unpkg.com/@uploadcare/blocks@0.30.4/web/file-uploader-regular.min.css">
+<lr-uploader css-src="https://unpkg.com/@uploadcare/blocks@0.30.5/web/file-uploader-regular.min.css">
</lr-uploader>
diff --git a/web/blocks.iife.min.js b/web/blocks.iife.min.js
index 4a9fb5ff8..26efb092d 100644
--- a/web/blocks.iife.min.js
+++ b/web/blocks.iife.min.js
@@ -24,4 +24,4 @@
*
*/
"use strict";var LR=(()=>{var Ie=Object.defineProperty;var Nr=Object.getOwnPropertyDescriptor;var Dr=Object.getOwnPropertyNames;var Fr=Object.prototype.hasOwnProperty;var Vr=(s,i,t)=>i in s?Ie(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var l=(s,i)=>Ie(s,"name",{value:i,configurable:!0});var Br=(s,i)=>{for(var t in i)Ie(s,t,{get:i[t],enumerable:!0})},zr=(s,i,t,e)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Dr(i))!Fr.call(s,r)&&r!==t&&Ie(s,r,{get:()=>i[r],enumerable:!(e=Nr(i,r))||e.enumerable});return s};var jr=s=>zr(Ie({},"__esModule",{value:!0}),s);var u=(s,i,t)=>(Vr(s,typeof i!="symbol"?i+"":i,t),t);var Qo={};Br(Qo,{ActivityBlock:()=>b,ActivityHeader:()=>ni,BaseComponent:()=>Lt,Block:()=>y,CameraSource:()=>ue,CloudImageEditor:()=>li,CloudImageEditorActivity:()=>si,CloudImageEditorBlock:()=>tt,Config:()=>lr,ConfirmationDialog:()=>pe,Copyright:()=>$e,CropFrame:()=>ge,Data:()=>E,DataOutput:()=>rs,DropArea:()=>Bt,EditorCropButtonControl:()=>Xt,EditorFilterControl:()=>kt,EditorImageCropper:()=>ye,EditorImageFader:()=>ii,EditorOperationControl:()=>qt,EditorScroller:()=>ve,EditorSlider:()=>be,EditorToolbar:()=>Ce,ExternalSource:()=>Ee,FileItem:()=>it,FilePreview:()=>Ht,FileUploaderInline:()=>Oe,FileUploaderMinimal:()=>ke,FileUploaderRegular:()=>Se,Icon:()=>Dt,Img:()=>Ke,LineLoaderUi:()=>we,LrBtnUi:()=>Gt,MessageBox:()=>ae,Modal:()=>jt,PACKAGE_NAME:()=>Yi,PACKAGE_VERSION:()=>Zi,PresenceToggle:()=>Te,ProgressBar:()=>me,ProgressBarCommon:()=>fe,Select:()=>Ae,ShadowWrapper:()=>Yt,SimpleBtn:()=>Vt,SliderUi:()=>xe,SourceBtn:()=>zt,SourceList:()=>Ye,StartFrom:()=>oe,Tabs:()=>Kt,UploadCtxProvider:()=>yr,UploadDetails:()=>de,UploadList:()=>ce,UploaderBlock:()=>v,UrlSource:()=>he,Video:()=>Z,connectBlocksFrom:()=>Pr,registerBlocks:()=>Oi,shadowed:()=>oi,toKebabCase:()=>rt});var Hr=Object.defineProperty,Wr=l((s,i,t)=>i in s?Hr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,"__defNormalProp"),Ri=l((s,i,t)=>(Wr(s,typeof i!="symbol"?i+"":i,t),t),"__publicField");function Xr(s){let i=l(t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}},"clone");return i(s)}l(Xr,"cloneObj");var E=l(class{constructor(s){s.constructor===Object?this.store=Xr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}},"Data");E.globalStore=new Map;var w=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"}),as="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",qr=as.length-1,Re=l(class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{ai&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}l(Gr,"kebabToCamel");function Kr(s,i){[...s.querySelectorAll(`[${w.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(w.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=l(class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}},"itemClass");let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(w.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],c,h=l(d=>{d.forEach((f,g)=>{if(a[g])if(a[g].set$)setTimeout(()=>{a[g].set$(f)});else for(let m in f)a[g][m]=f[m];else{c||(c=new DocumentFragment);let m=new r;Object.assign(m.init$,f),c.appendChild(m)}}),c&&t.appendChild(c);let p=a.slice(d.length,a.length);for(let f of p)f.remove()},"fillItems");if(o.constructor===Array)h(o);else if(o.constructor===Object){let d=[];for(let p in o){let f=o[p];Object.defineProperty(f,"_KEY_",{value:p,enumerable:!0}),d.push(f)}h(d)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(w.REPEAT_ATTR),t.removeAttribute(w.REPEAT_ITEM_TAG_ATTR)})}l(Kr,"repeatProcessor");var os="__default__";function Yr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||os;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=os;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}l(Yr,"slotProcessor");function Zr(s,i){[...s.querySelectorAll(`[${w.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(w.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(w.EL_REF_ATTR)})}l(Zr,"refProcessor");function Jr(s,i){[...s.querySelectorAll(`[${w.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(w.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Gr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(d=>d.trim()),a=o[0],c;a.indexOf(w.ATTR_BIND_PRFX)===0&&(c=!0,a=a.replace(w.ATTR_BIND_PRFX,""));let h=o[1].split(",").map(d=>d.trim());for(let d of h){let p;d.startsWith("!!")?(p="double",d=d.replace("!!","")):d.startsWith("!")&&(p="single",d=d.replace("!","")),i.sub(d,f=>{p==="double"?f=!!f:p==="single"&&(f=!f),c?(f==null?void 0:f.constructor)===Boolean?f?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,f):cs(t,a,f)||(t[w.SET_LATER_KEY]||(t[w.SET_LATER_KEY]=Object.create(null)),t[w.SET_LATER_KEY][a]=f)})}}),t.removeAttribute(w.BIND_ATTR)})}l(Jr,"domSetProcessor");var ai="{{",Le="}}",Qr="skip-text";function tn(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Qr))&&r.textContent.includes(ai)&&r.textContent.includes(Le)&&1}});for(;i=e.nextNode();)t.push(i);return t}l(tn,"getTextNodesWithTokens");var en=l(function(s,i){tn(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(Le);)e.textContent.startsWith(ai)?(n=e.textContent.indexOf(Le)+Le.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(ai),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let a=o.textContent.replace(ai,"").replace(Le,"");o.textContent="",i.sub(a,c=>{o.textContent=c})})})},"txtNodesProcessor"),sn=[Kr,Yr,Zr,Jr,en],ci="'",Jt='"',rn=/\\([0-9a-fA-F]{1,6} ?)/g;function nn(s){return(s[0]===Jt||s[0]===ci)&&(s[s.length-1]===Jt||s[s.length-1]===ci)}l(nn,"hasLeadingTrailingQuotes");function on(s){return(s[0]===Jt||s[0]===ci)&&(s=s.slice(1)),(s[s.length-1]===Jt||s[s.length-1]===ci)&&(s=s.slice(0,-1)),s}l(on,"trimQuotes");function ln(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\
-`,"\\n"),i=ln(i),i=Jt+i+Jt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}l(an,"parseCssPropertyValue");var ls=0,Zt=null,mt=null,Ct=l(class extends HTMLElement{constructor(){super(),Ri(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 Ct}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(w.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=l(()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()},"addFr");if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Re.generate(),this.style.setProperty(w.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(w.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(w.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(w.EXT_DATA_CTX_PRFX,"");else if(s.includes(w.NAMED_DATA_CTX_SPLTR)){let r=s.split(w.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=l(n=>{this.isConnected&&i(n)},"subCb"),r=Ct.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=Ct.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=Ct.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=Ct.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=Ct.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=Ct.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(w.CTX_OWNER_ATTR)&&this.getAttribute(w.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(w.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(w.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(w.NAMED_DATA_CTX_SPLTR)){let t=i.split(w.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(w.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[w.SET_LATER_KEY]){for(let t in this[w.SET_LATER_KEY])cs(this,t,this[w.SET_LATER_KEY][t]);delete this[w.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of sn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${w.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(w.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);mt==null||mt.delete(this.updateCssData),mt!=null&&mt.size||(Zt==null||Zt.disconnect(),Zt=null,mt=null)},100)))}static reg(s,i=!1){s||(ls++,s=`${w.AUTO_TAG_PRFX}-${ls}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" 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(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=an(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){mt||(mt=new Set),mt.add(this.updateCssData),Zt||(Zt=new MutationObserver(s=>{s[0].type==="attributes"&&mt.forEach(i=>{i()})}),Zt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},"_BaseComponent"),Lt=Ct;Ri(Lt,"template");var Li=l(class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Li.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Li.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}},"AppRouter");Li.appMap=Object.create(null);function Ui(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}l(Ui,"applyStyles");function cn(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}l(cn,"applyAttributes");function Ue(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&cn(i,s.attributes),s.styles&&Ui(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Ue(t);i.appendChild(e)}),i}l(Ue,"create");var hs="idb-store-ready",hn="symbiote-db",un="symbiote-idb-update_",dn=l(class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(hs,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return un+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,a)=>{n.onsuccess=c=>{t||this._notifySubscribers(s),o(c.target.result)},n.onerror=c=>{a(c)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,us.clear(this.name)}},"DbInstance"),us=l(class{static get readyEventName(){return hs}static open(s=hn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new dn(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}},"IDB");Ri(us,"_reg",Object.create(null));var k=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),pn=Object.freeze({[k.UPLOAD_START]:"LR_UPLOAD_START",[k.REMOVE]:"LR_REMOVE",[k.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[k.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[k.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[k.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[k.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[k.DATA_OUTPUT]:"LR_DATA_OUTPUT",[k.DONE_FLOW]:"LR_DONE_FLOW",[k.INIT_FLOW]:"LR_INIT_FLOW"}),Pe=class{constructor(i){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));let e=pn[i];window.dispatchEvent(new CustomEvent(e,{detail:{ctx:this._getCtxName(),type:e,data:t}}))}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};l(Pe,"EventEmitter");function O(s,i){let t,e=l((...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)},"debounced");return e.cancel=()=>{clearTimeout(t)},e}l(O,"debounce");var ds="--uploadcare-blocks-window-height",wt=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(ds)}};l(wt,"WindowHeightTracker"),u(wt,"clientsRegistry",new Set),u(wt,"flush",O(()=>{document.documentElement.style.setProperty(ds,`${window.innerHeight}px`)},100));var hi=l((s,i)=>new Intl.PluralRules(s).select(i),"getPluralForm");var fn=l(s=>s,"DEFAULT_TRANSFORMER"),Pi="{{",fs="}}",ps="plural:";function Me(s,i,t={}){var o;let{openToken:e=Pi,closeToken:r=fs,transform:n=fn}=t;for(let a in i){let c=(o=i[a])==null?void 0:o.toString();s=s.replaceAll(e+a+r,typeof c=="string"?n(c):c)}return s}l(Me,"applyTemplateData");function ms(s){let i=[],t=s.indexOf(Pi);for(;t!==-1;){let e=s.indexOf(fs,t),r=s.substring(t+2,e);if(r.startsWith(ps)){let n=s.substring(t+2,e).replace(ps,""),o=n.substring(0,n.indexOf("(")),a=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:a})}t=s.indexOf(Pi,e)}return i}l(ms,"getPluralObjects");var rt=l(s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")},"toKebabCase");var ui=l(({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=setTimeout(()=>{c.disconnect(),e()},r),o=l(h=>{let d=s.getAttribute(i);h.type==="attributes"&&h.attributeName===i&&d!==null&&(clearTimeout(n),c.disconnect(),t(d))},"handleMutation"),a=s.getAttribute(i);a!==null&&(clearTimeout(n),t(a));let c=new MutationObserver(h=>{let d=h[h.length-1];o(d)});c.observe(s,{attributes:!0,attributeFilter:[i]})},"waitForAttribute");var gs=new Set;function Ne(s){gs.has(s)||(gs.add(s),console.warn(s))}l(Ne,"warnOnce");function bs(s){return Object.prototype.toString.call(s)==="[object Object]"}l(bs,"isObject");var mn=/\W|_/g;function gn(s){return s.split(mn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}l(gn,"camelizeString");function _s(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>_t(t,{ignoreKeys:i})):s}l(_s,"camelizeArrayItems");function _t(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return _s(s,{ignoreKeys:i});if(!bs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}bs(r)?r=_t(r,{ignoreKeys:i}):Array.isArray(r)&&(r=_s(r,{ignoreKeys:i})),t[gn(e)]=r}return t}l(_t,"camelizeKeys");var bn=l(s=>new Promise(i=>setTimeout(i,s)),"delay");function Fi({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),a=[n,r].filter(Boolean).join("; ");return`${o} (${a})`}l(Fi,"getUserAgent$1");var _n={factor:2,time:100};function yn(s,i=_n){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l(a=>bn(a!=null?a:n).then(()=>(t+=1,e(r))),"retry")})}return l(e,"runAttempt"),e(s)}l(yn,"retrier");var Rt=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Rt.prototype),this.originalProgressEvent=t}};l(Rt,"UploadcareNetworkError");var mi=l((s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},"onCancel"),gt=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,gt.prototype)}};l(gt,"CancelError");var vn=500,vs=l(({check:s,interval:i=vn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,a;mi(e,()=>{o&&clearTimeout(o),n(new gt("Poll cancelled"))}),t&&(a=setTimeout(()=>{o&&clearTimeout(o),n(new gt("Timed out"))},t));let c=l(()=>{try{Promise.resolve(s(e)).then(h=>{h?(a&&clearTimeout(a),r(h)):o=setTimeout(c,i)}).catch(h=>{a&&clearTimeout(a),n(h)})}catch(h){a&&clearTimeout(a),n(h)}},"tick");o=setTimeout(c,0)}),"poll"),$={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"},gi="application/octet-stream",Cs="original",Tt=l(({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,a)=>{let c=new XMLHttpRequest,h=(s==null?void 0:s.toUpperCase())||"GET",d=!1;c.open(h,i,!0),e&&Object.entries(e).forEach(p=>{let[f,g]=p;typeof g!="undefined"&&!Array.isArray(g)&&c.setRequestHeader(f,g)}),c.responseType="text",mi(r,()=>{d=!0,c.abort(),a(new gt)}),c.onload=()=>{if(c.status!=200)a(new Error(`Error ${c.status}: ${c.statusText}`));else{let p={method:h,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},f=c.getAllResponseHeaders().trim().split(/[\r\n]+/),g={};f.forEach(function(S){let A=S.split(": "),x=A.shift(),T=A.join(": ");x&&typeof x!="undefined"&&(g[x]=T)});let m=c.response,_=c.status;o({request:p,data:m,headers:g,status:_})}},c.onerror=p=>{d||a(new Rt(p))},n&&typeof n=="function"&&(c.upload.onprogress=p=>{p.lengthComputable?n({isComputable:!0,value:p.loaded/p.total}):n({isComputable:!1})}),t?c.send(t):c.send()}),"request");function Cn(s,...i){return s}l(Cn,"identity");var wn=l(({name:s})=>s?[s]:[],"getFileOptions"),Tn=Cn,xn=l(()=>new FormData,"getFormData"),ws=l(s=>!1,"isBuffer"),bi=l(s=>typeof Blob!="undefined"&&s instanceof Blob,"isBlob"),_i=l(s=>typeof File!="undefined"&&s instanceof File,"isFile"),yi=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string","isReactNativeAsset"),Qt=l(s=>bi(s)||_i(s)||ws()||yi(s),"isFileData"),En=l(s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined","isSimpleValue"),An=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s),"isObjectValue"),$n=l(s=>!!s&&typeof s=="object"&&"data"in s&&Qt(s.data),"isFileValue");function Sn(s,i,t){if($n(t)){let{name:e,contentType:r}=t,n=Tn(t.data,e,r!=null?r:gi),o=wn({name:e,contentType:r});s.push([i,n,...o])}else if(An(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else En(t)&&t&&s.push([i,t.toString()])}l(Sn,"collectParams");function kn(s){let i=[];for(let[t,e]of Object.entries(s))Sn(i,t,e);return i}l(kn,"getFormDataParams");function Vi(s){let i=xn(),t=kn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}l(Vi,"buildFormData");var U=class extends Error{constructor(t,e,r,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,U.prototype)}};l(U,"UploadClientError");var On=l(s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},"buildSearchParams"),bt=l((s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=On(t)),e.toString()},"getUrl"),In="6.8.0",Ln="UploadcareUploadClient",Rn=In;function Ut(s){return Fi({libraryName:Ln,libraryVersion:Rn,...s})}l(Ut,"getUserAgent");var Un="RequestThrottledError",ys=15e3,Pn=1e3;function Mn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return ys;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:ys}l(Mn,"getTimeoutFromThrottledRequest");function xt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return yn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Un&&r{let i="";return(bi(s)||_i(s)||yi(s))&&(i=s.type),i||gi},"getContentType"),xs=l(s=>{let i="";return _i(s)&&s.name?i=s.name:bi(s)||ws()?i="":yi(s)&&s.name&&(i=s.name),i||Cs},"getFileName");function Bi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}l(Bi,"getStoreValue");function Nn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=$.baseURL,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=$.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:bt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:p,userAgent:f})},data:Vi({file:{data:s,name:t||xs(s),contentType:e||Ts(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Bi(a),signature:n,expire:o,source:d,metadata:_}),signal:c,onProgress:h}).then(({data:S,headers:A,request:x})=>{let T=_t(JSON.parse(S));if("error"in T)throw new U(T.error.content,T.error.errorCode,x,T,A);return T}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(Nn,"base");var Di;(function(s){s.Token="token",s.FileInfo="file_info"})(Di||(Di={}));function Dn(s,{publicKey:i,baseURL:t=$.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,source:h="url",signal:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=$.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:p,userAgent:f})},url:bt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Bi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:a,expire:c,source:h,metadata:_}),signal:d}).then(({data:S,headers:A,request:x})=>{let T=_t(JSON.parse(S));if("error"in T)throw new U(T.error.content,T.error.errorCode,x,T,A);return T}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(Dn,"fromUrl");var H;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(H||(H={}));var Fn=l(s=>"status"in s&&s.status===H.Error,"isErrorResponse");function Vn(s,{publicKey:i,baseURL:t=$.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=$.retryNetworkErrorMaxTimes}={}){return xt(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Ut({publicKey:i,integration:r,userAgent:n})}:void 0,url:bt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:c,headers:h,request:d})=>{let p=_t(JSON.parse(c));if("error"in p&&!Fn(p))throw new U(p.error.content,void 0,d,p,h);return p}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:o})}l(Vn,"fromUrlStatus");function Bn(s,{publicKey:i,baseURL:t=$.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:a,integration:c,userAgent:h,retryThrottledRequestMaxTimes:d=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=$.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:c,userAgent:h})},url:bt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:a}),signal:o}).then(({data:f,headers:g,request:m})=>{let _=_t(JSON.parse(f));if("error"in _)throw new U(_.error.content,_.error.errorCode,m,_,g);return _}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:d})}l(Bn,"group");function Es(s,{publicKey:i,baseURL:t=$.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=$.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:n,userAgent:o})},url:bt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:h,headers:d,request:p})=>{let f=_t(JSON.parse(h));if("error"in f)throw new U(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Es,"info");function zn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=$.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:a,store:c,signal:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=$.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:bt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:p,userAgent:f})},data:Vi({filename:e||Cs,size:s,content_type:t||gi,part_size:r,UPLOADCARE_STORE:Bi(c),UPLOADCARE_PUB_KEY:i,signature:o,expire:a,source:d,metadata:_}),signal:h}).then(({data:S,headers:A,request:x})=>{let T=_t(JSON.parse(S));if("error"in T)throw new U(T.error.content,T.error.errorCode,x,T,A);return T.parts=Object.keys(T.parts).map(z=>T.parts[z]),T}),{retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})}l(zn,"multipartStart");function jn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=$.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||gi}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}l(jn,"multipartUpload");function Hn(s,{publicKey:i,baseURL:t=$.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=$.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",url:bt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:n,userAgent:o})},data:Vi({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:h,headers:d,request:p})=>{let f=_t(JSON.parse(h));if("error"in f)throw new U(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Hn,"multipartComplete");function zi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a,signal:c,onProgress:h}){return vs({check:d=>Es(s,{publicKey:i,baseURL:t,signal:d,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a}).then(p=>p.isReady?p:(h&&h({isComputable:!0,value:1}),!1)),signal:c})}l(zi,"isReadyPoll");function Wn(s){return"defaultEffects"in s}l(Wn,"isGroupFileInfo");var nt=class{constructor(i,{baseCDN:t=$.baseCDN,fileName:e}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);u(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=bt(t,`${r}/`),a=n?bt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=a,Wn(i)&&(this.defaultEffects=i.defaultEffects)}};l(nt,"UploadcareFile");var Xn=l((s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,baseCDN:_,metadata:S})=>Nn(s,{publicKey:i,fileName:t,contentType:a,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:S}).then(({file:A})=>zi(A,{publicKey:i,baseURL:e,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then(A=>new nt(A,{baseCDN:_})),"uploadDirect"),qn=l((s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d,baseCDN:p})=>Es(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d}).then(f=>new nt(f,{baseCDN:p,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),"uploadFromUploaded"),Gn=l((s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=l(o=>()=>{e=o,r.forEach((a,c)=>c!==o&&a.abort())},"createStopRaceCallback");return mi(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,a)=>{let c=n(a);return Promise.resolve().then(()=>o({stopRace:c,signal:r[a].signal})).then(h=>(c(),h)).catch(h=>(t=h,null))})).then(o=>{if(e===null)throw t;return o[e]})},"race"),Kn=window.WebSocket,di=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}};l(di,"Events");var Yn=l((s,i)=>s==="success"?{status:H.Success,...i}:s==="progress"?{status:H.Progress,...i}:{status:H.Error,...i},"response"),pi=class{constructor(i,t=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 di);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Kn(i),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 e=JSON.parse(t.data.toString());switch(e.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(e.channel,Yn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=l(()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1},"actualDisconect");this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}};l(pi,"Pusher");var Mi=null,ji=l(s=>{if(!Mi){let i=typeof window=="undefined"?0:3e4;Mi=new pi(s,i)}return Mi},"getPusher"),Zn=l(s=>{ji(s).connect()},"preconnect");function Jn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:a,signal:c}){return vs({check:h=>Vn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:h}).then(d=>{switch(d.status){case H.Error:return new U(d.error,d.errorCode);case H.Waiting:return!1;case H.Unknown:return new U(`Token "${s}" was not found.`);case H.Progress:return a&&(d.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:d.done/d.total})),!1;case H.Success:return a&&a({isComputable:!0,value:d.done/d.total}),d;default:throw new Error("Unknown status")}}),signal:c})}l(Jn,"pollStrategy");var Qn=l(({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=ji(i),a=o.onError(n),c=l(()=>{a(),o.unsubscribe(s)},"destroy");mi(t,()=>{c(),n(new gt("pusher cancelled"))}),o.subscribe(s,h=>{switch(h.status){case H.Progress:{e&&(h.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:h.done/h.total}));break}case H.Success:{c(),e&&e({isComputable:!0,value:h.done/h.total}),r(h);break}case H.Error:c(),n(new U(h.msg,h.error_code))}})}),"pushStrategy"),to=l((s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,onProgress:p,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:_,pusherKey:S=$.pusherKey,metadata:A})=>Promise.resolve(Zn(S)).then(()=>Dn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:_,metadata:A})).catch(x=>{let T=ji(S);return T==null||T.disconnect(),Promise.reject(x)}).then(x=>x.type===Di.FileInfo?x:Gn([({signal:T})=>Jn({token:x.token,publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:_,onProgress:p,signal:T}),({signal:T})=>Qn({token:x.token,pusherKey:S,signal:T,onProgress:p})],{signal:d})).then(x=>{if(x instanceof U)throw x;return x}).then(x=>zi(x.uuid,{publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:_,onProgress:p,signal:d})).then(x=>new nt(x,{baseCDN:r})),"uploadFromUrl"),Ni=new WeakMap,eo=l(async s=>{if(Ni.has(s))return Ni.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Ni.set(s,i),i},"getBlobFromReactNativeAsset"),As=l(async s=>{if(_i(s)||bi(s))return s.size;if(yi(s))return(await eo(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},"getFileSize"),io=l((s,i=$.multipartMinFileSize)=>s>=i,"isMultipart"),$s=l(s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Qt(s)&&t.test(s)},"isUuid"),Hi=l(s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Qt(s)&&t.test(s)},"isUrl"),so=l((s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,a=[...i],c=l(()=>{let h=i.length-a.length,d=a.shift();d&&d().then(p=>{n||(r[h]=p,o-=1,o?c():t(r))}).catch(p=>{n=!0,e(p)})},"run");for(let h=0;h{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},"sliceChunk"),no=l(async(s,i,t)=>e=>ro(s,e,i,t),"prepareChunks"),oo=l((s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})=>jn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c}),"uploadPart"),lo=l(async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,contentType:_,multipartChunkSize:S=$.multipartChunkSize,maxConcurrentRequests:A=$.maxConcurrentRequests,baseCDN:x,metadata:T})=>{let z=e!=null?e:await As(s),pt,It=l((M,j)=>{if(!h)return;pt||(pt=Array(M).fill(0));let et=l(st=>st.reduce((ft,Ii)=>ft+Ii,0),"sum");return st=>{st.isComputable&&(pt[j]=st.value,h({isComputable:!0,value:et(pt)/M}))}},"createProgressHandler");return _||(_=Ts(s)),zn(z,{publicKey:i,contentType:_,fileName:t||xs(s),baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:T}).then(async({uuid:M,parts:j})=>{let et=await no(s,z,S);return Promise.all([M,so(A,j.map((st,ft)=>()=>oo(et(ft),st,{publicKey:i,contentType:_,onProgress:It(j.length,ft),signal:c,integration:p,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})))])}).then(([M])=>Hn(M,{publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})).then(M=>M.isReady?M:zi(M.uuid,{publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then(M=>new nt(M,{baseCDN:x}))},"uploadMultipart");async function Wi(s,{publicKey:i,fileName:t,baseURL:e=$.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartMinFileSize:_,multipartChunkSize:S,maxConcurrentRequests:A,baseCDN:x=$.baseCDN,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:z,pusherKey:pt,metadata:It}){if(Qt(s)){let M=await As(s);return io(M,_)?lo(s,{publicKey:i,contentType:m,multipartChunkSize:S,fileSize:M,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x,metadata:It}):Xn(s,{publicKey:i,fileName:t,contentType:m,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x,metadata:It})}if(Hi(s))return to(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:x,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:z,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,pusherKey:pt,metadata:It});if($s(s))return qn(s,{publicKey:i,fileName:t,baseURL:e,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x});throw new TypeError(`File uploading from "${s}" is not supported`)}l(Wi,"uploadFile");var fi=class{constructor(i,{baseCDN:t=$.baseCDN}={}){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new nt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}};l(fi,"UploadcareGroup");var ao=l(s=>{for(let i of s)if(!Qt(i))return!1;return!0},"isFileDataArray"),co=l(s=>{for(let i of s)if(!$s(i))return!1;return!0},"isUuidArray"),ho=l(s=>{for(let i of s)if(!Hi(i))return!1;return!0},"isUrlArray");function Ss(s,{publicKey:i,fileName:t,baseURL:e=$.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:_=$.multipartChunkSize,baseCDN:S=$.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x,jsonpCallback:T}){if(!ao(s)&&!ho(s)&&!co(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let z,pt=!0,It=s.length,M=l((j,et)=>{if(!c)return;z||(z=Array(j).fill(0));let st=l(ft=>ft.reduce((Ii,Mr)=>Ii+Mr)/j,"normalize");return ft=>{if(!ft.isComputable||!pt){pt=!1,c({isComputable:!1});return}z[et]=ft.value,c({isComputable:!0,value:st(z)})}},"createProgressHandler");return Promise.all(s.map((j,et)=>Qt(j)||Hi(j)?Wi(j,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:M(It,et),source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:_,baseCDN:S,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x}).then(st=>st.uuid):j)).then(j=>Bn(j,{publicKey:i,baseURL:e,jsonpCallback:T,secureSignature:r,secureExpire:n,signal:a,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g}).then(et=>new fi(et,{baseCDN:S})).then(et=>(c&&c({isComputable:!0,value:1}),et)))}l(Ss,"uploadFileGroup");var De=class{constructor(i){u(this,"_concurrency",1);u(this,"_pending",[]);u(this,"_running",0);u(this,"_resolvers",new Map);u(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};l(De,"Queue");var Xi=l(()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),"blockCtx"),qi=l(s=>({...Xi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),"activityBlockCtx"),vi=l(s=>({...qi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new De(1),"*uploadCollection":null}),"uploaderBlockCtx");function ks(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}l(ks,"l10nProcessor");var W=l(s=>`*cfg/${s}`,"sharedConfigKey");var Gi="lr-",y=class extends Lt{constructor(){super();u(this,"requireCtxName",!1);u(this,"allowCustomTemplate",!0);u(this,"init$",Xi());u(this,"updateCtxCssData",l(()=>{Ne("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()},"updateCtxCssData"));this.activityType=null,this.addTemplateProcessor(ks),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=ms(r);for(let a of n)e[a.variable]=this.pluralize(a.pluralKey,Number(e[a.countVariable]));return Me(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=hi(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Gi}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?ui({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),wt.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),wt.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new Pe(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=l(h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h,"getUnit");if(t===0)return`0 ${n(r[0])}`;let o=1024,a=e<0?0:e,c=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**c).toFixed(a))+" "+n(r[c])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Me(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=W(r);return this.$[o]=n,!0},get:(e,r)=>{let n=W(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Ne("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${rt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(W(t));r.ctx.has(r.name)?this.sub(W(t),e):(this.bindCssData(`--cfg-${rt(t)}`),this.sub(`--cfg-${rt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Gi)?t:Gi+t)}};l(y,"Block"),u(y,"StateConsumerScope",null),u(y,"className","");var Os="active",Fe="___ACTIVITY_IS_ACTIVE___",ot=class extends y{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",qi(this));u(this,"_debouncedHistoryFlush",O(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=ot._activityRegistry[this.activityKey];this[Fe]=!1,this.removeAttribute(Os),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=ot._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[Fe]=!0,this.setAttribute(Os,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[Fe]?this._deactivate():this.activityType===t&&!this[Fe]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!ot._activityRegistry[this.activityKey]}get isActivityActive(){return this[Fe]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;ot._activityRegistry||(ot._activityRegistry=Object.create(null)),ot._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),ot._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(ot._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let a=[...this.$["*blocksRegistry"]].find(c=>c.activityType===r);n=(e=a==null?void 0:a.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},b=ot;l(b,"ActivityBlock"),u(b,"_activityRegistry",Object.create(null));b.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Ve=33.333333333333336,C=1,Ki=24,Is=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}l(Pt,"setSvgNodeAttrs");function J(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}l(J,"createSvgNode");function Ls(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=i.includes("w")?0:1,c=i.includes("n")?0:1,h=[-1,1][a],d=[-1,1][c],p=[e+a*n+1.5*h,r+c*o+1.5*d-24*t*d],f=[e+a*n+1.5*h,r+c*o+1.5*d],g=[e+a*n-24*t*h+1.5*h,r+c*o+1.5*d];return{d:`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]} L ${g[0]} ${g[1]}`,center:f}}l(Ls,"cornerPath");function Rs(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=["n","s"].includes(i)?.5:{w:0,e:1}[i],c=["w","e"].includes(i)?.5:{n:0,s:1}[i],h=[-1,1][a],d=[-1,1][c],p,f;["n","s"].includes(i)?(p=[e+a*n-34*t/2,r+c*o+1.5*d],f=[e+a*n+34*t/2,r+c*o+1.5*d]):(p=[e+a*n+1.5*h,r+c*o-34*t/2],f=[e+a*n+1.5*h,r+c*o+34*t/2]);let g=`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]}`,m=[f[0]-(f[0]-p[0])/2,f[1]-(f[1]-p[1])/2];return{d:g,center:m}}l(Rs,"sidePath");function Us(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}l(Us,"thumbCursor");function Ps({rect:s,delta:[i,t],imageBox:e}){return ee({...s,x:s.x+i,y:s.y+t},e)}l(Ps,"moveRect");function ee(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}l(ee,"constraintRect");function uo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:a}=s;n+=r,a-=r,t&&(o=a*t);let c=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,a=s.y+s.height-n,t&&(o=a*t,c=s.x+s.width/2-o/2)),c<=e.x&&(c=e.x,n=s.y+s.height-a),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y+s.height-a),a=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x+s.width-o),a=e.y+e.height&&(a=e.y+e.height-n,t&&(o=a*t),c=s.x+s.width/2-o/2),c<=e.x&&(c=e.x,n=s.y),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y),a=e.x+e.width&&(o=e.x+e.width-n,t&&(a=o/t),c=s.y+s.height/2-a/2),c<=e.y&&(c=e.y,n=s.x),c+a>=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x),at?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x+s.width-c,a=e.y)):t&&(r=h*t-c,c=c+r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y+s.height-h)),he.x+e.width&&(r=e.x+e.width-o-c),a+nt?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x,a=e.y)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y+s.height-h)),he.y+e.height&&(n=e.y+e.height-a-h),o+=r,c-=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x+s.width-c,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y)),he.x+e.width&&(r=e.x+e.width-o-c),a+h+n>e.y+e.height&&(n=e.y+e.height-a-h),c+=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y)),h=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}l(Ds,"isRectInsideRect");function Fs(s,i){return Math.abs(s.width/s.height-i)<.1}l(Fs,"isRectMatchesAspectRatio");function ie({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}l(ie,"rotateSize");function Vs(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),a=Math.round((i-n)/2);return o+r>s&&(r=s-o),a+n>i&&(n=i-a),{x:o,y:a,width:r,height:n}}l(Vs,"calculateMaxCenteredCropFrame");function se(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}l(se,"roundRect");function Et(s,i,t){return Math.min(Math.max(s,i),t)}l(Et,"clamp");var wi=l(s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]},"parseCropPreset");var Q=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Bs=l(s=>s?s.split(",").map(i=>i.trim()):[],"deserealizeCsv"),Mt=l(s=>s?s.join(","):"","serializeCsv");var Yi="blocks",Zi="0.30.4";function zs(s){return Fi({...s,libraryName:Yi,libraryVersion:Zi})}l(zs,"customUserAgent");var js=l(s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},"normalizeCdnOperation"),Ti=l((...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>js(i)).join("/-/"),"joinCdnOperations"),N=l((...s)=>{let i=Ti(...s);return i?`-/${i}/`:""},"createCdnUrlModifiers");function Hs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}l(Hs,"extractFilename");function Ws(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}l(Ws,"extractUuid");function Xs(s){let i=qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>js(n))}l(Xs,"extractOperations");function qs(s){let i=new URL(s),t=Hs(s),e=Gs(t)?Ks(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}l(qs,"trimFilename");function Gs(s){return s.startsWith("http")}l(Gs,"isFileUrl");function Ks(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}l(Ks,"splitFileUrl");var L=l((s,i,t)=>{let e=new URL(qs(s));if(t=t||Hs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Gs(t)){let r=Ks(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},"createCdnUrl"),At=l((s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()},"createOriginalUrl");var D=l((s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0),"stringToArray");var Be=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Ji=l(s=>s?s.filter(i=>typeof i=="string").map(i=>D(i)).flat():[],"mergeFileTypes"),Qi=l((s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),"matchMimeType"),Ys=l((s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),"matchExtension"),ze=l(s=>{let i=s==null?void 0:s.type;return i?Qi(i,Be):!1},"fileIsImage");var at=1e3,Nt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),je=l(s=>Math.ceil(s*100)/100,"round"),Zs=l((s,i=Nt.AUTO)=>{let t=i===Nt.AUTO;if(i===Nt.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Js+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(vo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Js+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};l(He,"TypedData");var We=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Re.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new He(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};l(We,"TypedCollection");var Qs=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:nt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var v=class extends b{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!1);u(this,"isCtxOwner",!1);u(this,"init$",vi(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",O(this._runValidators.bind(this),100));u(this,"_flushOutputItems",O(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(k.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));u(this,"_handleCollectonUpdate",l((t,e,r)=>{var n;this._runValidators();for(let o of r)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()},"_handleCollectonUpdate"));u(this,"_handleCollectionPropertiesUpdate",l(t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(c=>!c.getValue("uploadError"));o.forEach(c=>{n+=e.readProp(c,"uploadProgress")});let a=Math.round(n/o.length);this.$["*commonProgress"]=a,this.emit(k.UPLOAD_PROGRESS,a,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(a=>!!a.getValue("fileInfo")),o=e.findItems(a=>!!a.getValue("uploadError")||!!a.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let a=this.getOutputData(c=>!!c.getValue("fileInfo")&&!c.getValue("silentUpload"));a.length>0&&this.emit(k.UPLOAD_FINISH,a,{debounce:!0})}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(k.UPLOAD_ERROR,e.readProp(o,"uploadError"))}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(k.VALIDATION_ERROR,e.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(k.CLOUD_MODIFICATION,e.readProp(o,"cdnUrlModifiers"))})},"_handleCollectionPropertiesUpdate"))}setUploadMetadata(t){Ne("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof v?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new We({typedSchema:Qs,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Q.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Q.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:ze(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:Q.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:ze(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Mt(Ji([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?Be:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Mt(Be)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Q.LOCAL})),this.$["*currentActivity"]=b.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=D(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":b.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=b.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":b.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":b.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(k.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(k.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Ji([...e?Be:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),a=t.getValue("fileName");if(!o||!a)return;let c=Qi(o,n),h=Ys(a,n);if(!c&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Zs(e)})}_validateMultipleLimit(t){let e=this.uploadCollection.items(),r=e.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&e.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=wi(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:a,height:c}=o.imageInfo,h=e.width/e.height,d=Vs(a,c,h),p=N(`crop/${d.width}x${d.height}/${d.x},${d.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:p,cdnUrl:L(n.getValue("cdnUrl"),p)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===b.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=b.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:zs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,a;let e=E.getCtx(t).store,r=e.fileInfo||{name:e.fileName,originalFilename:e.fileName,size:e.fileSize,isImage:e.isImage,mimeType:e.mimeType};return{...r,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(a=(o=e.cdnUrl)!=null?o:r.cdnUrl)!=null?a:null,validationErrorMessage:e.validationErrorMsg,uploadError:e.uploadError,isUploaded:!!e.uuid&&!!e.fileInfo,isValid:!e.validationErrorMsg&&!e.uploadError,fullPath:e.fullPath,uploadProgress:e.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};l(v,"UploaderBlock");v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});var K={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function Co(s,i){if(typeof i=="number")return K[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&K[s]!==i?`${s}`:"";if(s==="filter"){if(!i||K[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}l(Co,"transformationToStr");var er=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return Ti(...er.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return Co(i,t)}).filter(i=>!!i))}l($t,"transformationsToOperations");var xi=Ti("format/auto","progressive/yes"),yt=l(([s])=>typeof s!="undefined"?Number(s):void 0,"asNumber"),tr=l(()=>!0,"asBoolean"),wo=l(([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),"asFilter"),To=l(([s,i])=>({dimensions:D(s,"x").map(Number),coords:D(i).map(Number)}),"asCrop"),xo={enhance:yt,brightness:yt,exposure:yt,gamma:yt,contrast:yt,saturation:yt,vibrance:yt,warmth:yt,filter:wo,mirror:tr,flip:tr,rotate:yt,crop:To};function ir(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!er.includes(e))continue;let n=xo[e],o=n(r);i[e]=o}return i}l(ir,"operationsToTransformations");var P=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),X=[P.CROP,P.TUNING,P.FILTERS],sr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],rr=["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"],nr=["rotate","mirror","flip"],ct=Object.freeze({brightness:{zero:K.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:K.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:K.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:K.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:K.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:K.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:K.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:K.enhance,range:[0,100],keypointsNumber:1},filter:{zero:K.filter,range:[0,100],keypointsNumber:1}});var Eo="https://ucarecdn.com",Ao="https://upload.uploadcare.com",$o="https://social.uploadcare.com",St={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Mt(X),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Eo,baseUrl:Ao,socialBaseUrl:$o,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var q=l(s=>String(s),"asString"),ht=l(s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},"asNumber"),I=l(s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},"asBoolean"),So=l(s=>s==="auto"?s:I(s),"asStore"),ko={pubkey:q,multiple:I,multipleMin:ht,multipleMax:ht,confirmUpload:I,imgOnly:I,accept:q,externalSourcesPreferredTypes:q,store:So,cameraMirror:I,sourceList:q,maxLocalFileSizeBytes:ht,thumbSize:ht,showEmptyList:I,useLocalImageEditor:I,useCloudImageEditor:I,cloudImageEditorTabs:q,removeCopyright:I,cropPreset:q,modalScrollLock:I,modalBackdropStrokes:I,sourceListWrap:I,remoteTabSessionKey:q,cdnCname:q,baseUrl:q,socialBaseUrl:q,secureSignature:q,secureExpire:q,secureDeliveryProxy:q,retryThrottledRequestMaxTimes:ht,multipartMinFileSize:ht,multipartChunkSize:ht,maxConcurrentRequests:ht,multipartMaxConcurrentRequests:ht,multipartMaxAttempts:ht,checkForUrlDuplicates:I,saveUrlForRecurrentUploads:I,groupOutput:I,userAgentIntegration:q},or=l((s,i)=>{if(!(typeof i=="undefined"||i===null))try{return ko[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),St[s]}},"normalizeConfigValue");var Ei=Object.keys(St),Oo=["metadata"],Io=l(s=>Oo.includes(s),"isComplexKey"),Ai=Ei.filter(s=>!Io(s)),Lo={...Object.fromEntries(Ai.map(s=>[rt(s),s])),...Object.fromEntries(Ai.map(s=>[s.toLowerCase(),s]))},Ro={...Object.fromEntries(Ei.map(s=>[rt(s),W(s)])),...Object.fromEntries(Ei.map(s=>[s.toLowerCase(),W(s)]))},Xe=class extends y{constructor(){super();u(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(St).map(([t,e])=>[W(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of Ai)this.sub(W(e),r=>{r!==St[e]&&(t[e]=r)},!1);for(let e of Ei){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,Ai.includes(e)){let o=[...new Set([rt(e),e.toLowerCase()])];for(let a of o)typeof n=="undefined"||n===null?this.removeAttribute(a):this.setAttribute(a,n.toString())}this.$[W(e)]!==n&&(typeof n=="undefined"||n===null?this.$[W(e)]=St[e]:this.$[W(e)]=n)},get:()=>this.$[W(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Lo[t],o=or(n,r),a=o!=null?o:St[n],c=this;c[n]=a}};l(Xe,"ConfigClass");Xe.bindAttributes(Ro);var lr=Xe;var Dt=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};l(Dt,"Icon");Dt.template=``;Dt.bindAttributes({name:"name",size:"size"});var Uo="https://ucarecdn.com",Ft=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Uo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var ar=l(s=>[...new Set(s)],"uniqueArray");var qe="--lr-img-",cr="unresolved",re=2,ne=3,hr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),dr=Object.create(null),ur;for(let s in Ft)dr[qe+s]=((ur=Ft[s])==null?void 0:ur.default)||"";var Ge=class extends Lt{constructor(){super(...arguments);u(this,"cssInit$",dr)}$$(t){return this.$[qe+t]}set$$(t){for(let e in t)this.$[qe+e]=t[e]}sub$$(t,e){this.sub(qe+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!hr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return N(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Ft.format.default}`,`quality/${this.$$("quality")||Ft.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(hr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return L(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(L(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(L(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(L(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(L(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Me(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),a=r?"":e*Math.round(n.height);return o||a?`${o||""}x${a||""}`:null}_setupEventProxy(t){let e=l(n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},"proxifyEvent"),r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(cr,""),this.img.onload=()=>{this.img.removeAttribute(cr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Ft[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?ar(D(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*re+"x")}") ${n*re}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*ne+"x")}") ${n*ne}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,re))}") ${re}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,ne))}") ${ne}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*re+"x")+` ${e*re}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*ne+"x")+` ${e*ne}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(Ft)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[qe+t]=r})}};l(Ge,"ImgBase");var Ke=class extends Ge{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};l(Ke,"Img");var Vt=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=I(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};l(Vt,"SimpleBtn");Vt.template=` `;Vt.bindAttributes({dropzone:null});var oe=class extends b{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};l(oe,"StartFrom");oe.template=' ';function Po(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=l(r=>{r.type!=="loadend"&&t.abort(),i(!1)},"onLoad");t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}l(Po,"checkIsDirectory");function Mo(s,i){return new Promise(t=>{let e=0,r=[],n=l(a=>{a||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),a.isFile?(e++,a.file(c=>{e--;let h=new File([c],c.name,{type:c.type||i});r.push({type:"file",file:h,fullPath:a.fullPath}),e===0&&t(r)})):a.isDirectory&&o(a.createReader())},"readEntry"),o=l(a=>{e++,a.readEntries(c=>{e--;for(let h of c)n(h);e===0&&t(r)})},"readReaderContent");n(s)})}l(Mo,"readEntryContentAsync");function pr(s){let i=[],t=[];for(let e=0;e{c&&i.push(...c)}));continue}let o=r.getAsFile();o&&t.push(Po(o).then(a=>{a||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}l(pr,"getDropItems");var V={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},fr=["focus"],No=100,ts=new Map;function Do(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}l(Do,"distance");function es(s){let i=0,t=document.body,e=new Set,r=l(m=>e.add(m),"handleSwitch"),n=V.INACTIVE,o=l(m=>{s.shouldIgnore()&&m!==V.INACTIVE||(n!==m&&e.forEach(_=>_(m)),n=m)},"setState"),a=l(()=>i>0,"isDragging");r(m=>s.onChange(m));let c=l(()=>{i=0,o(V.INACTIVE)},"onResetEvent"),h=l(()=>{i+=1,n===V.INACTIVE&&o(V.ACTIVE)},"onDragEnter"),d=l(()=>{i-=1,a()||o(V.INACTIVE)},"onDragLeave"),p=l(m=>{m.preventDefault(),i=0,o(V.INACTIVE)},"onDrop"),f=l(m=>{if(s.shouldIgnore())return;a()||(i+=1);let _=[m.x,m.y],S=s.element.getBoundingClientRect(),A=Math.floor(Do(_,S)),x=A{if(s.shouldIgnore())return;m.preventDefault();let _=await pr(m.dataTransfer);s.onItems(_),o(V.INACTIVE)},"onElementDrop");return t.addEventListener("drop",p),t.addEventListener("dragleave",d),t.addEventListener("dragenter",h),t.addEventListener("dragover",f),s.element.addEventListener("drop",g),fr.forEach(m=>{window.addEventListener(m,c)}),()=>{ts.delete(s.element),t.removeEventListener("drop",p),t.removeEventListener("dragleave",d),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",f),s.element.removeEventListener("drop",g),fr.forEach(m=>{window.removeEventListener(m,c)})}}l(es,"addDropzone");var mr="lr-drop-area",le=`${mr}/registry`,Bt=class extends v{constructor(){super(),this.init$={...this.init$,state:V.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[le]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[le]||(this.$[le]=new Set),this.$[le].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!I(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:I(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:I(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:I(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=es({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Q.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Q.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":b.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=es({element:i,onChange:t=>{var r;let e=(r=Object.entries(V).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(V).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=D(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[le]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[le];i&&(i.delete(this),i.size===0&&E.deleteCtx(mr)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};l(Bt,"DropArea");Bt.template=` {{text}} `;Bt.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Fo="src-type-",zt=class extends v{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"_registeredTypes",{});u(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:b.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:b.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:b.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:b.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:a,activityParams:c={}}=e;this.applyL10nKey("src-type",`${Fo}${r}`),this.$.iconName=n,this.onclick=h=>{(a?a(h):!!o)&&this.set$({"*currentActivityParams":c,"*currentActivity":o})}}};l(zt,"SourceBtn");zt.template=` `;zt.bindAttributes({type:null});var Ye=class extends y{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=D(i),e="";t.forEach(r=>{e+=` `}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};l(Ye,"SourceList");function gr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}l(gr,"createSvgBlobUrl");function br(s="#fff",i="rgba(0, 0, 0, .1)"){return gr(``)}l(br,"checkerboardCssBg");function Ze(s="hsl(209, 21%, 65%)",i=32,t=32){return gr(``)}l(Ze,"fileCssBg");function _r(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,a)=>{r.onload=()=>{let c=r.height/r.width;c>1?(t.width=i,t.height=i*c):(t.height=i,t.width=i/c),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(h=>{if(!h){a();return}let d=URL.createObjectURL(h);o(d)})},r.onerror=c=>{a(c)}});return r.src=URL.createObjectURL(s),n}l(_r,"generateThumb");var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),it=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",O(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",O(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===b.activities.DETAILS)?this.$["*currentActivity"]=b.activities.DETAILS:this.$["*currentActivity"]=b.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);this.emit(k.REMOVE,e,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(L(At(this.cfg.cdnCname,this._entry.getValue("uuid")),N(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await _r(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ze(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ze(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{it.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),it.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),it.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,a;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(c=>!c.getValue("fileInfo"));this.emit(k.UPLOAD_START,r,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let c=new AbortController;t.setValue("abortController",c);let h=l(async()=>{let p=this.getUploadClientOptions();return Wi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...p,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let g=f.value*100;t.setValue("uploadProgress",g)}this.$.progressUnknown=!f.isComputable},signal:c.signal,metadata:await this.getMetadataFor(t.uid)})},"uploadTask"),d=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:d,isUploading:!1,fileName:d.originalFilename,fileSize:d.size,isImage:d.isImage,mimeType:(a=(o=(n=d.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?a:d.mimeType,uuid:d.uuid,cdnUrl:d.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(c){console.warn("Upload error",c),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),c instanceof U?c.isCancel||t.setValue("uploadError",c):t.setValue("uploadError",new Error("Unexpected error"))}}};l(it,"FileItem");it.template=` {{itemName}}{{errorText}} `;it.activeInstances=new Set;var jt=class extends y{constructor(){super();u(this,"_handleBackdropClick",l(()=>{this._closeDialog()},"_handleBackdropClick"));u(this,"_closeDialog",l(()=>{this.setOrAddState("*modalActive",!1)},"_closeDialog"));u(this,"_handleDialogClose",l(()=>{this._closeDialog()},"_handleDialogClose"));u(this,"_handleDialogMouseDown",l(t=>{this._mouseDownTarget=t.target},"_handleDialogMouseDown"));u(this,"_handleDialogMouseUp",l(t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()},"_handleDialogMouseUp"));this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};l(jt,"Modal"),u(jt,"StateConsumerScope","modal");jt.template=``;var Je=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}};l(Je,"UiMessage");var ae=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};l(ae,"MessageBox");ae.template=` {{msgTxt}}`;var ce=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",b.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",O(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));this.emit(k.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var d,p;let t=!!this.cfg.multiple,e=t?(d=this.cfg.multipleMin)!=null?d:0:1,r=t?(p=this.cfg.multipleMax)!=null?p:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!a,tooFew:o,tooMany:a,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Je,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let g of t){let m=this.uploadCollection.read(g);m.getValue("fileInfo")&&!m.getValue("validationErrorMsg")&&(r.succeed+=1),m.getValue("isUploading")&&(r.uploading+=1),(m.getValue("validationErrorMsg")||m.getValue("uploadError"))&&(r.failed+=1),m.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:a}=this._validateFilesCount(),c=r.failed===0&&r.limitOverflow===0,h=!1,d=!1,p=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?h=!0:(d=!0,p=r.total===r.succeed&&n&&c),this.set$({doneBtnVisible:d,doneBtnEnabled:p,uploadBtnVisible:h,addMoreBtnEnabled:r.total===0||!o&&!a,addMoreBtnVisible:!a||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=l(r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})},"localizedText");return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};l(ce,"UploadList");ce.template=`{{headerText}} `;var he=class extends v{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.URL);u(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Q.URL_TAB}),this.$["*currentActivity"]=b.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};l(he,"UrlSource");he.template=` `;var is=l(()=>typeof navigator.permissions!="undefined","canUsePermissionsApi");var ue=class extends v{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.CAMERA);u(this,"_unsubPermissions",null);u(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:is(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});u(this,"_onActivate",l(()=>{is()&&this._subscribePermissions(),this._capture()},"_onActivate"));u(this,"_onDeactivate",l(()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()},"_onDeactivate"));u(this,"_handlePermissionsChange",l(()=>{this._capture()},"_handlePermissionsChange"));u(this,"_setPermissionsState",O(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Q.CAMERA}),this.set$({"*currentActivity":b.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};l(ue,"CameraSource");ue.template=` `;var $i=class extends v{constructor(){super(...arguments);u(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}};l($i,"UploadCtxProviderClass");var yr=$i;var de=class extends v{constructor(){super(...arguments);u(this,"activityType",b.activities.DETAILS);u(this,"pauseRender",!0);u(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=b.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Ze(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=ze(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=l((n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))},"tmpSub");r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let a=L(n,N("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(a))}})})}};l(de,"UploadDetails");de.template=` `;var Si=class{constructor(){u(this,"captionL10nStr","confirm-your-action");u(this,"messageL10Str","are-you-sure");u(this,"confirmL10nStr","yes");u(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}};l(Si,"UiConfirmation");var pe=class extends b{constructor(){super(...arguments);u(this,"activityType",b.activities.CONFIRMATION);u(this,"_defaults",new Si);u(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":b.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};l(pe,"ConfirmationDialog");pe.template=`{{activityCaption}} `;var fe=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};l(fe,"ProgressBarCommon");fe.template=` `;var me=class extends y{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};l(me,"ProgressBar");me.template='';var Y="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Ht=class extends y{constructor(){super();u(this,"init$",{...this.init$,checkerboard:!1,src:Y})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${br()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Y}};l(Ht,"FilePreview");Ht.template=' ';Ht.bindAttributes({checkerboard:"checkerboard"});var vr="--cfg-ctx-name",R=class extends y{get cfgCssCtxName(){return this.getCssData(vr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(vr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};l(R,"CloudImageEditorBase");function Cr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}l(Cr,"normalize");function F(...s){let i=Cr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}l(F,"classNames");function wr(s,...i){let t=Cr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}l(wr,"applyClassNames");var Tr=l(s=>{if(!s)return X;let i=Bs(s).filter(t=>X.includes(t));return i.length===0?X:i},"parseTabs");function xr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":X,"*tabId":P.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Y,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Mt(X),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Y,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=N($t(i),"preview"),r=L(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}l(xr,"initState");var Er=` Network error `;var tt=class extends R{constructor(){super();u(this,"_debouncedShowLoader",O(this._showLoader.bind(this),300));this.init$={...this.init$,...xr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$["*tabId"]===P.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Ws(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Xs(this.$.cdnUrl),r=ir(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=L(this.$["*originalUrl"],N("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===P.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Y&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Y)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=wi(t)}),this.sub("tabs",t=>{this.$["*tabList"]=Tr(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=F("image",{image_hidden_to_cropper:t===P.CROP,image_hidden_effects:t!==P.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=N($t(t),"preview"),n=L(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};l(tt,"CloudImageEditorBlock"),u(tt,"className","cloud-image-editor");tt.template=Er;tt.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ge=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=C&&t.width<=C)return!0;let e=t.height<=C&&(i.includes("n")||i.includes("s")),r=t.width<=C&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],a=J("mask",{id:"backdrop-mask"}),c=J("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=J("rect",{x:t,y:e,width:r,height:n,fill:"black"});a.appendChild(c),a.appendChild(h);let d=J("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(d),o.appendChild(a),this._backdropMask=a,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,a=e==="",c=e.length===2,{x:h,y:d,width:p,height:f}=i;if(a){let m={x:h+p/3,y:d+f/3,width:p/3,height:f/3};Pt(n,m)}else{let m=Et(Math.min(p,f)/(24*2+34)/2,0,1),{d:_,center:S}=c?Ls(i,e,m):Rs(i,e,m),A=Math.max(Ki*Et(Math.min(p,f)/Ki/3,0,1),Is);Pt(n,{x:S[0]-A,y:S[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let g=this._shouldThumbBeDisabled(e);o.setAttribute("class",F("thumb",{"thumb--hidden":g,"thumb--visible":!g}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=J("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=J("rect",{fill:"transparent"}),a=J("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(a),n.appendChild(o),i[r]={direction:r,pathNode:a,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=J("svg"),t=J("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=J("line",{x1:`${Ve*e}%`,y1:"0%",x2:`${Ve*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=J("line",{x1:"0%",y1:`${Ve*e}%`,x2:"100%",y2:`${Ve*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),a=t.x-n,c=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[a,c],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,a=n-this._dragStartPoint[0],c=o-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this._calcCropBox(h,[a,c]);d&&(this.$["*cropBox"]=d)}_calcCropBox(i,t){var h,d;let[e,r]=t,n=this.$["*imageBox"],o=(h=this._dragStartCrop)!=null?h:this.$["*cropBox"],a=(d=this.$["*cropPresetList"])==null?void 0:d[0],c=a?a.width/a.height:void 0;if(i===""?o=Ps({rect:o,delta:[e,r],imageBox:n}):o=Ms({rect:o,delta:[e,r],direction:i,aspectRatio:c,imageBox:n}),!Object.values(o).every(p=>Number.isFinite(p)&&p>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return ee(se(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Ns(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Us(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",F("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=C||i.width<=C,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",F({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};l(ge,"CropFrame");ge.template='';var ut=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=F({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};l(ut,"EditorButtonControl");ut.template=` {{title}}`;function Bo(s){let i=s+90;return i=i>=360?0:i,i}l(Bo,"nextAngle");function zo(s,i){return s==="rotate"?Bo(i):["mirror","flip"].includes(s)?!i:null}l(zo,"nextValue");var Xt=class extends ut{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=zo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};l(Xt,"EditorCropButtonControl");var Qe={FILTER:"filter",COLOR_OPERATION:"color_operation"},dt="original",be=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?Qe.FILTER:Qe.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===dt?void 0:this.$.value,filter:this._filter===dt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ct[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===Qe.FILTER){let a=n;if(o){let{name:c,amount:h}=o;a=c===this._filter?h:n}this.$.value=a,this.$.defaultValue=a}if(this._controlType===Qe.COLOR_OPERATION){let a=typeof o!="undefined"?o:e;this.$.value=a,this.$.defaultValue=a}}apply(){let t;this._controlType===Qe.FILTER?this._filter===dt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};l(be,"EditorSlider");be.template=` `;function ti(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:l(()=>{i.naturalWidth===0&&(i.src=Y)},"cancel")}}l(ti,"preloadImage");function ei(s){let i=[];for(let n of s){let o=ti(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:l(()=>{i.forEach(n=>{n.cancel()})},"cancel")}}l(ei,"batchPreloadImages");var kt=class extends ut{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==dt?{name:this._filter,amount:o}:void 0,L(this._originalUrl,N(xi,$t(a),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:a,cancel:c}=ti(n);this._cancelPreload=c,a.catch(h=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:h})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===dt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};l(kt,"EditorFilterControl");kt.template=` `;var qt=class extends ut{constructor(){super(...arguments);u(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ct[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};l(qt,"EditorOperationControl");var Ar=l((s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}},"throttle");function $r(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}l($r,"pick");function _e(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return L(s,N(xi,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}l(_e,"viewerImageSrc");function jo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}l(jo,"validateCrop");var ye=class extends R{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=O(this._commit.bind(this),300),this._handleResizeThrottled=Ar(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=$r(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=ie({width:i.naturalWidth,height:i.naturalHeight},r),a;if(o.width>n.width-t*2||o.height>n.height-t*2){let c=o.width/o.height,h=n.width/n.height;if(c>h){let d=n.width-t*2,p=d/c,f=0+t,g=t+(n.height-t*2)/2-p/2;a={x:f,y:g,width:d,height:p}}else{let d=n.height-t*2,p=d*c,f=t+(n.width-t*2)/2-p/2,g=0+t;a={x:f,y:g,width:p,height:d}}}else{let{width:c,height:h}=o,d=t+(n.width-t*2)/2-c/2,p=t+(n.height-t*2)/2-h/2;a={x:d,y:p,width:c,height:h}}this.$["*imageBox"]=se(a)}_alignCrop(){var p;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:a,y:c}=this.$["*imageBox"];if(n){let{dimensions:[f,g],coords:[m,_]}=n,{width:S}=ie(this._imageSize,r),A=o/S;i=ee(se({x:a+m*A,y:c+_*A,width:f*A,height:g*A}),this.$["*imageBox"])}let h=(p=this.$["*cropPresetList"])==null?void 0:p[0],d=h?h.width/h.height:void 0;if(!Ds(i,t)||d&&!Fs(i,d)){let f=t.width/t.height,g=t.width,m=t.height;d&&(f>d?g=Math.min(t.height*d,t.width):m=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-g/2,y:t.y+t.height/2-m/2,width:g,height:m}}this.$["*cropBox"]=ee(se(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:a}=r,c=ie({width:e.width,height:e.height},a);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(a*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-c.width/2,-c.height/2,c.width,c.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=F({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:a,height:c}=ie(this._imageSize,r),{width:h,height:d}=i,p=n/a,f=o/c;return[Et(Math.round(h/p),1,a),Et(Math.round(d/f),1,c)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:a,y:c}=t,{width:h,height:d}=ie(this._imageSize,r),{x:p,y:f}=i,g=n/h,m=o/d,_=this._getCropDimensions(),S={dimensions:_,coords:[Et(Math.round((p-a)/g),0,h-_[0]),Et(Math.round((f-c)/m),0,d-_[1])]};if(!jo(S)){console.error("Cropper is trying to create invalid crop object",{payload:S});return}if(!(_[0]===h&&_[1]===d))return S}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),a={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=a}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=F({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(_e(i,e,t)),{promise:n,cancel:o,image:a}=ti(r),c=this._handleImageLoading(r);return a.addEventListener("load",c,{once:!0}),a.addEventListener("error",c,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>a).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(a)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};l(ye,"EditorImageCropper");ye.template=` `;function ss(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}l(ss,"linspace");function Ho(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}l(Wo,"calculateOpacities");function Xo(s,i){return s.map((t,e)=>tn-o)}l(Sr,"keypointsRange");var ii=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=O(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(_e(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=l(()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(c=>c.value===e),"shouldSkip");if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let a=this._handleImageLoading(n.src);o.addEventListener("load",a,{once:!0}),o.addEventListener("error",a,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let c=this._keypoints,h=c.findIndex(p=>p.value>e),d=h{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ct[i],r=this._keypoints.map(a=>a.value),n=Wo(r,t,e),o=Xo(r,e);for(let[a,c]of Object.entries(this._keypoints))c.opacity=n[a],c.zIndex=o[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(h=>h.src),{images:r,promise:n,cancel:o}=ei(e);r.forEach(h=>{let d=this._handleImageLoading(h.src);h.addEventListener("load",d),h.addEventListener("error",d)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let a=this._operation,c=this._filter;await n,this._isActive&&this._isSame(a,c)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((h,d)=>{let p=r[d];p.classList.add("fader-image"),h.image=p,this._container.appendChild(p)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Sr(e,r).map(c=>this._imageSrc({url:i,filter:t,operation:e,value:c})),{cancel:a}=ei(o);this._cancelBatchPreload=a}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let a=this._imageSrc({operation:t,value:e});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Sr(t,e).map(a=>this._constructKeypoint(t,a)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=F({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};l(ii,"EditorImageFader");var qo=1,ve=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>qo?this.scrollLeft+=e:this.scrollLeft+=t})}};l(ve,"EditorScroller");ve.template=" ";function Go(s){return` `}l(Go,"renderTabToggle");function Ko(s){return` `}l(Ko,"renderTabContent");var Ce=class extends R{constructor(){super();u(this,"_updateInfoTooltip",O(()=>{var o,a;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===P.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let c=((a=t==null?void 0:t.filter)==null?void 0:a.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+c}else r=this.l10n(dt);else if(this.$["*tabId"]===P.TUNING&&e){n=!0;let c=(t==null?void 0:t[e])||ct[e].zero;r=e+" "+c}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":dt,"*currentOperation":null,showLoader:!1,filters:rr,colorOperations:sr,cropOperations:nr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=O(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===P.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new qt;return e.operation=t,e}_createFilterControl(t){let e=new kt;return e.filter=t,e}_createToggleControl(t){let e=new Xt;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===P.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===P.FILTERS?[dt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===P.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===P.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of X){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(_e(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=ei([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of X){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};l(Ce,"EditorToolbar");Ce.template=` {{*operationTooltip}} `;var Gt=class extends y{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return F("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};l(Gt,"LrBtnUi");Gt.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Gt.template=` {{text}}`;var we=class extends y{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};l(we,"LineLoaderUi");we.template=``;var ki={transition:"transition",visible:"visible",hidden:"hidden"},Te=class extends y{constructor(){super(),this._visible=!1,this._visibleStyle=ki.visible,this._hiddenStyle=ki.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",wr(this,{[ki.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(ki.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};l(Te,"PresenceToggle");Te.template=" ";var xe=class extends y{constructor(){super();u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let a=document.createDocumentFragment(),c=document.createElement("div"),h=document.createElement("div");c.className="minor-step",h.className="border-step",a.appendChild(h);for(let p=0;p`;var si=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new tt,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};l(si,"CloudImageEditorActivity");var Yo=l(function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},"escapeRegExp"),kr=l(function(s,i="i"){let t=s.split("*").map(Yo);return new RegExp("^"+t.join(".+")+"$",i)},"wildcardRegexp");var Zo=l(s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,a)=>{let c=r[a];return o+`${a}: ${c};`},"");return t+`${e}{${n}}`},""),"styleToCss");function Or({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Zo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}l(Or,"buildStyles");var Ot={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in Ot){let t=Ot[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ir=l(function(s,i,t){s in Ot||(Ot[s]=[]),Ot[s].push([i,t])},"registerMessage"),Lr=l(function(s,i){s in Ot&&(Ot[s]=Ot[s].filter(t=>t[0]!==i))},"unregisterMessage");function Rr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}l(Rr,"queryString");var Ee=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.EXTERNAL);u(this,"_iframe",null);u(this,"updateCssData",l(()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())},"updateCssData"));u(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=b.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=D(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=kr(r);for(let[o,a]of Object.entries(t.alternatives))if(n.test(o))return a}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Or(t)})}remoteUrl(){var a,c;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((c=(a=this.getCssData("--l10n-locale-name"))==null?void 0:a.split("-"))==null?void 0:c[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Rr(n),o.toString()}mountIframe(){let t=Ue({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ir("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Lr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};l(Ee,"ExternalSource");Ee.template=` {{activityCaption}} `;var Kt=class extends y{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;D(i).forEach(e=>{let r=Ue({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};l(Kt,"Tabs");Kt.bindAttributes({"tab-list":null,default:null});Kt.template=` `;var ri=class extends v{constructor(){super();u(this,"processInnerHtml",!0);u(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return rs.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,Ui(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var e,r;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(a=>a.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let a of n){let c=document.createElement("input");c.type="hidden",c.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,c.value=a!=null?a:"",this._dynamicInputsContainer.appendChild(c)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let a=o.find(p=>!p.isValid),c=(r=a==null?void 0:a.validationErrorMessage)!=null?r:(e=a==null?void 0:a.uploadError)==null?void 0:e.message,h=this.$["*message"];h=h!=null&&h.isError?`${h.caption}. ${h.text}`:void 0;let d=c!=null?c:h;d?this._validationInputElement.setCustomValidity(d):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(a=>a.isUploaded&&a.isValid)){this.$.output={groupData:void 0,files:t};return}let r=this.getUploadClientOptions(),n=t.map(a=>a.uuid+(a.cdnUrlModifiers?`/${a.cdnUrlModifiers}`:"")),o=await Ss(n,r);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};l(ri,"DataOutputClass");ri.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var rs=ri;var ni=class extends b{};l(ni,"ActivityHeader");var Ae=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};l(Ae,"Select");Ae.template=``;var G={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Ur={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Z=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,src:"",ppIcon:G.PLAY,fsIcon:G.FS_ON,volIcon:G.VOL_ON,capIcon:G.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Ur.exitFullscreen():Ur.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===G.CAP_OFF?(this.$.capIcon=G.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Z.is+":captions","1")):(this.$.capIcon=G.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Z.is+":captions"))}toggleSound(){this.$.volIcon===G.VOL_ON?(this.$.volIcon=G.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=G.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Z.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Z.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=G.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=G.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=G.FS_OFF:this.$.fsIcon=G.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Z.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};l(Z,"Video");Z.template=` `;Z.bindAttributes({video:"video",src:"src"});var Jo="css-src";function oi(s){return class extends s{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0);u(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),ui({element:this,attribute:Jo,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}l(oi,"shadowed");var Yt=class extends oi(y){};l(Yt,"ShadowWrapper");var $e=class extends y{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};l($e,"Copyright"),u($e,"template",`Powered by Uploadcare`);var vt=class extends Yt{constructor(){super(...arguments);u(this,"requireCtxName",!0);u(this,"init$",vi(this));u(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};l(vt,"SolutionBlock");var Se=class extends vt{};l(Se,"FileUploaderRegular");Se.template=` `;var ke=class extends vt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||b.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=b.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||b.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};l(ke,"FileUploaderMinimal");ke.template=` `;var Oe=class extends vt{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=b.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==b.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||b.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||b.activities.START_FROM)&&(this.$["*currentActivity"]=b.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};l(Oe,"FileUploaderInline");Oe.template=` `;var li=class extends oi(tt){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};l(li,"CloudImageEditor");function Oi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}l(Oi,"registerBlocks");var ns="LR";async function Pr(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ns]){t(window[ns]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ns];i&&Oi(n),t(n)},document.head.appendChild(r)})}l(Pr,"connectBlocksFrom");return jr(Qo);})();
\ No newline at end of file
+`,"\\n"),i=ln(i),i=Jt+i+Jt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}l(an,"parseCssPropertyValue");var ls=0,Zt=null,mt=null,Ct=l(class extends HTMLElement{constructor(){super(),Ri(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 Ct}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(w.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=l(()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()},"addFr");if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Re.generate(),this.style.setProperty(w.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(w.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(w.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(w.EXT_DATA_CTX_PRFX,"");else if(s.includes(w.NAMED_DATA_CTX_SPLTR)){let r=s.split(w.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=l(n=>{this.isConnected&&i(n)},"subCb"),r=Ct.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=Ct.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=Ct.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=Ct.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=Ct.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=Ct.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(w.CTX_OWNER_ATTR)&&this.getAttribute(w.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(w.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(w.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(w.NAMED_DATA_CTX_SPLTR)){let t=i.split(w.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(w.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[w.SET_LATER_KEY]){for(let t in this[w.SET_LATER_KEY])cs(this,t,this[w.SET_LATER_KEY][t]);delete this[w.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of sn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${w.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(w.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);mt==null||mt.delete(this.updateCssData),mt!=null&&mt.size||(Zt==null||Zt.disconnect(),Zt=null,mt=null)},100)))}static reg(s,i=!1){s||(ls++,s=`${w.AUTO_TAG_PRFX}-${ls}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" 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(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=an(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){mt||(mt=new Set),mt.add(this.updateCssData),Zt||(Zt=new MutationObserver(s=>{s[0].type==="attributes"&&mt.forEach(i=>{i()})}),Zt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},"_BaseComponent"),Lt=Ct;Ri(Lt,"template");var Li=l(class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Li.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Li.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}},"AppRouter");Li.appMap=Object.create(null);function Ui(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}l(Ui,"applyStyles");function cn(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}l(cn,"applyAttributes");function Ue(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&cn(i,s.attributes),s.styles&&Ui(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Ue(t);i.appendChild(e)}),i}l(Ue,"create");var hs="idb-store-ready",hn="symbiote-db",un="symbiote-idb-update_",dn=l(class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(hs,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return un+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,a)=>{n.onsuccess=c=>{t||this._notifySubscribers(s),o(c.target.result)},n.onerror=c=>{a(c)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,us.clear(this.name)}},"DbInstance"),us=l(class{static get readyEventName(){return hs}static open(s=hn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new dn(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}},"IDB");Ri(us,"_reg",Object.create(null));var k=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),pn=Object.freeze({[k.UPLOAD_START]:"LR_UPLOAD_START",[k.REMOVE]:"LR_REMOVE",[k.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[k.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[k.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[k.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[k.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[k.DATA_OUTPUT]:"LR_DATA_OUTPUT",[k.DONE_FLOW]:"LR_DONE_FLOW",[k.INIT_FLOW]:"LR_INIT_FLOW"}),Pe=class{constructor(i){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));let e=pn[i];window.dispatchEvent(new CustomEvent(e,{detail:{ctx:this._getCtxName(),type:e,data:t}}))}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};l(Pe,"EventEmitter");function O(s,i){let t,e=l((...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)},"debounced");return e.cancel=()=>{clearTimeout(t)},e}l(O,"debounce");var ds="--uploadcare-blocks-window-height",wt=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(ds)}};l(wt,"WindowHeightTracker"),u(wt,"clientsRegistry",new Set),u(wt,"flush",O(()=>{document.documentElement.style.setProperty(ds,`${window.innerHeight}px`)},100));var hi=l((s,i)=>new Intl.PluralRules(s).select(i),"getPluralForm");var fn=l(s=>s,"DEFAULT_TRANSFORMER"),Pi="{{",fs="}}",ps="plural:";function Me(s,i,t={}){var o;let{openToken:e=Pi,closeToken:r=fs,transform:n=fn}=t;for(let a in i){let c=(o=i[a])==null?void 0:o.toString();s=s.replaceAll(e+a+r,typeof c=="string"?n(c):c)}return s}l(Me,"applyTemplateData");function ms(s){let i=[],t=s.indexOf(Pi);for(;t!==-1;){let e=s.indexOf(fs,t),r=s.substring(t+2,e);if(r.startsWith(ps)){let n=s.substring(t+2,e).replace(ps,""),o=n.substring(0,n.indexOf("(")),a=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:a})}t=s.indexOf(Pi,e)}return i}l(ms,"getPluralObjects");var rt=l(s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")},"toKebabCase");var ui=l(({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=setTimeout(()=>{c.disconnect(),e()},r),o=l(h=>{let d=s.getAttribute(i);h.type==="attributes"&&h.attributeName===i&&d!==null&&(clearTimeout(n),c.disconnect(),t(d))},"handleMutation"),a=s.getAttribute(i);a!==null&&(clearTimeout(n),t(a));let c=new MutationObserver(h=>{let d=h[h.length-1];o(d)});c.observe(s,{attributes:!0,attributeFilter:[i]})},"waitForAttribute");var gs=new Set;function Ne(s){gs.has(s)||(gs.add(s),console.warn(s))}l(Ne,"warnOnce");function bs(s){return Object.prototype.toString.call(s)==="[object Object]"}l(bs,"isObject");var mn=/\W|_/g;function gn(s){return s.split(mn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}l(gn,"camelizeString");function _s(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>_t(t,{ignoreKeys:i})):s}l(_s,"camelizeArrayItems");function _t(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return _s(s,{ignoreKeys:i});if(!bs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}bs(r)?r=_t(r,{ignoreKeys:i}):Array.isArray(r)&&(r=_s(r,{ignoreKeys:i})),t[gn(e)]=r}return t}l(_t,"camelizeKeys");var bn=l(s=>new Promise(i=>setTimeout(i,s)),"delay");function Fi({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),a=[n,r].filter(Boolean).join("; ");return`${o} (${a})`}l(Fi,"getUserAgent$1");var _n={factor:2,time:100};function yn(s,i=_n){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l(a=>bn(a!=null?a:n).then(()=>(t+=1,e(r))),"retry")})}return l(e,"runAttempt"),e(s)}l(yn,"retrier");var Rt=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Rt.prototype),this.originalProgressEvent=t}};l(Rt,"UploadcareNetworkError");var mi=l((s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},"onCancel"),gt=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,gt.prototype)}};l(gt,"CancelError");var vn=500,vs=l(({check:s,interval:i=vn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,a;mi(e,()=>{o&&clearTimeout(o),n(new gt("Poll cancelled"))}),t&&(a=setTimeout(()=>{o&&clearTimeout(o),n(new gt("Timed out"))},t));let c=l(()=>{try{Promise.resolve(s(e)).then(h=>{h?(a&&clearTimeout(a),r(h)):o=setTimeout(c,i)}).catch(h=>{a&&clearTimeout(a),n(h)})}catch(h){a&&clearTimeout(a),n(h)}},"tick");o=setTimeout(c,0)}),"poll"),$={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"},gi="application/octet-stream",Cs="original",Tt=l(({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,a)=>{let c=new XMLHttpRequest,h=(s==null?void 0:s.toUpperCase())||"GET",d=!1;c.open(h,i,!0),e&&Object.entries(e).forEach(p=>{let[f,g]=p;typeof g!="undefined"&&!Array.isArray(g)&&c.setRequestHeader(f,g)}),c.responseType="text",mi(r,()=>{d=!0,c.abort(),a(new gt)}),c.onload=()=>{if(c.status!=200)a(new Error(`Error ${c.status}: ${c.statusText}`));else{let p={method:h,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},f=c.getAllResponseHeaders().trim().split(/[\r\n]+/),g={};f.forEach(function(S){let A=S.split(": "),x=A.shift(),T=A.join(": ");x&&typeof x!="undefined"&&(g[x]=T)});let m=c.response,_=c.status;o({request:p,data:m,headers:g,status:_})}},c.onerror=p=>{d||a(new Rt(p))},n&&typeof n=="function"&&(c.upload.onprogress=p=>{p.lengthComputable?n({isComputable:!0,value:p.loaded/p.total}):n({isComputable:!1})}),t?c.send(t):c.send()}),"request");function Cn(s,...i){return s}l(Cn,"identity");var wn=l(({name:s})=>s?[s]:[],"getFileOptions"),Tn=Cn,xn=l(()=>new FormData,"getFormData"),ws=l(s=>!1,"isBuffer"),bi=l(s=>typeof Blob!="undefined"&&s instanceof Blob,"isBlob"),_i=l(s=>typeof File!="undefined"&&s instanceof File,"isFile"),yi=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string","isReactNativeAsset"),Qt=l(s=>bi(s)||_i(s)||ws()||yi(s),"isFileData"),En=l(s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined","isSimpleValue"),An=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s),"isObjectValue"),$n=l(s=>!!s&&typeof s=="object"&&"data"in s&&Qt(s.data),"isFileValue");function Sn(s,i,t){if($n(t)){let{name:e,contentType:r}=t,n=Tn(t.data,e,r!=null?r:gi),o=wn({name:e,contentType:r});s.push([i,n,...o])}else if(An(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else En(t)&&t&&s.push([i,t.toString()])}l(Sn,"collectParams");function kn(s){let i=[];for(let[t,e]of Object.entries(s))Sn(i,t,e);return i}l(kn,"getFormDataParams");function Vi(s){let i=xn(),t=kn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}l(Vi,"buildFormData");var U=class extends Error{constructor(t,e,r,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,U.prototype)}};l(U,"UploadClientError");var On=l(s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},"buildSearchParams"),bt=l((s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=On(t)),e.toString()},"getUrl"),In="6.8.0",Ln="UploadcareUploadClient",Rn=In;function Ut(s){return Fi({libraryName:Ln,libraryVersion:Rn,...s})}l(Ut,"getUserAgent");var Un="RequestThrottledError",ys=15e3,Pn=1e3;function Mn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return ys;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:ys}l(Mn,"getTimeoutFromThrottledRequest");function xt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return yn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Un&&r{let i="";return(bi(s)||_i(s)||yi(s))&&(i=s.type),i||gi},"getContentType"),xs=l(s=>{let i="";return _i(s)&&s.name?i=s.name:bi(s)||ws()?i="":yi(s)&&s.name&&(i=s.name),i||Cs},"getFileName");function Bi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}l(Bi,"getStoreValue");function Nn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=$.baseURL,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=$.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:bt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:p,userAgent:f})},data:Vi({file:{data:s,name:t||xs(s),contentType:e||Ts(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Bi(a),signature:n,expire:o,source:d,metadata:_}),signal:c,onProgress:h}).then(({data:S,headers:A,request:x})=>{let T=_t(JSON.parse(S));if("error"in T)throw new U(T.error.content,T.error.errorCode,x,T,A);return T}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(Nn,"base");var Di;(function(s){s.Token="token",s.FileInfo="file_info"})(Di||(Di={}));function Dn(s,{publicKey:i,baseURL:t=$.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,source:h="url",signal:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=$.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:p,userAgent:f})},url:bt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Bi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:a,expire:c,source:h,metadata:_}),signal:d}).then(({data:S,headers:A,request:x})=>{let T=_t(JSON.parse(S));if("error"in T)throw new U(T.error.content,T.error.errorCode,x,T,A);return T}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(Dn,"fromUrl");var H;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(H||(H={}));var Fn=l(s=>"status"in s&&s.status===H.Error,"isErrorResponse");function Vn(s,{publicKey:i,baseURL:t=$.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=$.retryNetworkErrorMaxTimes}={}){return xt(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Ut({publicKey:i,integration:r,userAgent:n})}:void 0,url:bt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:c,headers:h,request:d})=>{let p=_t(JSON.parse(c));if("error"in p&&!Fn(p))throw new U(p.error.content,void 0,d,p,h);return p}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:o})}l(Vn,"fromUrlStatus");function Bn(s,{publicKey:i,baseURL:t=$.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:a,integration:c,userAgent:h,retryThrottledRequestMaxTimes:d=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=$.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:c,userAgent:h})},url:bt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:a}),signal:o}).then(({data:f,headers:g,request:m})=>{let _=_t(JSON.parse(f));if("error"in _)throw new U(_.error.content,_.error.errorCode,m,_,g);return _}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:d})}l(Bn,"group");function Es(s,{publicKey:i,baseURL:t=$.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=$.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:n,userAgent:o})},url:bt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:h,headers:d,request:p})=>{let f=_t(JSON.parse(h));if("error"in f)throw new U(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Es,"info");function zn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=$.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:a,store:c,signal:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=$.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:bt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:p,userAgent:f})},data:Vi({filename:e||Cs,size:s,content_type:t||gi,part_size:r,UPLOADCARE_STORE:Bi(c),UPLOADCARE_PUB_KEY:i,signature:o,expire:a,source:d,metadata:_}),signal:h}).then(({data:S,headers:A,request:x})=>{let T=_t(JSON.parse(S));if("error"in T)throw new U(T.error.content,T.error.errorCode,x,T,A);return T.parts=Object.keys(T.parts).map(z=>T.parts[z]),T}),{retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})}l(zn,"multipartStart");function jn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=$.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||gi}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}l(jn,"multipartUpload");function Hn(s,{publicKey:i,baseURL:t=$.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=$.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=$.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",url:bt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:n,userAgent:o})},data:Vi({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:h,headers:d,request:p})=>{let f=_t(JSON.parse(h));if("error"in f)throw new U(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Hn,"multipartComplete");function zi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a,signal:c,onProgress:h}){return vs({check:d=>Es(s,{publicKey:i,baseURL:t,signal:d,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a}).then(p=>p.isReady?p:(h&&h({isComputable:!0,value:1}),!1)),signal:c})}l(zi,"isReadyPoll");function Wn(s){return"defaultEffects"in s}l(Wn,"isGroupFileInfo");var nt=class{constructor(i,{baseCDN:t=$.baseCDN,fileName:e}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);u(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=bt(t,`${r}/`),a=n?bt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=a,Wn(i)&&(this.defaultEffects=i.defaultEffects)}};l(nt,"UploadcareFile");var Xn=l((s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,baseCDN:_,metadata:S})=>Nn(s,{publicKey:i,fileName:t,contentType:a,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:S}).then(({file:A})=>zi(A,{publicKey:i,baseURL:e,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then(A=>new nt(A,{baseCDN:_})),"uploadDirect"),qn=l((s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d,baseCDN:p})=>Es(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d}).then(f=>new nt(f,{baseCDN:p,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),"uploadFromUploaded"),Gn=l((s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=l(o=>()=>{e=o,r.forEach((a,c)=>c!==o&&a.abort())},"createStopRaceCallback");return mi(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,a)=>{let c=n(a);return Promise.resolve().then(()=>o({stopRace:c,signal:r[a].signal})).then(h=>(c(),h)).catch(h=>(t=h,null))})).then(o=>{if(e===null)throw t;return o[e]})},"race"),Kn=window.WebSocket,di=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}};l(di,"Events");var Yn=l((s,i)=>s==="success"?{status:H.Success,...i}:s==="progress"?{status:H.Progress,...i}:{status:H.Error,...i},"response"),pi=class{constructor(i,t=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 di);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Kn(i),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 e=JSON.parse(t.data.toString());switch(e.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(e.channel,Yn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=l(()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1},"actualDisconect");this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}};l(pi,"Pusher");var Mi=null,ji=l(s=>{if(!Mi){let i=typeof window=="undefined"?0:3e4;Mi=new pi(s,i)}return Mi},"getPusher"),Zn=l(s=>{ji(s).connect()},"preconnect");function Jn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:a,signal:c}){return vs({check:h=>Vn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:h}).then(d=>{switch(d.status){case H.Error:return new U(d.error,d.errorCode);case H.Waiting:return!1;case H.Unknown:return new U(`Token "${s}" was not found.`);case H.Progress:return a&&(d.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:d.done/d.total})),!1;case H.Success:return a&&a({isComputable:!0,value:d.done/d.total}),d;default:throw new Error("Unknown status")}}),signal:c})}l(Jn,"pollStrategy");var Qn=l(({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=ji(i),a=o.onError(n),c=l(()=>{a(),o.unsubscribe(s)},"destroy");mi(t,()=>{c(),n(new gt("pusher cancelled"))}),o.subscribe(s,h=>{switch(h.status){case H.Progress:{e&&(h.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:h.done/h.total}));break}case H.Success:{c(),e&&e({isComputable:!0,value:h.done/h.total}),r(h);break}case H.Error:c(),n(new U(h.msg,h.error_code))}})}),"pushStrategy"),to=l((s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,onProgress:p,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:_,pusherKey:S=$.pusherKey,metadata:A})=>Promise.resolve(Zn(S)).then(()=>Dn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:_,metadata:A})).catch(x=>{let T=ji(S);return T==null||T.disconnect(),Promise.reject(x)}).then(x=>x.type===Di.FileInfo?x:Gn([({signal:T})=>Jn({token:x.token,publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:_,onProgress:p,signal:T}),({signal:T})=>Qn({token:x.token,pusherKey:S,signal:T,onProgress:p})],{signal:d})).then(x=>{if(x instanceof U)throw x;return x}).then(x=>zi(x.uuid,{publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:_,onProgress:p,signal:d})).then(x=>new nt(x,{baseCDN:r})),"uploadFromUrl"),Ni=new WeakMap,eo=l(async s=>{if(Ni.has(s))return Ni.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Ni.set(s,i),i},"getBlobFromReactNativeAsset"),As=l(async s=>{if(_i(s)||bi(s))return s.size;if(yi(s))return(await eo(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},"getFileSize"),io=l((s,i=$.multipartMinFileSize)=>s>=i,"isMultipart"),$s=l(s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Qt(s)&&t.test(s)},"isUuid"),Hi=l(s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Qt(s)&&t.test(s)},"isUrl"),so=l((s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,a=[...i],c=l(()=>{let h=i.length-a.length,d=a.shift();d&&d().then(p=>{n||(r[h]=p,o-=1,o?c():t(r))}).catch(p=>{n=!0,e(p)})},"run");for(let h=0;h{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},"sliceChunk"),no=l(async(s,i,t)=>e=>ro(s,e,i,t),"prepareChunks"),oo=l((s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})=>jn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c}),"uploadPart"),lo=l(async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,contentType:_,multipartChunkSize:S=$.multipartChunkSize,maxConcurrentRequests:A=$.maxConcurrentRequests,baseCDN:x,metadata:T})=>{let z=e!=null?e:await As(s),pt,It=l((M,j)=>{if(!h)return;pt||(pt=Array(M).fill(0));let et=l(st=>st.reduce((ft,Ii)=>ft+Ii,0),"sum");return st=>{st.isComputable&&(pt[j]=st.value,h({isComputable:!0,value:et(pt)/M}))}},"createProgressHandler");return _||(_=Ts(s)),zn(z,{publicKey:i,contentType:_,fileName:t||xs(s),baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:T}).then(async({uuid:M,parts:j})=>{let et=await no(s,z,S);return Promise.all([M,so(A,j.map((st,ft)=>()=>oo(et(ft),st,{publicKey:i,contentType:_,onProgress:It(j.length,ft),signal:c,integration:p,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})))])}).then(([M])=>Hn(M,{publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})).then(M=>M.isReady?M:zi(M.uuid,{publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then(M=>new nt(M,{baseCDN:x}))},"uploadMultipart");async function Wi(s,{publicKey:i,fileName:t,baseURL:e=$.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartMinFileSize:_,multipartChunkSize:S,maxConcurrentRequests:A,baseCDN:x=$.baseCDN,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:z,pusherKey:pt,metadata:It}){if(Qt(s)){let M=await As(s);return io(M,_)?lo(s,{publicKey:i,contentType:m,multipartChunkSize:S,fileSize:M,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x,metadata:It}):Xn(s,{publicKey:i,fileName:t,contentType:m,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x,metadata:It})}if(Hi(s))return to(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:x,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:z,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,pusherKey:pt,metadata:It});if($s(s))return qn(s,{publicKey:i,fileName:t,baseURL:e,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x});throw new TypeError(`File uploading from "${s}" is not supported`)}l(Wi,"uploadFile");var fi=class{constructor(i,{baseCDN:t=$.baseCDN}={}){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new nt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}};l(fi,"UploadcareGroup");var ao=l(s=>{for(let i of s)if(!Qt(i))return!1;return!0},"isFileDataArray"),co=l(s=>{for(let i of s)if(!$s(i))return!1;return!0},"isUuidArray"),ho=l(s=>{for(let i of s)if(!Hi(i))return!1;return!0},"isUrlArray");function Ss(s,{publicKey:i,fileName:t,baseURL:e=$.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:_=$.multipartChunkSize,baseCDN:S=$.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x,jsonpCallback:T}){if(!ao(s)&&!ho(s)&&!co(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let z,pt=!0,It=s.length,M=l((j,et)=>{if(!c)return;z||(z=Array(j).fill(0));let st=l(ft=>ft.reduce((Ii,Mr)=>Ii+Mr)/j,"normalize");return ft=>{if(!ft.isComputable||!pt){pt=!1,c({isComputable:!1});return}z[et]=ft.value,c({isComputable:!0,value:st(z)})}},"createProgressHandler");return Promise.all(s.map((j,et)=>Qt(j)||Hi(j)?Wi(j,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:M(It,et),source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:_,baseCDN:S,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x}).then(st=>st.uuid):j)).then(j=>Bn(j,{publicKey:i,baseURL:e,jsonpCallback:T,secureSignature:r,secureExpire:n,signal:a,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g}).then(et=>new fi(et,{baseCDN:S})).then(et=>(c&&c({isComputable:!0,value:1}),et)))}l(Ss,"uploadFileGroup");var De=class{constructor(i){u(this,"_concurrency",1);u(this,"_pending",[]);u(this,"_running",0);u(this,"_resolvers",new Map);u(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};l(De,"Queue");var Xi=l(()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),"blockCtx"),qi=l(s=>({...Xi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),"activityBlockCtx"),vi=l(s=>({...qi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new De(1),"*uploadCollection":null}),"uploaderBlockCtx");function ks(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}l(ks,"l10nProcessor");var W=l(s=>`*cfg/${s}`,"sharedConfigKey");var Gi="lr-",y=class extends Lt{constructor(){super();u(this,"requireCtxName",!1);u(this,"allowCustomTemplate",!0);u(this,"init$",Xi());u(this,"updateCtxCssData",l(()=>{Ne("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()},"updateCtxCssData"));this.activityType=null,this.addTemplateProcessor(ks),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=ms(r);for(let a of n)e[a.variable]=this.pluralize(a.pluralKey,Number(e[a.countVariable]));return Me(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=hi(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Gi}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?ui({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),wt.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),wt.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new Pe(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=l(h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h,"getUnit");if(t===0)return`0 ${n(r[0])}`;let o=1024,a=e<0?0:e,c=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**c).toFixed(a))+" "+n(r[c])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Me(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=W(r);return this.$[o]=n,!0},get:(e,r)=>{let n=W(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Ne("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${rt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(W(t));r.ctx.has(r.name)?this.sub(W(t),e):(this.bindCssData(`--cfg-${rt(t)}`),this.sub(`--cfg-${rt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Gi)?t:Gi+t)}};l(y,"Block"),u(y,"StateConsumerScope",null),u(y,"className","");var Os="active",Fe="___ACTIVITY_IS_ACTIVE___",ot=class extends y{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",qi(this));u(this,"_debouncedHistoryFlush",O(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=ot._activityRegistry[this.activityKey];this[Fe]=!1,this.removeAttribute(Os),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=ot._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[Fe]=!0,this.setAttribute(Os,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[Fe]?this._deactivate():this.activityType===t&&!this[Fe]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!ot._activityRegistry[this.activityKey]}get isActivityActive(){return this[Fe]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;ot._activityRegistry||(ot._activityRegistry=Object.create(null)),ot._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),ot._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(ot._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let a=[...this.$["*blocksRegistry"]].find(c=>c.activityType===r);n=(e=a==null?void 0:a.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},b=ot;l(b,"ActivityBlock"),u(b,"_activityRegistry",Object.create(null));b.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Ve=33.333333333333336,C=1,Ki=24,Is=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}l(Pt,"setSvgNodeAttrs");function J(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}l(J,"createSvgNode");function Ls(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=i.includes("w")?0:1,c=i.includes("n")?0:1,h=[-1,1][a],d=[-1,1][c],p=[e+a*n+1.5*h,r+c*o+1.5*d-24*t*d],f=[e+a*n+1.5*h,r+c*o+1.5*d],g=[e+a*n-24*t*h+1.5*h,r+c*o+1.5*d];return{d:`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]} L ${g[0]} ${g[1]}`,center:f}}l(Ls,"cornerPath");function Rs(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=["n","s"].includes(i)?.5:{w:0,e:1}[i],c=["w","e"].includes(i)?.5:{n:0,s:1}[i],h=[-1,1][a],d=[-1,1][c],p,f;["n","s"].includes(i)?(p=[e+a*n-34*t/2,r+c*o+1.5*d],f=[e+a*n+34*t/2,r+c*o+1.5*d]):(p=[e+a*n+1.5*h,r+c*o-34*t/2],f=[e+a*n+1.5*h,r+c*o+34*t/2]);let g=`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]}`,m=[f[0]-(f[0]-p[0])/2,f[1]-(f[1]-p[1])/2];return{d:g,center:m}}l(Rs,"sidePath");function Us(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}l(Us,"thumbCursor");function Ps({rect:s,delta:[i,t],imageBox:e}){return ee({...s,x:s.x+i,y:s.y+t},e)}l(Ps,"moveRect");function ee(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}l(ee,"constraintRect");function uo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:a}=s;n+=r,a-=r,t&&(o=a*t);let c=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,a=s.y+s.height-n,t&&(o=a*t,c=s.x+s.width/2-o/2)),c<=e.x&&(c=e.x,n=s.y+s.height-a),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y+s.height-a),a=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x+s.width-o),a=e.y+e.height&&(a=e.y+e.height-n,t&&(o=a*t),c=s.x+s.width/2-o/2),c<=e.x&&(c=e.x,n=s.y),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y),a=e.x+e.width&&(o=e.x+e.width-n,t&&(a=o/t),c=s.y+s.height/2-a/2),c<=e.y&&(c=e.y,n=s.x),c+a>=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x),at?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x+s.width-c,a=e.y)):t&&(r=h*t-c,c=c+r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y+s.height-h)),he.x+e.width&&(r=e.x+e.width-o-c),a+nt?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x,a=e.y)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y+s.height-h)),he.y+e.height&&(n=e.y+e.height-a-h),o+=r,c-=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x+s.width-c,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y)),he.x+e.width&&(r=e.x+e.width-o-c),a+h+n>e.y+e.height&&(n=e.y+e.height-a-h),c+=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y)),h=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}l(Ds,"isRectInsideRect");function Fs(s,i){return Math.abs(s.width/s.height-i)<.1}l(Fs,"isRectMatchesAspectRatio");function ie({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}l(ie,"rotateSize");function Vs(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),a=Math.round((i-n)/2);return o+r>s&&(r=s-o),a+n>i&&(n=i-a),{x:o,y:a,width:r,height:n}}l(Vs,"calculateMaxCenteredCropFrame");function se(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}l(se,"roundRect");function Et(s,i,t){return Math.min(Math.max(s,i),t)}l(Et,"clamp");var wi=l(s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]},"parseCropPreset");var Q=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Bs=l(s=>s?s.split(",").map(i=>i.trim()):[],"deserealizeCsv"),Mt=l(s=>s?s.join(","):"","serializeCsv");var Yi="blocks",Zi="0.30.5";function zs(s){return Fi({...s,libraryName:Yi,libraryVersion:Zi})}l(zs,"customUserAgent");var js=l(s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},"normalizeCdnOperation"),Ti=l((...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>js(i)).join("/-/"),"joinCdnOperations"),N=l((...s)=>{let i=Ti(...s);return i?`-/${i}/`:""},"createCdnUrlModifiers");function Hs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}l(Hs,"extractFilename");function Ws(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}l(Ws,"extractUuid");function Xs(s){let i=qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>js(n))}l(Xs,"extractOperations");function qs(s){let i=new URL(s),t=Hs(s),e=Gs(t)?Ks(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}l(qs,"trimFilename");function Gs(s){return s.startsWith("http")}l(Gs,"isFileUrl");function Ks(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}l(Ks,"splitFileUrl");var L=l((s,i,t)=>{let e=new URL(qs(s));if(t=t||Hs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Gs(t)){let r=Ks(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},"createCdnUrl"),At=l((s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()},"createOriginalUrl");var D=l((s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0),"stringToArray");var Be=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Ji=l(s=>s?s.filter(i=>typeof i=="string").map(i=>D(i)).flat():[],"mergeFileTypes"),Qi=l((s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),"matchMimeType"),Ys=l((s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),"matchExtension"),ze=l(s=>{let i=s==null?void 0:s.type;return i?Qi(i,Be):!1},"fileIsImage");var at=1e3,Nt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),je=l(s=>Math.ceil(s*100)/100,"round"),Zs=l((s,i=Nt.AUTO)=>{let t=i===Nt.AUTO;if(i===Nt.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Js+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(vo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Js+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};l(He,"TypedData");var We=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Re.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new He(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};l(We,"TypedCollection");var Qs=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:nt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var v=class extends b{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!1);u(this,"isCtxOwner",!1);u(this,"init$",vi(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",O(this._runValidators.bind(this),100));u(this,"_flushOutputItems",O(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(k.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));u(this,"_handleCollectonUpdate",l((t,e,r)=>{var n;this._runValidators();for(let o of r)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()},"_handleCollectonUpdate"));u(this,"_handleCollectionPropertiesUpdate",l(t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(c=>!c.getValue("uploadError"));o.forEach(c=>{n+=e.readProp(c,"uploadProgress")});let a=Math.round(n/o.length);this.$["*commonProgress"]=a,this.emit(k.UPLOAD_PROGRESS,a,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(a=>!!a.getValue("fileInfo")),o=e.findItems(a=>!!a.getValue("uploadError")||!!a.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let a=this.getOutputData(c=>!!c.getValue("fileInfo")&&!c.getValue("silentUpload"));a.length>0&&this.emit(k.UPLOAD_FINISH,a,{debounce:!0})}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(k.UPLOAD_ERROR,e.readProp(o,"uploadError"))}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(k.VALIDATION_ERROR,e.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(k.CLOUD_MODIFICATION,e.readProp(o,"cdnUrlModifiers"))})},"_handleCollectionPropertiesUpdate"))}setUploadMetadata(t){Ne("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof v?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new We({typedSchema:Qs,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Q.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Q.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:ze(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:Q.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:ze(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Mt(Ji([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?Be:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Mt(Be)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Q.LOCAL})),this.$["*currentActivity"]=b.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=D(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":b.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=b.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":b.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":b.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(k.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(k.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Ji([...e?Be:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),a=t.getValue("fileName");if(!o||!a)return;let c=Qi(o,n),h=Ys(a,n);if(!c&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Zs(e)})}_validateMultipleLimit(t){let e=this.uploadCollection.items(),r=e.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&e.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=wi(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:a,height:c}=o.imageInfo,h=e.width/e.height,d=Vs(a,c,h),p=N(`crop/${d.width}x${d.height}/${d.x},${d.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:p,cdnUrl:L(n.getValue("cdnUrl"),p)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===b.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=b.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:zs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,a;let e=E.getCtx(t).store,r=e.fileInfo||{name:e.fileName,originalFilename:e.fileName,size:e.fileSize,isImage:e.isImage,mimeType:e.mimeType};return{...r,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(a=(o=e.cdnUrl)!=null?o:r.cdnUrl)!=null?a:null,validationErrorMessage:e.validationErrorMsg,uploadError:e.uploadError,isUploaded:!!e.uuid&&!!e.fileInfo,isValid:!e.validationErrorMsg&&!e.uploadError,fullPath:e.fullPath,uploadProgress:e.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};l(v,"UploaderBlock");v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});var K={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function Co(s,i){if(typeof i=="number")return K[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&K[s]!==i?`${s}`:"";if(s==="filter"){if(!i||K[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}l(Co,"transformationToStr");var er=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return Ti(...er.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return Co(i,t)}).filter(i=>!!i))}l($t,"transformationsToOperations");var xi=Ti("format/auto","progressive/yes"),yt=l(([s])=>typeof s!="undefined"?Number(s):void 0,"asNumber"),tr=l(()=>!0,"asBoolean"),wo=l(([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),"asFilter"),To=l(([s,i])=>({dimensions:D(s,"x").map(Number),coords:D(i).map(Number)}),"asCrop"),xo={enhance:yt,brightness:yt,exposure:yt,gamma:yt,contrast:yt,saturation:yt,vibrance:yt,warmth:yt,filter:wo,mirror:tr,flip:tr,rotate:yt,crop:To};function ir(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!er.includes(e))continue;let n=xo[e],o=n(r);i[e]=o}return i}l(ir,"operationsToTransformations");var P=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),X=[P.CROP,P.TUNING,P.FILTERS],sr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],rr=["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"],nr=["rotate","mirror","flip"],ct=Object.freeze({brightness:{zero:K.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:K.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:K.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:K.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:K.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:K.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:K.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:K.enhance,range:[0,100],keypointsNumber:1},filter:{zero:K.filter,range:[0,100],keypointsNumber:1}});var Eo="https://ucarecdn.com",Ao="https://upload.uploadcare.com",$o="https://social.uploadcare.com",St={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Mt(X),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Eo,baseUrl:Ao,socialBaseUrl:$o,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var q=l(s=>String(s),"asString"),ht=l(s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},"asNumber"),I=l(s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},"asBoolean"),So=l(s=>s==="auto"?s:I(s),"asStore"),ko={pubkey:q,multiple:I,multipleMin:ht,multipleMax:ht,confirmUpload:I,imgOnly:I,accept:q,externalSourcesPreferredTypes:q,store:So,cameraMirror:I,sourceList:q,maxLocalFileSizeBytes:ht,thumbSize:ht,showEmptyList:I,useLocalImageEditor:I,useCloudImageEditor:I,cloudImageEditorTabs:q,removeCopyright:I,cropPreset:q,modalScrollLock:I,modalBackdropStrokes:I,sourceListWrap:I,remoteTabSessionKey:q,cdnCname:q,baseUrl:q,socialBaseUrl:q,secureSignature:q,secureExpire:q,secureDeliveryProxy:q,retryThrottledRequestMaxTimes:ht,multipartMinFileSize:ht,multipartChunkSize:ht,maxConcurrentRequests:ht,multipartMaxConcurrentRequests:ht,multipartMaxAttempts:ht,checkForUrlDuplicates:I,saveUrlForRecurrentUploads:I,groupOutput:I,userAgentIntegration:q},or=l((s,i)=>{if(!(typeof i=="undefined"||i===null))try{return ko[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),St[s]}},"normalizeConfigValue");var Ei=Object.keys(St),Oo=["metadata"],Io=l(s=>Oo.includes(s),"isComplexKey"),Ai=Ei.filter(s=>!Io(s)),Lo={...Object.fromEntries(Ai.map(s=>[rt(s),s])),...Object.fromEntries(Ai.map(s=>[s.toLowerCase(),s]))},Ro={...Object.fromEntries(Ei.map(s=>[rt(s),W(s)])),...Object.fromEntries(Ei.map(s=>[s.toLowerCase(),W(s)]))},Xe=class extends y{constructor(){super();u(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(St).map(([t,e])=>[W(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of Ai)this.sub(W(e),r=>{r!==St[e]&&(t[e]=r)},!1);for(let e of Ei){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,Ai.includes(e)){let o=[...new Set([rt(e),e.toLowerCase()])];for(let a of o)typeof n=="undefined"||n===null?this.removeAttribute(a):this.setAttribute(a,n.toString())}this.$[W(e)]!==n&&(typeof n=="undefined"||n===null?this.$[W(e)]=St[e]:this.$[W(e)]=n)},get:()=>this.$[W(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Lo[t],o=or(n,r),a=o!=null?o:St[n],c=this;c[n]=a}};l(Xe,"ConfigClass");Xe.bindAttributes(Ro);var lr=Xe;var Dt=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};l(Dt,"Icon");Dt.template=``;Dt.bindAttributes({name:"name",size:"size"});var Uo="https://ucarecdn.com",Ft=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Uo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var ar=l(s=>[...new Set(s)],"uniqueArray");var qe="--lr-img-",cr="unresolved",re=2,ne=3,hr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),dr=Object.create(null),ur;for(let s in Ft)dr[qe+s]=((ur=Ft[s])==null?void 0:ur.default)||"";var Ge=class extends Lt{constructor(){super(...arguments);u(this,"cssInit$",dr)}$$(t){return this.$[qe+t]}set$$(t){for(let e in t)this.$[qe+e]=t[e]}sub$$(t,e){this.sub(qe+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!hr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return N(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Ft.format.default}`,`quality/${this.$$("quality")||Ft.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(hr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return L(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(L(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(L(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(L(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(L(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Me(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),a=r?"":e*Math.round(n.height);return o||a?`${o||""}x${a||""}`:null}_setupEventProxy(t){let e=l(n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},"proxifyEvent"),r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(cr,""),this.img.onload=()=>{this.img.removeAttribute(cr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Ft[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?ar(D(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*re+"x")}") ${n*re}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*ne+"x")}") ${n*ne}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,re))}") ${re}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,ne))}") ${ne}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*re+"x")+` ${e*re}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*ne+"x")+` ${e*ne}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(Ft)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[qe+t]=r})}};l(Ge,"ImgBase");var Ke=class extends Ge{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};l(Ke,"Img");var Vt=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=I(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};l(Vt,"SimpleBtn");Vt.template=` `;Vt.bindAttributes({dropzone:null});var oe=class extends b{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};l(oe,"StartFrom");oe.template=' ';function Po(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=l(r=>{r.type!=="loadend"&&t.abort(),i(!1)},"onLoad");t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}l(Po,"checkIsDirectory");function Mo(s,i){return new Promise(t=>{let e=0,r=[],n=l(a=>{a||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),a.isFile?(e++,a.file(c=>{e--;let h=new File([c],c.name,{type:c.type||i});r.push({type:"file",file:h,fullPath:a.fullPath}),e===0&&t(r)})):a.isDirectory&&o(a.createReader())},"readEntry"),o=l(a=>{e++,a.readEntries(c=>{e--;for(let h of c)n(h);e===0&&t(r)})},"readReaderContent");n(s)})}l(Mo,"readEntryContentAsync");function pr(s){let i=[],t=[];for(let e=0;e{c&&i.push(...c)}));continue}let o=r.getAsFile();o&&t.push(Po(o).then(a=>{a||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}l(pr,"getDropItems");var V={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},fr=["focus"],No=100,ts=new Map;function Do(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}l(Do,"distance");function es(s){let i=0,t=document.body,e=new Set,r=l(m=>e.add(m),"handleSwitch"),n=V.INACTIVE,o=l(m=>{s.shouldIgnore()&&m!==V.INACTIVE||(n!==m&&e.forEach(_=>_(m)),n=m)},"setState"),a=l(()=>i>0,"isDragging");r(m=>s.onChange(m));let c=l(()=>{i=0,o(V.INACTIVE)},"onResetEvent"),h=l(()=>{i+=1,n===V.INACTIVE&&o(V.ACTIVE)},"onDragEnter"),d=l(()=>{i-=1,a()||o(V.INACTIVE)},"onDragLeave"),p=l(m=>{m.preventDefault(),i=0,o(V.INACTIVE)},"onDrop"),f=l(m=>{if(s.shouldIgnore())return;a()||(i+=1);let _=[m.x,m.y],S=s.element.getBoundingClientRect(),A=Math.floor(Do(_,S)),x=A{if(s.shouldIgnore())return;m.preventDefault();let _=await pr(m.dataTransfer);s.onItems(_),o(V.INACTIVE)},"onElementDrop");return t.addEventListener("drop",p),t.addEventListener("dragleave",d),t.addEventListener("dragenter",h),t.addEventListener("dragover",f),s.element.addEventListener("drop",g),fr.forEach(m=>{window.addEventListener(m,c)}),()=>{ts.delete(s.element),t.removeEventListener("drop",p),t.removeEventListener("dragleave",d),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",f),s.element.removeEventListener("drop",g),fr.forEach(m=>{window.removeEventListener(m,c)})}}l(es,"addDropzone");var mr="lr-drop-area",le=`${mr}/registry`,Bt=class extends v{constructor(){super(),this.init$={...this.init$,state:V.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[le]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[le]||(this.$[le]=new Set),this.$[le].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!I(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:I(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:I(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:I(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=es({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Q.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Q.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":b.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=es({element:i,onChange:t=>{var r;let e=(r=Object.entries(V).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(V).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=D(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[le]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[le];i&&(i.delete(this),i.size===0&&E.deleteCtx(mr)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};l(Bt,"DropArea");Bt.template=` {{text}} `;Bt.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Fo="src-type-",zt=class extends v{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"_registeredTypes",{});u(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:b.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:b.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:b.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:b.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:a,activityParams:c={}}=e;this.applyL10nKey("src-type",`${Fo}${r}`),this.$.iconName=n,this.onclick=h=>{(a?a(h):!!o)&&this.set$({"*currentActivityParams":c,"*currentActivity":o})}}};l(zt,"SourceBtn");zt.template=` `;zt.bindAttributes({type:null});var Ye=class extends y{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=D(i),e="";t.forEach(r=>{e+=` `}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};l(Ye,"SourceList");function gr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}l(gr,"createSvgBlobUrl");function br(s="#fff",i="rgba(0, 0, 0, .1)"){return gr(``)}l(br,"checkerboardCssBg");function Ze(s="hsl(209, 21%, 65%)",i=32,t=32){return gr(``)}l(Ze,"fileCssBg");function _r(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,a)=>{r.onload=()=>{let c=r.height/r.width;c>1?(t.width=i,t.height=i*c):(t.height=i,t.width=i/c),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(h=>{if(!h){a();return}let d=URL.createObjectURL(h);o(d)})},r.onerror=c=>{a(c)}});return r.src=URL.createObjectURL(s),n}l(_r,"generateThumb");var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),it=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",O(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",O(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===b.activities.DETAILS)?this.$["*currentActivity"]=b.activities.DETAILS:this.$["*currentActivity"]=b.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);this.emit(k.REMOVE,e,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(L(At(this.cfg.cdnCname,this._entry.getValue("uuid")),N(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await _r(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ze(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ze(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{it.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),it.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),it.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,a;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(c=>!c.getValue("fileInfo"));this.emit(k.UPLOAD_START,r,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let c=new AbortController;t.setValue("abortController",c);let h=l(async()=>{let p=this.getUploadClientOptions();return Wi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...p,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let g=f.value*100;t.setValue("uploadProgress",g)}this.$.progressUnknown=!f.isComputable},signal:c.signal,metadata:await this.getMetadataFor(t.uid)})},"uploadTask"),d=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:d,isUploading:!1,fileName:d.originalFilename,fileSize:d.size,isImage:d.isImage,mimeType:(a=(o=(n=d.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?a:d.mimeType,uuid:d.uuid,cdnUrl:d.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(c){console.warn("Upload error",c),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),c instanceof U?c.isCancel||t.setValue("uploadError",c):t.setValue("uploadError",new Error("Unexpected error"))}}};l(it,"FileItem");it.template=` {{itemName}}{{errorText}} `;it.activeInstances=new Set;var jt=class extends y{constructor(){super();u(this,"_handleBackdropClick",l(()=>{this._closeDialog()},"_handleBackdropClick"));u(this,"_closeDialog",l(()=>{this.setOrAddState("*modalActive",!1)},"_closeDialog"));u(this,"_handleDialogClose",l(()=>{this._closeDialog()},"_handleDialogClose"));u(this,"_handleDialogMouseDown",l(t=>{this._mouseDownTarget=t.target},"_handleDialogMouseDown"));u(this,"_handleDialogMouseUp",l(t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()},"_handleDialogMouseUp"));this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};l(jt,"Modal"),u(jt,"StateConsumerScope","modal");jt.template=``;var Je=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}};l(Je,"UiMessage");var ae=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};l(ae,"MessageBox");ae.template=` {{msgTxt}}`;var ce=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",b.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",O(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));this.emit(k.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var d,p;let t=!!this.cfg.multiple,e=t?(d=this.cfg.multipleMin)!=null?d:0:1,r=t?(p=this.cfg.multipleMax)!=null?p:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!a,tooFew:o,tooMany:a,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Je,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let g of t){let m=this.uploadCollection.read(g);m.getValue("fileInfo")&&!m.getValue("validationErrorMsg")&&(r.succeed+=1),m.getValue("isUploading")&&(r.uploading+=1),(m.getValue("validationErrorMsg")||m.getValue("uploadError"))&&(r.failed+=1),m.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:a}=this._validateFilesCount(),c=r.failed===0&&r.limitOverflow===0,h=!1,d=!1,p=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?h=!0:(d=!0,p=r.total===r.succeed&&n&&c),this.set$({doneBtnVisible:d,doneBtnEnabled:p,uploadBtnVisible:h,addMoreBtnEnabled:r.total===0||!o&&!a,addMoreBtnVisible:!a||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=l(r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})},"localizedText");return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};l(ce,"UploadList");ce.template=`{{headerText}} `;var he=class extends v{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.URL);u(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Q.URL_TAB}),this.$["*currentActivity"]=b.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};l(he,"UrlSource");he.template=` `;var is=l(()=>typeof navigator.permissions!="undefined","canUsePermissionsApi");var ue=class extends v{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.CAMERA);u(this,"_unsubPermissions",null);u(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:is(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});u(this,"_onActivate",l(()=>{is()&&this._subscribePermissions(),this._capture()},"_onActivate"));u(this,"_onDeactivate",l(()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()},"_onDeactivate"));u(this,"_handlePermissionsChange",l(()=>{this._capture()},"_handlePermissionsChange"));u(this,"_setPermissionsState",O(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Q.CAMERA}),this.set$({"*currentActivity":b.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};l(ue,"CameraSource");ue.template=` `;var $i=class extends v{constructor(){super(...arguments);u(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}};l($i,"UploadCtxProviderClass");var yr=$i;var de=class extends v{constructor(){super(...arguments);u(this,"activityType",b.activities.DETAILS);u(this,"pauseRender",!0);u(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=b.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Ze(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=ze(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=l((n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))},"tmpSub");r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let a=L(n,N("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(a))}})})}};l(de,"UploadDetails");de.template=` `;var Si=class{constructor(){u(this,"captionL10nStr","confirm-your-action");u(this,"messageL10Str","are-you-sure");u(this,"confirmL10nStr","yes");u(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}};l(Si,"UiConfirmation");var pe=class extends b{constructor(){super(...arguments);u(this,"activityType",b.activities.CONFIRMATION);u(this,"_defaults",new Si);u(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":b.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};l(pe,"ConfirmationDialog");pe.template=`{{activityCaption}} `;var fe=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};l(fe,"ProgressBarCommon");fe.template=` `;var me=class extends y{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};l(me,"ProgressBar");me.template='';var Y="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Ht=class extends y{constructor(){super();u(this,"init$",{...this.init$,checkerboard:!1,src:Y})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${br()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Y}};l(Ht,"FilePreview");Ht.template=' ';Ht.bindAttributes({checkerboard:"checkerboard"});var vr="--cfg-ctx-name",R=class extends y{get cfgCssCtxName(){return this.getCssData(vr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(vr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};l(R,"CloudImageEditorBase");function Cr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}l(Cr,"normalize");function F(...s){let i=Cr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}l(F,"classNames");function wr(s,...i){let t=Cr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}l(wr,"applyClassNames");var Tr=l(s=>{if(!s)return X;let i=Bs(s).filter(t=>X.includes(t));return i.length===0?X:i},"parseTabs");function xr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":X,"*tabId":P.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Y,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Mt(X),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Y,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=N($t(i),"preview"),r=L(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}l(xr,"initState");var Er=` Network error `;var tt=class extends R{constructor(){super();u(this,"_debouncedShowLoader",O(this._showLoader.bind(this),300));this.init$={...this.init$,...xr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$["*tabId"]===P.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Ws(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Xs(this.$.cdnUrl),r=ir(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=L(this.$["*originalUrl"],N("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===P.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Y&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Y)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=wi(t)}),this.sub("tabs",t=>{this.$["*tabList"]=Tr(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=F("image",{image_hidden_to_cropper:t===P.CROP,image_hidden_effects:t!==P.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=N($t(t),"preview"),n=L(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};l(tt,"CloudImageEditorBlock"),u(tt,"className","cloud-image-editor");tt.template=Er;tt.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ge=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=C&&t.width<=C)return!0;let e=t.height<=C&&(i.includes("n")||i.includes("s")),r=t.width<=C&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],a=J("mask",{id:"backdrop-mask"}),c=J("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=J("rect",{x:t,y:e,width:r,height:n,fill:"black"});a.appendChild(c),a.appendChild(h);let d=J("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(d),o.appendChild(a),this._backdropMask=a,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,a=e==="",c=e.length===2,{x:h,y:d,width:p,height:f}=i;if(a){let m={x:h+p/3,y:d+f/3,width:p/3,height:f/3};Pt(n,m)}else{let m=Et(Math.min(p,f)/(24*2+34)/2,0,1),{d:_,center:S}=c?Ls(i,e,m):Rs(i,e,m),A=Math.max(Ki*Et(Math.min(p,f)/Ki/3,0,1),Is);Pt(n,{x:S[0]-A,y:S[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let g=this._shouldThumbBeDisabled(e);o.setAttribute("class",F("thumb",{"thumb--hidden":g,"thumb--visible":!g}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=J("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=J("rect",{fill:"transparent"}),a=J("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(a),n.appendChild(o),i[r]={direction:r,pathNode:a,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=J("svg"),t=J("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=J("line",{x1:`${Ve*e}%`,y1:"0%",x2:`${Ve*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=J("line",{x1:"0%",y1:`${Ve*e}%`,x2:"100%",y2:`${Ve*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),a=t.x-n,c=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[a,c],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,a=n-this._dragStartPoint[0],c=o-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this._calcCropBox(h,[a,c]);d&&(this.$["*cropBox"]=d)}_calcCropBox(i,t){var h,d;let[e,r]=t,n=this.$["*imageBox"],o=(h=this._dragStartCrop)!=null?h:this.$["*cropBox"],a=(d=this.$["*cropPresetList"])==null?void 0:d[0],c=a?a.width/a.height:void 0;if(i===""?o=Ps({rect:o,delta:[e,r],imageBox:n}):o=Ms({rect:o,delta:[e,r],direction:i,aspectRatio:c,imageBox:n}),!Object.values(o).every(p=>Number.isFinite(p)&&p>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return ee(se(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Ns(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Us(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",F("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=C||i.width<=C,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",F({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};l(ge,"CropFrame");ge.template='';var ut=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=F({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};l(ut,"EditorButtonControl");ut.template=` {{title}}`;function Bo(s){let i=s+90;return i=i>=360?0:i,i}l(Bo,"nextAngle");function zo(s,i){return s==="rotate"?Bo(i):["mirror","flip"].includes(s)?!i:null}l(zo,"nextValue");var Xt=class extends ut{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=zo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};l(Xt,"EditorCropButtonControl");var Qe={FILTER:"filter",COLOR_OPERATION:"color_operation"},dt="original",be=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?Qe.FILTER:Qe.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===dt?void 0:this.$.value,filter:this._filter===dt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ct[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===Qe.FILTER){let a=n;if(o){let{name:c,amount:h}=o;a=c===this._filter?h:n}this.$.value=a,this.$.defaultValue=a}if(this._controlType===Qe.COLOR_OPERATION){let a=typeof o!="undefined"?o:e;this.$.value=a,this.$.defaultValue=a}}apply(){let t;this._controlType===Qe.FILTER?this._filter===dt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};l(be,"EditorSlider");be.template=` `;function ti(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:l(()=>{i.naturalWidth===0&&(i.src=Y)},"cancel")}}l(ti,"preloadImage");function ei(s){let i=[];for(let n of s){let o=ti(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:l(()=>{i.forEach(n=>{n.cancel()})},"cancel")}}l(ei,"batchPreloadImages");var kt=class extends ut{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==dt?{name:this._filter,amount:o}:void 0,L(this._originalUrl,N(xi,$t(a),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:a,cancel:c}=ti(n);this._cancelPreload=c,a.catch(h=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:h})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===dt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};l(kt,"EditorFilterControl");kt.template=` `;var qt=class extends ut{constructor(){super(...arguments);u(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ct[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};l(qt,"EditorOperationControl");var Ar=l((s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}},"throttle");function $r(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}l($r,"pick");function _e(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return L(s,N(xi,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}l(_e,"viewerImageSrc");function jo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}l(jo,"validateCrop");var ye=class extends R{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=O(this._commit.bind(this),300),this._handleResizeThrottled=Ar(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=$r(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=ie({width:i.naturalWidth,height:i.naturalHeight},r),a;if(o.width>n.width-t*2||o.height>n.height-t*2){let c=o.width/o.height,h=n.width/n.height;if(c>h){let d=n.width-t*2,p=d/c,f=0+t,g=t+(n.height-t*2)/2-p/2;a={x:f,y:g,width:d,height:p}}else{let d=n.height-t*2,p=d*c,f=t+(n.width-t*2)/2-p/2,g=0+t;a={x:f,y:g,width:p,height:d}}}else{let{width:c,height:h}=o,d=t+(n.width-t*2)/2-c/2,p=t+(n.height-t*2)/2-h/2;a={x:d,y:p,width:c,height:h}}this.$["*imageBox"]=se(a)}_alignCrop(){var p;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:a,y:c}=this.$["*imageBox"];if(n){let{dimensions:[f,g],coords:[m,_]}=n,{width:S}=ie(this._imageSize,r),A=o/S;i=ee(se({x:a+m*A,y:c+_*A,width:f*A,height:g*A}),this.$["*imageBox"])}let h=(p=this.$["*cropPresetList"])==null?void 0:p[0],d=h?h.width/h.height:void 0;if(!Ds(i,t)||d&&!Fs(i,d)){let f=t.width/t.height,g=t.width,m=t.height;d&&(f>d?g=Math.min(t.height*d,t.width):m=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-g/2,y:t.y+t.height/2-m/2,width:g,height:m}}this.$["*cropBox"]=ee(se(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:a}=r,c=ie({width:e.width,height:e.height},a);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(a*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-c.width/2,-c.height/2,c.width,c.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=F({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:a,height:c}=ie(this._imageSize,r),{width:h,height:d}=i,p=n/a,f=o/c;return[Et(Math.round(h/p),1,a),Et(Math.round(d/f),1,c)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:a,y:c}=t,{width:h,height:d}=ie(this._imageSize,r),{x:p,y:f}=i,g=n/h,m=o/d,_=this._getCropDimensions(),S={dimensions:_,coords:[Et(Math.round((p-a)/g),0,h-_[0]),Et(Math.round((f-c)/m),0,d-_[1])]};if(!jo(S)){console.error("Cropper is trying to create invalid crop object",{payload:S});return}if(!(_[0]===h&&_[1]===d))return S}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),a={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=a}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=F({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(_e(i,e,t)),{promise:n,cancel:o,image:a}=ti(r),c=this._handleImageLoading(r);return a.addEventListener("load",c,{once:!0}),a.addEventListener("error",c,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>a).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(a)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};l(ye,"EditorImageCropper");ye.template=` `;function ss(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}l(ss,"linspace");function Ho(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}l(Wo,"calculateOpacities");function Xo(s,i){return s.map((t,e)=>tn-o)}l(Sr,"keypointsRange");var ii=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=O(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(_e(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=l(()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(c=>c.value===e),"shouldSkip");if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let a=this._handleImageLoading(n.src);o.addEventListener("load",a,{once:!0}),o.addEventListener("error",a,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let c=this._keypoints,h=c.findIndex(p=>p.value>e),d=h{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ct[i],r=this._keypoints.map(a=>a.value),n=Wo(r,t,e),o=Xo(r,e);for(let[a,c]of Object.entries(this._keypoints))c.opacity=n[a],c.zIndex=o[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(h=>h.src),{images:r,promise:n,cancel:o}=ei(e);r.forEach(h=>{let d=this._handleImageLoading(h.src);h.addEventListener("load",d),h.addEventListener("error",d)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let a=this._operation,c=this._filter;await n,this._isActive&&this._isSame(a,c)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((h,d)=>{let p=r[d];p.classList.add("fader-image"),h.image=p,this._container.appendChild(p)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Sr(e,r).map(c=>this._imageSrc({url:i,filter:t,operation:e,value:c})),{cancel:a}=ei(o);this._cancelBatchPreload=a}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let a=this._imageSrc({operation:t,value:e});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Sr(t,e).map(a=>this._constructKeypoint(t,a)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=F({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};l(ii,"EditorImageFader");var qo=1,ve=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>qo?this.scrollLeft+=e:this.scrollLeft+=t})}};l(ve,"EditorScroller");ve.template=" ";function Go(s){return` `}l(Go,"renderTabToggle");function Ko(s){return` `}l(Ko,"renderTabContent");var Ce=class extends R{constructor(){super();u(this,"_updateInfoTooltip",O(()=>{var o,a;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===P.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let c=((a=t==null?void 0:t.filter)==null?void 0:a.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+c}else r=this.l10n(dt);else if(this.$["*tabId"]===P.TUNING&&e){n=!0;let c=(t==null?void 0:t[e])||ct[e].zero;r=e+" "+c}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":dt,"*currentOperation":null,showLoader:!1,filters:rr,colorOperations:sr,cropOperations:nr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=O(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===P.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new qt;return e.operation=t,e}_createFilterControl(t){let e=new kt;return e.filter=t,e}_createToggleControl(t){let e=new Xt;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===P.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===P.FILTERS?[dt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===P.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===P.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of X){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(_e(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=ei([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of X){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};l(Ce,"EditorToolbar");Ce.template=` {{*operationTooltip}} `;var Gt=class extends y{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return F("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};l(Gt,"LrBtnUi");Gt.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Gt.template=` {{text}}`;var we=class extends y{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};l(we,"LineLoaderUi");we.template=``;var ki={transition:"transition",visible:"visible",hidden:"hidden"},Te=class extends y{constructor(){super(),this._visible=!1,this._visibleStyle=ki.visible,this._hiddenStyle=ki.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",wr(this,{[ki.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(ki.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};l(Te,"PresenceToggle");Te.template=" ";var xe=class extends y{constructor(){super();u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let a=document.createDocumentFragment(),c=document.createElement("div"),h=document.createElement("div");c.className="minor-step",h.className="border-step",a.appendChild(h);for(let p=0;p`;var si=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new tt,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};l(si,"CloudImageEditorActivity");var Yo=l(function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},"escapeRegExp"),kr=l(function(s,i="i"){let t=s.split("*").map(Yo);return new RegExp("^"+t.join(".+")+"$",i)},"wildcardRegexp");var Zo=l(s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,a)=>{let c=r[a];return o+`${a}: ${c};`},"");return t+`${e}{${n}}`},""),"styleToCss");function Or({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Zo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}l(Or,"buildStyles");var Ot={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in Ot){let t=Ot[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ir=l(function(s,i,t){s in Ot||(Ot[s]=[]),Ot[s].push([i,t])},"registerMessage"),Lr=l(function(s,i){s in Ot&&(Ot[s]=Ot[s].filter(t=>t[0]!==i))},"unregisterMessage");function Rr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}l(Rr,"queryString");var Ee=class extends v{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.EXTERNAL);u(this,"_iframe",null);u(this,"updateCssData",l(()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())},"updateCssData"));u(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=b.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=D(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=kr(r);for(let[o,a]of Object.entries(t.alternatives))if(n.test(o))return a}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Or(t)})}remoteUrl(){var a,c;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((c=(a=this.getCssData("--l10n-locale-name"))==null?void 0:a.split("-"))==null?void 0:c[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Rr(n),o.toString()}mountIframe(){let t=Ue({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ir("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Lr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};l(Ee,"ExternalSource");Ee.template=` {{activityCaption}} `;var Kt=class extends y{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;D(i).forEach(e=>{let r=Ue({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};l(Kt,"Tabs");Kt.bindAttributes({"tab-list":null,default:null});Kt.template=` `;var ri=class extends v{constructor(){super();u(this,"processInnerHtml",!0);u(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return rs.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,Ui(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var e,r;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(a=>a.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let a of n){let c=document.createElement("input");c.type="hidden",c.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,c.value=a!=null?a:"",this._dynamicInputsContainer.appendChild(c)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let a=o.find(p=>!p.isValid),c=(r=a==null?void 0:a.validationErrorMessage)!=null?r:(e=a==null?void 0:a.uploadError)==null?void 0:e.message,h=this.$["*message"];h=h!=null&&h.isError?`${h.caption}. ${h.text}`:void 0;let d=c!=null?c:h;d?this._validationInputElement.setCustomValidity(d):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(a=>a.isUploaded&&a.isValid)){this.$.output={groupData:void 0,files:t};return}let r=this.getUploadClientOptions(),n=t.map(a=>a.uuid+(a.cdnUrlModifiers?`/${a.cdnUrlModifiers}`:"")),o=await Ss(n,r);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};l(ri,"DataOutputClass");ri.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var rs=ri;var ni=class extends b{};l(ni,"ActivityHeader");var Ae=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};l(Ae,"Select");Ae.template=``;var G={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Ur={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Z=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,src:"",ppIcon:G.PLAY,fsIcon:G.FS_ON,volIcon:G.VOL_ON,capIcon:G.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Ur.exitFullscreen():Ur.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===G.CAP_OFF?(this.$.capIcon=G.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Z.is+":captions","1")):(this.$.capIcon=G.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Z.is+":captions"))}toggleSound(){this.$.volIcon===G.VOL_ON?(this.$.volIcon=G.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=G.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Z.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Z.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=G.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=G.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=G.FS_OFF:this.$.fsIcon=G.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Z.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};l(Z,"Video");Z.template=` `;Z.bindAttributes({video:"video",src:"src"});var Jo="css-src";function oi(s){return class extends s{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0);u(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),ui({element:this,attribute:Jo,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}l(oi,"shadowed");var Yt=class extends oi(y){};l(Yt,"ShadowWrapper");var $e=class extends y{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};l($e,"Copyright"),u($e,"template",`Powered by Uploadcare`);var vt=class extends Yt{constructor(){super(...arguments);u(this,"requireCtxName",!0);u(this,"init$",vi(this));u(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};l(vt,"SolutionBlock");var Se=class extends vt{};l(Se,"FileUploaderRegular");Se.template=` `;var ke=class extends vt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||b.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=b.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||b.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};l(ke,"FileUploaderMinimal");ke.template=` `;var Oe=class extends vt{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=b.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==b.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||b.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||b.activities.START_FROM)&&(this.$["*currentActivity"]=b.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};l(Oe,"FileUploaderInline");Oe.template=` `;var li=class extends oi(tt){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};l(li,"CloudImageEditor");function Oi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}l(Oi,"registerBlocks");var ns="LR";async function Pr(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ns]){t(window[ns]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ns];i&&Oi(n),t(n)},document.head.appendChild(r)})}l(Pr,"connectBlocksFrom");return jr(Qo);})();
\ No newline at end of file
diff --git a/web/blocks.min.js b/web/blocks.min.js
index d89b21f23..092fa7930 100644
--- a/web/blocks.min.js
+++ b/web/blocks.min.js
@@ -24,4 +24,4 @@
*
*/
var Lr=Object.defineProperty;var Ur=(s,i,t)=>i in s?Lr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Ur(s,typeof i!="symbol"?i+"":i,t),t);var Rr=Object.defineProperty,Pr=(s,i,t)=>i in s?Rr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,yi=(s,i,t)=>(Pr(s,typeof i!="symbol"?i+"":i,t),t);function Mr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Mr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.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"}),ss="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Nr=ss.length-1,Zt=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Fr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var es="__default__";function Br(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||es;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=es;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function Vr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function zr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Dr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):rs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var we="{{",Yt="}}",jr="skip-text";function Hr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(jr))&&r.textContent.includes(we)&&r.textContent.includes(Yt)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Wr=function(s,i){Hr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(Yt);)e.textContent.startsWith(we)?(n=e.textContent.indexOf(Yt)+Yt.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(we),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(we,"").replace(Yt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Xr=[Fr,Br,Vr,zr,Wr],Te="'",Nt='"',qr=/\\([0-9a-fA-F]{1,6} ?)/g;function Gr(s){return(s[0]===Nt||s[0]===Te)&&(s[s.length-1]===Nt||s[s.length-1]===Te)}function Kr(s){return(s[0]===Nt||s[0]===Te)&&(s=s.slice(1)),(s[s.length-1]===Nt||s[s.length-1]===Te)&&(s=s.slice(0,-1)),s}function Yr(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\
-`,"\\n"),i=Yr(i),i=Nt+i+Nt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var is=0,Mt=null,ht=null,_t=class extends HTMLElement{constructor(){super(),yi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 _t}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Zt.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 s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=_t.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=_t.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=_t.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=_t.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=_t.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=_t.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])rs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Xr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ht==null||ht.delete(this.updateCssData),ht!=null&&ht.size||(Mt==null||Mt.disconnect(),Mt=null,ht=null)},100)))}static reg(s,i=!1){s||(is++,s=`${C.AUTO_TAG_PRFX}-${is}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" 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(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Zr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){ht||(ht=new Set),ht.add(this.updateCssData),Mt||(Mt=new MutationObserver(s=>{s[0].type==="attributes"&&ht.forEach(i=>{i()})}),Mt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},Dt=_t;yi(Dt,"template");var _i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(_i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),_i.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}};_i.appMap=Object.create(null);function vi(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function Jr(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function Jt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&Jr(i,s.attributes),s.styles&&vi(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Jt(t);i.appendChild(e)}),i}var ns="idb-store-ready",Qr="symbiote-db",tn="symbiote-idb-update_",en=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ns,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return tn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,os.clear(this.name)}},os=class{static get readyEventName(){return ns}static open(s=Qr,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new en(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};yi(os,"_reg",Object.create(null));var S=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),sn=Object.freeze({[S.UPLOAD_START]:"LR_UPLOAD_START",[S.REMOVE]:"LR_REMOVE",[S.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[S.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[S.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[S.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[S.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[S.DATA_OUTPUT]:"LR_DATA_OUTPUT",[S.DONE_FLOW]:"LR_DONE_FLOW",[S.INIT_FLOW]:"LR_INIT_FLOW"}),xe=class{constructor(i){h(this,"_timeoutStore",new Map);h(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));let e=sn[i];window.dispatchEvent(new CustomEvent(e,{detail:{ctx:this._getCtxName(),type:e,data:t}}))}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};function I(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var ls="--uploadcare-blocks-window-height",It=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(ls)}};h(It,"clientsRegistry",new Set),h(It,"flush",I(()=>{document.documentElement.style.setProperty(ls,`${window.innerHeight}px`)},100));var Ee=(s,i)=>new Intl.PluralRules(s).select(i);var rn=s=>s,Ci="{{",cs="}}",as="plural:";function Qt(s,i,t={}){var o;let{openToken:e=Ci,closeToken:r=cs,transform:n=rn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function hs(s){let i=[],t=s.indexOf(Ci);for(;t!==-1;){let e=s.indexOf(cs,t),r=s.substring(t+2,e);if(r.startsWith(as)){let n=s.substring(t+2,e).replace(as,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ci,e)}return i}var ut=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ae=({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=setTimeout(()=>{a.disconnect(),e()},r),o=c=>{let u=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&u!==null&&(clearTimeout(n),a.disconnect(),t(u))},l=s.getAttribute(i);l!==null&&(clearTimeout(n),t(l));let a=new MutationObserver(c=>{let u=c[c.length-1];o(u)});a.observe(s,{attributes:!0,attributeFilter:[i]})};var us=new Set;function te(s){us.has(s)||(us.add(s),console.warn(s))}function ds(s){return Object.prototype.toString.call(s)==="[object Object]"}var nn=/\W|_/g;function on(s){return s.split(nn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ps(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>ft(t,{ignoreKeys:i})):s}function ft(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ps(s,{ignoreKeys:i});if(!ds(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ds(r)?r=ft(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ps(r,{ignoreKeys:i})),t[on(e)]=r}return t}var ln=s=>new Promise(i=>setTimeout(i,s));function Si({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var an={factor:2,time:100};function cn(s,i=an){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>ln(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Ft=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Ft.prototype),this.originalProgressEvent=t}},Se=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},yt=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,yt.prototype)}},hn=500,ms=({check:s,interval:i=hn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Se(e,()=>{o&&clearTimeout(o),n(new yt("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new yt("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),A={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"},Ie="application/octet-stream",gs="original",vt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Se(r,()=>{u=!0,a.abort(),l(new yt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let x=$.split(": "),T=x.shift(),w=x.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,b=a.status;o({request:d,data:f,headers:m,status:b})}},a.onerror=d=>{u||l(new Ft(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function un(s,...i){return s}var dn=({name:s})=>s?[s]:[],pn=un,fn=()=>new FormData,bs=s=>!1,ke=s=>typeof Blob!="undefined"&&s instanceof Blob,Oe=s=>typeof File!="undefined"&&s instanceof File,Le=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Bt=s=>ke(s)||Oe(s)||bs()||Le(s),mn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",gn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),bn=s=>!!s&&typeof s=="object"&&"data"in s&&Bt(s.data);function _n(s,i,t){if(bn(t)){let{name:e,contentType:r}=t,n=pn(t.data,e,r!=null?r:Ie),o=dn({name:e,contentType:r});s.push([i,n,...o])}else if(gn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else mn(t)&&t&&s.push([i,t.toString()])}function yn(s){let i=[];for(let[t,e]of Object.entries(s))_n(i,t,e);return i}function Ii(s){let i=fn(),t=yn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},vn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},dt=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=vn(t)),e.toString()},Cn="6.8.0",wn="UploadcareUploadClient",Tn=Cn;function kt(s){return Si({libraryName:wn,libraryVersion:Tn,...s})}var xn="RequestThrottledError",fs=15e3,En=1e3;function An(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return fs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:fs}function Ct(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return cn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===xn&&r{let i="";return(ke(s)||Oe(s)||Le(s))&&(i=s.type),i||Ie},ys=s=>{let i="";return Oe(s)&&s.name?i=s.name:ke(s)||bs()?i="":Le(s)&&s.name&&(i=s.name),i||gs};function ki(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function $n(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=A.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({file:{data:s,name:t||ys(s),contentType:e||_s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ki(l),signature:n,expire:o,source:u,metadata:b}),signal:a,onProgress:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var xi;(function(s){s.Token="token",s.FileInfo="file_info"})(xi||(xi={}));function Sn(s,{publicKey:i,baseURL:t=A.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},url:dt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:ki(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:b}),signal:u}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var j;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(j||(j={}));var In=s=>"status"in s&&s.status===j.Error;function kn(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=A.retryNetworkErrorMaxTimes}={}){return Ct(()=>vt({method:"GET",headers:i?{"X-UC-User-Agent":kt({publicKey:i,integration:r,userAgent:n})}:void 0,url:dt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=ft(JSON.parse(a));if("error"in d&&!In(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function On(s,{publicKey:i,baseURL:t=A.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:a,userAgent:c})},url:dt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let b=ft(JSON.parse(p));if("error"in b)throw new P(b.error.content,b.error.errorCode,f,b,m);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function vs(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"GET",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},url:dt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Ln(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=A.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({filename:e||gs,size:s,content_type:t||Ie,part_size:r,UPLOADCARE_STORE:ki(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:b}),signal:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w.parts=Object.keys(w.parts).map(V=>w.parts[V]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Un(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Ie}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Rn(s,{publicKey:i,baseURL:t=A.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",url:dt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},data:Ii({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Oi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return ms({check:u=>vs(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function Pn(s){return"defaultEffects"in s}var pt=class{constructor(i,{baseCDN:t=A.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);h(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=dt(t,`${r}/`),l=n?dt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,Pn(i)&&(this.defaultEffects=i.defaultEffects)}},Mn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:b,metadata:$})=>$n(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:x})=>Oi(x,{publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(x=>new pt(x,{baseCDN:b})),Nn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>vs(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new pt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Dn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Se(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Fn=window.WebSocket,Ei=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Bn=(s,i)=>s==="success"?{status:j.Success,...i}:s==="progress"?{status:j.Progress,...i}:{status:j.Error,...i},Ai=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ei);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Fn(i),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 e=JSON.parse(t.data.toString());switch(e.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(e.channel,Bn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},wi=null,Li=s=>{if(!wi){let i=typeof window=="undefined"?0:3e4;wi=new Ai(s,i)}return wi},Vn=s=>{Li(s).connect()};function zn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ms({check:c=>kn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case j.Error:return new P(u.error,u.errorCode);case j.Waiting:return!1;case j.Unknown:return new P(`Token "${s}" was not found.`);case j.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case j.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var jn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Li(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Se(t,()=>{a(),n(new yt("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case j.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case j.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case j.Error:a(),n(new P(c.msg,c.error_code))}})}),Hn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,pusherKey:$=A.pusherKey,metadata:x})=>Promise.resolve(Vn($)).then(()=>Sn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,metadata:x})).catch(T=>{let w=Li($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===xi.FileInfo?T:Dn([({signal:w})=>zn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:w}),({signal:w})=>jn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof P)throw T;return T}).then(T=>Oi(T.uuid,{publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:u})).then(T=>new pt(T,{baseCDN:r})),Ti=new WeakMap,Wn=async s=>{if(Ti.has(s))return Ti.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Ti.set(s,i),i},Cs=async s=>{if(Oe(s)||ke(s))return s.size;if(Le(s))return(await Wn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Xn=(s,i=A.multipartMinFileSize)=>s>=i,ws=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Bt(s)&&t.test(s)},Ui=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Bt(s)&&t.test(s)},qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},Kn=async(s,i,t)=>e=>Gn(s,e,i,t),Yn=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Un(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Zn=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:b,multipartChunkSize:$=A.multipartChunkSize,maxConcurrentRequests:x=A.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let V=e!=null?e:await Cs(s),at,St=(R,z)=>{if(!c)return;at||(at=Array(R).fill(0));let J=tt=>tt.reduce((ct,bi)=>ct+bi,0);return tt=>{tt.isComputable&&(at[z]=tt.value,c({isComputable:!0,value:J(at)/R}))}};return b||(b=_s(s)),Ln(V,{publicKey:i,contentType:b,fileName:t||ys(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:z})=>{let J=await Kn(s,V,$);return Promise.all([R,qn(x,z.map((tt,ct)=>()=>Yn(J(ct),tt,{publicKey:i,contentType:b,onProgress:St(z.length,ct),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Rn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Oi(R.uuid,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new pt(R,{baseCDN:T}))};async function Ri(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:b,multipartChunkSize:$,maxConcurrentRequests:x,baseCDN:T=A.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,pusherKey:at,metadata:St}){if(Bt(s)){let R=await Cs(s);return Xn(R,b)?Zn(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:x,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St}):Mn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St})}if(Ui(s))return Hn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:at,metadata:St});if(ws(s))return Nn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var $i=class{constructor(i,{baseCDN:t=A.baseCDN}={}){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new pt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Jn=s=>{for(let i of s)if(!Bt(i))return!1;return!0},Qn=s=>{for(let i of s)if(!ws(i))return!1;return!0},to=s=>{for(let i of s)if(!Ui(i))return!1;return!0};function Ts(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b=A.multipartChunkSize,baseCDN:$=A.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!Jn(s)&&!to(s)&&!Qn(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let V,at=!0,St=s.length,R=(z,J)=>{if(!a)return;V||(V=Array(z).fill(0));let tt=ct=>ct.reduce((bi,Or)=>bi+Or)/z;return ct=>{if(!ct.isComputable||!at){at=!1,a({isComputable:!1});return}V[J]=ct.value,a({isComputable:!0,value:tt(V)})}};return Promise.all(s.map((z,J)=>Bt(z)||Ui(z)?Ri(z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(St,J),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b,baseCDN:$,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T}).then(tt=>tt.uuid):z)).then(z=>On(z,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(J=>new $i(J,{baseCDN:$})).then(J=>(a&&a({isComputable:!0,value:1}),J)))}var $e=class{constructor(i){h(this,"_concurrency",1);h(this,"_pending",[]);h(this,"_running",0);h(this,"_resolvers",new Map);h(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var Pi=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),Mi=s=>({...Pi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Ue=s=>({...Mi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $e(1),"*uploadCollection":null});function xs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var H=s=>`*cfg/${s}`;var Ni="lr-",_=class extends Dt{constructor(){super();h(this,"requireCtxName",!1);h(this,"allowCustomTemplate",!0);h(this,"init$",Pi());h(this,"updateCtxCssData",()=>{te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(xs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=hs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Qt(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Ee(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ni}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ae({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),It.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),It.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new xe(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Qt(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=H(r);return this.$[o]=n,!0},get:(e,r)=>{let n=H(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ut(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(H(t));r.ctx.has(r.name)?this.sub(H(t),e):(this.bindCssData(`--cfg-${ut(t)}`),this.sub(`--cfg-${ut(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ni)?t:Ni+t)}};h(_,"StateConsumerScope",null),h(_,"className","");var Es="active",ee="___ACTIVITY_IS_ACTIVE___",et=class extends _{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Mi(this));h(this,"_debouncedHistoryFlush",I(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=et._activityRegistry[this.activityKey];this[ee]=!1,this.removeAttribute(Es),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=et._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ee]=!0,this.setAttribute(Es,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ee]?this._deactivate():this.activityType===t&&!this[ee]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!et._activityRegistry[this.activityKey]}get isActivityActive(){return this[ee]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;et._activityRegistry||(et._activityRegistry=Object.create(null)),et._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),et._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(et._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===r);n=(e=l==null?void 0:l.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},g=et;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ie=33.333333333333336,y=1,Di=24,As=6;function Ot(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function Y(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Ot(t,i),t}function $s(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Ss(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Is(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function ks({rect:s,delta:[i,t],imageBox:e}){return zt({...s,x:s.x+i,y:s.y+t},e)}function zt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function eo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Rs(s,i){return Math.abs(s.width/s.height-i)<.1}function jt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ps(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Ht(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function wt(s,i,t){return Math.min(Math.max(s,i),t)}var Pe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var Z=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Ms=s=>s?s.split(",").map(i=>i.trim()):[],Lt=s=>s?s.join(","):"";var Ns="blocks",Ds="0.30.4";function Fs(s){return Si({...s,libraryName:Ns,libraryVersion:Ds})}var Bs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Me=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Bs(i)).join("/-/"),M=(...s)=>{let i=Me(...s);return i?`-/${i}/`:""};function Vs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function js(s){let i=Hs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Bs(n))}function Hs(s){let i=new URL(s),t=Vs(s),e=Ws(t)?Xs(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ws(s){return s.startsWith("http")}function Xs(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var O=(s,i,t)=>{let e=new URL(Hs(s));if(t=t||Vs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ws(t)){let r=Xs(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},Tt=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var se=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Fi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],Bi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),qs=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),re=s=>{let i=s==null?void 0:s.type;return i?Bi(i,se):!1};var st=1e3,Ut=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ne=s=>Math.ceil(s*100)/100,Gs=(s,i=Ut.AUTO)=>{let t=i===Ut.AUTO;if(i===Ut.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(co+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var De=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Zt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new Ne(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var Ys=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:pt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!1);h(this,"isCtxOwner",!1);h(this,"init$",Ue(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",I(this._runValidators.bind(this),100));h(this,"_flushOutputItems",I(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(S.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));h(this,"_handleCollectonUpdate",(t,e,r)=>{var n;this._runValidators();for(let o of r)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()});h(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,this.emit(S.UPLOAD_PROGRESS,l,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&this.emit(S.UPLOAD_FINISH,l,{debounce:!0})}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(S.UPLOAD_ERROR,e.readProp(o,"uploadError"))}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(S.VALIDATION_ERROR,e.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(S.CLOUD_MODIFICATION,e.readProp(o,"cdnUrlModifiers"))})})}setUploadMetadata(t){te("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof v?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new De({typedSchema:Ys,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:re(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:re(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Lt(Fi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?se:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Lt(se)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Z.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(S.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(S.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Fi([...e?se:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Bi(o,n),c=qs(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Gs(e)})}_validateMultipleLimit(t){let e=this.uploadCollection.items(),r=e.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&e.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Pe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ps(l,a,c),d=M(`crop/${u.width}x${u.height}/${u.x},${u.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:O(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,l;let e=E.getCtx(t).store,r=e.fileInfo||{name:e.fileName,originalFilename:e.fileName,size:e.fileSize,isImage:e.isImage,mimeType:e.mimeType};return{...r,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(l=(o=e.cdnUrl)!=null?o:r.cdnUrl)!=null?l:null,validationErrorMessage:e.validationErrorMsg,uploadError:e.uploadError,isUploaded:!!e.uuid&&!!e.fileInfo,isValid:!e.validationErrorMsg&&!e.uploadError,fullPath:e.fullPath,uploadProgress:e.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});var G={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function ho(s,i){if(typeof i=="number")return G[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&G[s]!==i?`${s}`:"";if(s==="filter"){if(!i||G[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Js=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function xt(s){return Me(...Js.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return ho(i,t)}).filter(i=>!!i))}var Fe=Me("format/auto","progressive/yes"),mt=([s])=>typeof s!="undefined"?Number(s):void 0,Zs=()=>!0,uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),po=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),fo={enhance:mt,brightness:mt,exposure:mt,gamma:mt,contrast:mt,saturation:mt,vibrance:mt,warmth:mt,filter:uo,mirror:Zs,flip:Zs,rotate:mt,crop:po};function Qs(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Js.includes(e))continue;let n=fo[e],o=n(r);i[e]=o}return i}var L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),W=[L.CROP,L.TUNING,L.FILTERS],tr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],er=["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"],ir=["rotate","mirror","flip"],rt=Object.freeze({brightness:{zero:G.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:G.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:G.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:G.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:G.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:G.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:G.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:G.enhance,range:[0,100],keypointsNumber:1},filter:{zero:G.filter,range:[0,100],keypointsNumber:1}});var mo="https://ucarecdn.com",go="https://upload.uploadcare.com",bo="https://social.uploadcare.com",Et={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Lt(W),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:mo,baseUrl:go,socialBaseUrl:bo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var X=s=>String(s),nt=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},k=s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},_o=s=>s==="auto"?s:k(s),yo={pubkey:X,multiple:k,multipleMin:nt,multipleMax:nt,confirmUpload:k,imgOnly:k,accept:X,externalSourcesPreferredTypes:X,store:_o,cameraMirror:k,sourceList:X,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:X,removeCopyright:k,cropPreset:X,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:X,cdnCname:X,baseUrl:X,socialBaseUrl:X,secureSignature:X,secureExpire:X,secureDeliveryProxy:X,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:X},sr=(s,i)=>{if(!(typeof i=="undefined"||i===null))try{return yo[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),Et[s]}};var Be=Object.keys(Et),vo=["metadata"],Co=s=>vo.includes(s),Ve=Be.filter(s=>!Co(s)),wo={...Object.fromEntries(Ve.map(s=>[ut(s),s])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),s]))},To={...Object.fromEntries(Be.map(s=>[ut(s),H(s)])),...Object.fromEntries(Be.map(s=>[s.toLowerCase(),H(s)]))},ze=class extends _{constructor(){super();h(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Et).map(([t,e])=>[H(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of Ve)this.sub(H(e),r=>{r!==Et[e]&&(t[e]=r)},!1);for(let e of Be){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,Ve.includes(e)){let o=[...new Set([ut(e),e.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[H(e)]!==n&&(typeof n=="undefined"||n===null?this.$[H(e)]=Et[e]:this.$[H(e)]=n)},get:()=>this.$[H(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=wo[t],o=sr(n,r),l=o!=null?o:Et[n],a=this;a[n]=l}};ze.bindAttributes(To);var xo=ze;var oe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};oe.template=``;oe.bindAttributes({name:"name",size:"size"});var Eo="https://ucarecdn.com",Rt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Eo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var rr=s=>[...new Set(s)];var le="--lr-img-",nr="unresolved",Wt=2,Xt=3,or=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ar=Object.create(null),lr;for(let s in Rt)ar[le+s]=((lr=Rt[s])==null?void 0:lr.default)||"";var je=class extends Dt{constructor(){super(...arguments);h(this,"cssInit$",ar)}$$(t){return this.$[le+t]}set$$(t){for(let e in t)this.$[le+e]=t[e]}sub$$(t,e){this.sub(le+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!or&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return M(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Rt.format.default}`,`quality/${this.$$("quality")||Rt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(or&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Qt(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(nr,""),this.img.onload=()=>{this.img.removeAttribute(nr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Rt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?rr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Wt+"x")}") ${n*Wt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Xt+"x")}") ${n*Xt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Wt))}") ${Wt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Xt))}") ${Xt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Wt+"x")+` ${e*Wt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Xt+"x")+` ${e*Xt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(Rt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[le+t]=r})}};var Vi=class extends je{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var ae=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=k(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};ae.template=` `;ae.bindAttributes({dropzone:null});var He=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};He.template=' ';function Ao(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function $o(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function cr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Ao(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var F={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},hr=["focus"],So=100,zi=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function ji(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=F.INACTIVE,o=f=>{s.shouldIgnore()&&f!==F.INACTIVE||(n!==f&&e.forEach(b=>b(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(F.INACTIVE)},c=()=>{i+=1,n===F.INACTIVE&&o(F.ACTIVE)},u=()=>{i-=1,l()||o(F.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(F.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let b=[f.x,f.y],$=s.element.getBoundingClientRect(),x=Math.floor(Io(b,$)),T=x{if(s.shouldIgnore())return;f.preventDefault();let b=await cr(f.dataTransfer);s.onItems(b),o(F.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),hr.forEach(f=>{window.addEventListener(f,a)}),()=>{zi.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),hr.forEach(f=>{window.removeEventListener(f,a)})}}var ur="lr-drop-area",qt=`${ur}/registry`,ce=class extends v{constructor(){super(),this.init$={...this.init$,state:F.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[qt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[qt]||(this.$[qt]=new Set),this.$[qt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=ji({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Z.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Z.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=ji({element:i,onChange:t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[qt]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[qt];i&&(i.delete(this),i.size===0&&E.deleteCtx(ur)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ce.template=` {{text}} `;ce.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var ko="src-type-",he=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${ko}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};he.template=` `;he.bindAttributes({type:null});var Hi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=` `}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function dr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function pr(s="#fff",i="rgba(0, 0, 0, .1)"){return dr(``)}function ue(s="hsl(209, 21%, 65%)",i=32,t=32){return dr(``)}function fr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),gt=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",I(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",I(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);this.emit(S.REMOVE,e,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(Tt(this.cfg.cdnCname,this._entry.getValue("uuid")),M(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await fr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{gt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),gt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),gt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));this.emit(S.UPLOAD_START,r,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=this.getUploadClientOptions();return Ri(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal,metadata:await this.getMetadataFor(t.uid)})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};gt.template=` {{itemName}}{{errorText}} `;gt.activeInstances=new Set;var de=class extends _{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogMouseDown",t=>{this._mouseDownTarget=t.target});h(this,"_handleDialogMouseUp",t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};h(de,"StateConsumerScope","modal");de.template=``;var We=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Xe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Xe.template=` {{msgTxt}}`;var qe=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",I(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));this.emit(S.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new We,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};qe.template=`{{headerText}} `;var Ge=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Z.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ge.template=` `;var Wi=()=>typeof navigator.permissions!="undefined";var Ke=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Wi(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{Wi()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",I(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Z.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ke.template=` `;var Xi=class extends v{constructor(){super(...arguments);h(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},Oo=Xi;var Ye=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ue(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=re(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=O(n,M("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};Ye.template=` `;var qi=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Ze=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new qi);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Ze.template=`{{activityCaption}} `;var Je=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};Je.template=` `;var Qe=class extends _{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};Qe.template='';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var pe=class extends _{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${pr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};pe.template=' ';pe.bindAttributes({checkerboard:"checkerboard"});var mr="--cfg-ctx-name",U=class extends _{get cfgCssCtxName(){return this.getCssData(mr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(mr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function gr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function D(...s){let i=gr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function br(s,...i){let t=gr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var _r=s=>{if(!s)return W;let i=Ms(s).filter(t=>W.includes(t));return i.length===0?W:i};function yr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":W,"*tabId":L.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Lt(W),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=M(xt(i),"preview"),r=O(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var vr=` Network error `;var ot=class extends U{constructor(){super();h(this,"_debouncedShowLoader",I(this._showLoader.bind(this),300));this.init$={...this.init$,...yr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$["*tabId"]===L.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=zs(this.$.cdnUrl);this.$["*originalUrl"]=Tt(this.$.cdnUrl,t);let e=js(this.$.cdnUrl),r=Qs(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=Tt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=O(this.$["*originalUrl"],M("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===L.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Pe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=_r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=D("image",{image_hidden_to_cropper:t===L.CROP,image_hidden_effects:t!==L.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=M(xt(t),"preview"),n=O(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(ot,"className","cloud-image-editor");ot.template=vr;ot.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ti=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=Y("mask",{id:"backdrop-mask"}),a=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=Y("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Ot(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Ot(n,f)}else{let f=wt(Math.min(d,p)/(24*2+34)/2,0,1),{d:b,center:$}=a?$s(i,e,f):Ss(i,e,f),x=Math.max(Di*wt(Math.min(d,p)/Di/3,0,1),As);Ot(n,{x:$[0]-x,y:$[1]-x,width:x*2,height:x*2}),Ot(r,{d:b})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",D("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ot(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=Y("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=Y("rect",{fill:"transparent"}),l=Y("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=Y("svg"),t=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=Y("line",{x1:`${ie*e}%`,y1:"0%",x2:`${ie*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=Y("line",{x1:"0%",y1:`${ie*e}%`,x2:"100%",y2:`${ie*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=ks({rect:o,delta:[e,r],imageBox:n}):o=Os({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return zt(Ht(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Ls(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Is(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",D("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",D({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ti.template='';var bt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=D({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};bt.template=` {{title}}`;function Uo(s){let i=s+90;return i=i>=360?0:i,i}function Ro(s,i){return s==="rotate"?Uo(i):["mirror","flip"].includes(s)?!i:null}var fe=class extends bt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Ro(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var me={FILTER:"filter",COLOR_OPERATION:"color_operation"},lt="original",ei=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?me.FILTER:me.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===lt?void 0:this.$.value,filter:this._filter===lt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=rt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===me.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===me.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===me.FILTER?this._filter===lt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ei.template=` `;function ge(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function be(s){let i=[];for(let n of s){let o=ge(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Gt=class extends bt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==lt?{name:this._filter,amount:o}:void 0,O(this._originalUrl,M(Fe,xt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ge(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===lt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Gt.template=` `;var _e=class extends bt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=rt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Cr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function wr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Kt(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,M(Fe,xt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Po(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ii=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=I(this._commit.bind(this),300),this._handleResizeThrottled=Cr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=wr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=jt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Ht(l)}_alignCrop(){var d;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[p,m],coords:[f,b]}=n,{width:$}=jt(this._imageSize,r),x=o/$;i=zt(Ht({x:l+f*x,y:a+b*x,width:p*x,height:m*x}),this.$["*imageBox"])}let c=(d=this.$["*cropPresetList"])==null?void 0:d[0],u=c?c.width/c.height:void 0;if(!Us(i,t)||u&&!Rs(i,u)){let p=t.width/t.height,m=t.width,f=t.height;u&&(p>u?m=Math.min(t.height*u,t.width):f=Math.min(t.width/u,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=zt(Ht(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=jt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=D({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=jt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[wt(Math.round(c/d),1,l),wt(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=jt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,b=this._getCropDimensions(),$={dimensions:b,coords:[wt(Math.round((d-l)/m),0,c-b[0]),wt(Math.round((p-a)/f),0,u-b[1])]};if(!Po($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(b[0]===c&&b[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=D({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Kt(i,e,t)),{promise:n,cancel:o,image:l}=ge(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ii.template=` `;function Gi(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Mo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Do(s,i){return s.map((t,e)=>tn-o)}var Ki=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=I(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Kt(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=rt[i],r=this._keypoints.map(l=>l.value),n=No(r,t,e),o=Do(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=be(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Tr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=be(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Tr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=D({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Fo=1,si=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Fo?this.scrollLeft+=e:this.scrollLeft+=t})}};si.template=" ";function Bo(s){return` `}function Vo(s){return` `}var ri=class extends U{constructor(){super();h(this,"_updateInfoTooltip",I(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===L.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(lt);else if(this.$["*tabId"]===L.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||rt[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":lt,"*currentOperation":null,showLoader:!1,filters:er,colorOperations:tr,cropOperations:ir,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=I(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===L.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new _e;return e.operation=t,e}_createFilterControl(t){let e=new Gt;return e.filter=t,e}_createToggleControl(t){let e=new fe;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===L.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===L.FILTERS?[lt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===L.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===L.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of W){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Kt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=be([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of W){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};ri.template=` {{*operationTooltip}} `;var ye=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return D("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};ye.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ye.template=` {{text}}`;var ni=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};ni.template=``;var oi={transition:"transition",visible:"visible",hidden:"hidden"},li=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=oi.visible,this._hiddenStyle=oi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",br(this,{[oi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(oi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};li.template=" ";var ai=class extends _{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d`;var Yi=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ot,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};var zo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},xr=function(s,i="i"){let t=s.split("*").map(zo);return new RegExp("^"+t.join(".+")+"$",i)};var jo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Er({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return jo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var At={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in At){let t=At[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ar=function(s,i,t){s in At||(At[s]=[]),At[s].push([i,t])},$r=function(s,i){s in At&&(At[s]=At[s].filter(t=>t[0]!==i))};function Sr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var ci=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=xr(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Er(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Sr(n),o.toString()}mountIframe(){let t=Jt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ar("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&$r("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};ci.template=` {{activityCaption}} `;var ve=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=Jt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ve.bindAttributes({"tab-list":null,default:null});ve.template=` `;var hi=class extends v{constructor(){super();h(this,"processInnerHtml",!0);h(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return Ir.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,vi(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var e,r;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(l=>l.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,a.value=l!=null?l:"",this._dynamicInputsContainer.appendChild(a)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let l=o.find(d=>!d.isValid),a=(r=l==null?void 0:l.validationErrorMessage)!=null?r:(e=l==null?void 0:l.uploadError)==null?void 0:e.message,c=this.$["*message"];c=c!=null&&c.isError?`${c.caption}. ${c.text}`:void 0;let u=a!=null?a:c;u?this._validationInputElement.setCustomValidity(u):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(l=>l.isUploaded&&l.isValid)){this.$.output={groupData:void 0,files:t};return}let r=this.getUploadClientOptions(),n=t.map(l=>l.uuid+(l.cdnUrlModifiers?`/${l.cdnUrlModifiers}`:"")),o=await Ts(n,r);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};hi.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var Ir=hi;var Zi=class extends g{};var ui=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};ui.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},kr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?kr.exitFullscreen():kr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};Q.template=` `;Q.bindAttributes({video:"video",src:"src"});var Ho="css-src";function di(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0);h(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ae({element:this,attribute:Ho,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Ce=class extends di(_){};var pi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(pi,"template",`Powered by Uploadcare`);var $t=class extends Ce{constructor(){super(...arguments);h(this,"requireCtxName",!0);h(this,"init$",Ue(this));h(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};var fi=class extends $t{};fi.template=` `;var mi=class extends $t{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};mi.template=` `;var gi=class extends $t{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==g.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};gi.template=` `;var Ji=class extends di(ot){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function Qi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var ts="LR";async function Wo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ts]){t(window[ts]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ts];i&&Qi(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,Zi as ActivityHeader,Dt as BaseComponent,_ as Block,Ke as CameraSource,Ji as CloudImageEditor,Yi as CloudImageEditorActivity,ot as CloudImageEditorBlock,xo as Config,Ze as ConfirmationDialog,pi as Copyright,ti as CropFrame,E as Data,Ir as DataOutput,ce as DropArea,fe as EditorCropButtonControl,Gt as EditorFilterControl,ii as EditorImageCropper,Ki as EditorImageFader,_e as EditorOperationControl,si as EditorScroller,ei as EditorSlider,ri as EditorToolbar,ci as ExternalSource,gt as FileItem,pe as FilePreview,gi as FileUploaderInline,mi as FileUploaderMinimal,fi as FileUploaderRegular,oe as Icon,Vi as Img,ni as LineLoaderUi,ye as LrBtnUi,Xe as MessageBox,de as Modal,Ns as PACKAGE_NAME,Ds as PACKAGE_VERSION,li as PresenceToggle,Qe as ProgressBar,Je as ProgressBarCommon,ui as Select,Ce as ShadowWrapper,ae as SimpleBtn,ai as SliderUi,he as SourceBtn,Hi as SourceList,He as StartFrom,ve as Tabs,Oo as UploadCtxProvider,Ye as UploadDetails,qe as UploadList,v as UploaderBlock,Ge as UrlSource,Q as Video,Wo as connectBlocksFrom,Qi as registerBlocks,di as shadowed,ut as toKebabCase};
\ No newline at end of file
+`,"\\n"),i=Yr(i),i=Nt+i+Nt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var is=0,Mt=null,ht=null,_t=class extends HTMLElement{constructor(){super(),yi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 _t}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Zt.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 s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=_t.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=_t.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=_t.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=_t.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=_t.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=_t.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])rs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Xr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ht==null||ht.delete(this.updateCssData),ht!=null&&ht.size||(Mt==null||Mt.disconnect(),Mt=null,ht=null)},100)))}static reg(s,i=!1){s||(is++,s=`${C.AUTO_TAG_PRFX}-${is}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" 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(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Zr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){ht||(ht=new Set),ht.add(this.updateCssData),Mt||(Mt=new MutationObserver(s=>{s[0].type==="attributes"&&ht.forEach(i=>{i()})}),Mt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},Dt=_t;yi(Dt,"template");var _i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(_i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),_i.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}};_i.appMap=Object.create(null);function vi(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function Jr(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function Jt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&Jr(i,s.attributes),s.styles&&vi(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Jt(t);i.appendChild(e)}),i}var ns="idb-store-ready",Qr="symbiote-db",tn="symbiote-idb-update_",en=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ns,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return tn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,os.clear(this.name)}},os=class{static get readyEventName(){return ns}static open(s=Qr,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new en(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};yi(os,"_reg",Object.create(null));var S=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),sn=Object.freeze({[S.UPLOAD_START]:"LR_UPLOAD_START",[S.REMOVE]:"LR_REMOVE",[S.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[S.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[S.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[S.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[S.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[S.DATA_OUTPUT]:"LR_DATA_OUTPUT",[S.DONE_FLOW]:"LR_DONE_FLOW",[S.INIT_FLOW]:"LR_INIT_FLOW"}),xe=class{constructor(i){h(this,"_timeoutStore",new Map);h(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));let e=sn[i];window.dispatchEvent(new CustomEvent(e,{detail:{ctx:this._getCtxName(),type:e,data:t}}))}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};function I(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var ls="--uploadcare-blocks-window-height",It=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(ls)}};h(It,"clientsRegistry",new Set),h(It,"flush",I(()=>{document.documentElement.style.setProperty(ls,`${window.innerHeight}px`)},100));var Ee=(s,i)=>new Intl.PluralRules(s).select(i);var rn=s=>s,Ci="{{",cs="}}",as="plural:";function Qt(s,i,t={}){var o;let{openToken:e=Ci,closeToken:r=cs,transform:n=rn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function hs(s){let i=[],t=s.indexOf(Ci);for(;t!==-1;){let e=s.indexOf(cs,t),r=s.substring(t+2,e);if(r.startsWith(as)){let n=s.substring(t+2,e).replace(as,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ci,e)}return i}var ut=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ae=({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=setTimeout(()=>{a.disconnect(),e()},r),o=c=>{let u=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&u!==null&&(clearTimeout(n),a.disconnect(),t(u))},l=s.getAttribute(i);l!==null&&(clearTimeout(n),t(l));let a=new MutationObserver(c=>{let u=c[c.length-1];o(u)});a.observe(s,{attributes:!0,attributeFilter:[i]})};var us=new Set;function te(s){us.has(s)||(us.add(s),console.warn(s))}function ds(s){return Object.prototype.toString.call(s)==="[object Object]"}var nn=/\W|_/g;function on(s){return s.split(nn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ps(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>ft(t,{ignoreKeys:i})):s}function ft(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ps(s,{ignoreKeys:i});if(!ds(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ds(r)?r=ft(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ps(r,{ignoreKeys:i})),t[on(e)]=r}return t}var ln=s=>new Promise(i=>setTimeout(i,s));function Si({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var an={factor:2,time:100};function cn(s,i=an){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>ln(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Ft=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Ft.prototype),this.originalProgressEvent=t}},Se=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},yt=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,yt.prototype)}},hn=500,ms=({check:s,interval:i=hn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Se(e,()=>{o&&clearTimeout(o),n(new yt("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new yt("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),A={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"},Ie="application/octet-stream",gs="original",vt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Se(r,()=>{u=!0,a.abort(),l(new yt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let x=$.split(": "),T=x.shift(),w=x.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,b=a.status;o({request:d,data:f,headers:m,status:b})}},a.onerror=d=>{u||l(new Ft(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function un(s,...i){return s}var dn=({name:s})=>s?[s]:[],pn=un,fn=()=>new FormData,bs=s=>!1,ke=s=>typeof Blob!="undefined"&&s instanceof Blob,Oe=s=>typeof File!="undefined"&&s instanceof File,Le=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Bt=s=>ke(s)||Oe(s)||bs()||Le(s),mn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",gn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),bn=s=>!!s&&typeof s=="object"&&"data"in s&&Bt(s.data);function _n(s,i,t){if(bn(t)){let{name:e,contentType:r}=t,n=pn(t.data,e,r!=null?r:Ie),o=dn({name:e,contentType:r});s.push([i,n,...o])}else if(gn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else mn(t)&&t&&s.push([i,t.toString()])}function yn(s){let i=[];for(let[t,e]of Object.entries(s))_n(i,t,e);return i}function Ii(s){let i=fn(),t=yn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},vn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},dt=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=vn(t)),e.toString()},Cn="6.8.0",wn="UploadcareUploadClient",Tn=Cn;function kt(s){return Si({libraryName:wn,libraryVersion:Tn,...s})}var xn="RequestThrottledError",fs=15e3,En=1e3;function An(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return fs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:fs}function Ct(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return cn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===xn&&r{let i="";return(ke(s)||Oe(s)||Le(s))&&(i=s.type),i||Ie},ys=s=>{let i="";return Oe(s)&&s.name?i=s.name:ke(s)||bs()?i="":Le(s)&&s.name&&(i=s.name),i||gs};function ki(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function $n(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=A.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({file:{data:s,name:t||ys(s),contentType:e||_s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ki(l),signature:n,expire:o,source:u,metadata:b}),signal:a,onProgress:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var xi;(function(s){s.Token="token",s.FileInfo="file_info"})(xi||(xi={}));function Sn(s,{publicKey:i,baseURL:t=A.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},url:dt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:ki(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:b}),signal:u}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var j;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(j||(j={}));var In=s=>"status"in s&&s.status===j.Error;function kn(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=A.retryNetworkErrorMaxTimes}={}){return Ct(()=>vt({method:"GET",headers:i?{"X-UC-User-Agent":kt({publicKey:i,integration:r,userAgent:n})}:void 0,url:dt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=ft(JSON.parse(a));if("error"in d&&!In(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function On(s,{publicKey:i,baseURL:t=A.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:a,userAgent:c})},url:dt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let b=ft(JSON.parse(p));if("error"in b)throw new P(b.error.content,b.error.errorCode,f,b,m);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function vs(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"GET",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},url:dt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Ln(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=A.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({filename:e||gs,size:s,content_type:t||Ie,part_size:r,UPLOADCARE_STORE:ki(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:b}),signal:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w.parts=Object.keys(w.parts).map(V=>w.parts[V]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Un(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Ie}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Rn(s,{publicKey:i,baseURL:t=A.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",url:dt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},data:Ii({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Oi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return ms({check:u=>vs(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function Pn(s){return"defaultEffects"in s}var pt=class{constructor(i,{baseCDN:t=A.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);h(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=dt(t,`${r}/`),l=n?dt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,Pn(i)&&(this.defaultEffects=i.defaultEffects)}},Mn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:b,metadata:$})=>$n(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:x})=>Oi(x,{publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(x=>new pt(x,{baseCDN:b})),Nn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>vs(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new pt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Dn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Se(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Fn=window.WebSocket,Ei=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Bn=(s,i)=>s==="success"?{status:j.Success,...i}:s==="progress"?{status:j.Progress,...i}:{status:j.Error,...i},Ai=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ei);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Fn(i),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 e=JSON.parse(t.data.toString());switch(e.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(e.channel,Bn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},wi=null,Li=s=>{if(!wi){let i=typeof window=="undefined"?0:3e4;wi=new Ai(s,i)}return wi},Vn=s=>{Li(s).connect()};function zn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ms({check:c=>kn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case j.Error:return new P(u.error,u.errorCode);case j.Waiting:return!1;case j.Unknown:return new P(`Token "${s}" was not found.`);case j.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case j.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var jn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Li(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Se(t,()=>{a(),n(new yt("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case j.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case j.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case j.Error:a(),n(new P(c.msg,c.error_code))}})}),Hn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,pusherKey:$=A.pusherKey,metadata:x})=>Promise.resolve(Vn($)).then(()=>Sn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,metadata:x})).catch(T=>{let w=Li($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===xi.FileInfo?T:Dn([({signal:w})=>zn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:w}),({signal:w})=>jn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof P)throw T;return T}).then(T=>Oi(T.uuid,{publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:u})).then(T=>new pt(T,{baseCDN:r})),Ti=new WeakMap,Wn=async s=>{if(Ti.has(s))return Ti.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Ti.set(s,i),i},Cs=async s=>{if(Oe(s)||ke(s))return s.size;if(Le(s))return(await Wn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Xn=(s,i=A.multipartMinFileSize)=>s>=i,ws=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Bt(s)&&t.test(s)},Ui=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Bt(s)&&t.test(s)},qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},Kn=async(s,i,t)=>e=>Gn(s,e,i,t),Yn=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Un(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Zn=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:b,multipartChunkSize:$=A.multipartChunkSize,maxConcurrentRequests:x=A.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let V=e!=null?e:await Cs(s),at,St=(R,z)=>{if(!c)return;at||(at=Array(R).fill(0));let J=tt=>tt.reduce((ct,bi)=>ct+bi,0);return tt=>{tt.isComputable&&(at[z]=tt.value,c({isComputable:!0,value:J(at)/R}))}};return b||(b=_s(s)),Ln(V,{publicKey:i,contentType:b,fileName:t||ys(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:z})=>{let J=await Kn(s,V,$);return Promise.all([R,qn(x,z.map((tt,ct)=>()=>Yn(J(ct),tt,{publicKey:i,contentType:b,onProgress:St(z.length,ct),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Rn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Oi(R.uuid,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new pt(R,{baseCDN:T}))};async function Ri(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:b,multipartChunkSize:$,maxConcurrentRequests:x,baseCDN:T=A.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,pusherKey:at,metadata:St}){if(Bt(s)){let R=await Cs(s);return Xn(R,b)?Zn(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:x,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St}):Mn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St})}if(Ui(s))return Hn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:at,metadata:St});if(ws(s))return Nn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var $i=class{constructor(i,{baseCDN:t=A.baseCDN}={}){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new pt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Jn=s=>{for(let i of s)if(!Bt(i))return!1;return!0},Qn=s=>{for(let i of s)if(!ws(i))return!1;return!0},to=s=>{for(let i of s)if(!Ui(i))return!1;return!0};function Ts(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b=A.multipartChunkSize,baseCDN:$=A.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!Jn(s)&&!to(s)&&!Qn(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let V,at=!0,St=s.length,R=(z,J)=>{if(!a)return;V||(V=Array(z).fill(0));let tt=ct=>ct.reduce((bi,Or)=>bi+Or)/z;return ct=>{if(!ct.isComputable||!at){at=!1,a({isComputable:!1});return}V[J]=ct.value,a({isComputable:!0,value:tt(V)})}};return Promise.all(s.map((z,J)=>Bt(z)||Ui(z)?Ri(z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(St,J),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b,baseCDN:$,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T}).then(tt=>tt.uuid):z)).then(z=>On(z,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(J=>new $i(J,{baseCDN:$})).then(J=>(a&&a({isComputable:!0,value:1}),J)))}var $e=class{constructor(i){h(this,"_concurrency",1);h(this,"_pending",[]);h(this,"_running",0);h(this,"_resolvers",new Map);h(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var Pi=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),Mi=s=>({...Pi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Ue=s=>({...Mi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $e(1),"*uploadCollection":null});function xs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var H=s=>`*cfg/${s}`;var Ni="lr-",_=class extends Dt{constructor(){super();h(this,"requireCtxName",!1);h(this,"allowCustomTemplate",!0);h(this,"init$",Pi());h(this,"updateCtxCssData",()=>{te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(xs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=hs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Qt(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Ee(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ni}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ae({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),It.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),It.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new xe(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Qt(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=H(r);return this.$[o]=n,!0},get:(e,r)=>{let n=H(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ut(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(H(t));r.ctx.has(r.name)?this.sub(H(t),e):(this.bindCssData(`--cfg-${ut(t)}`),this.sub(`--cfg-${ut(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ni)?t:Ni+t)}};h(_,"StateConsumerScope",null),h(_,"className","");var Es="active",ee="___ACTIVITY_IS_ACTIVE___",et=class extends _{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Mi(this));h(this,"_debouncedHistoryFlush",I(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=et._activityRegistry[this.activityKey];this[ee]=!1,this.removeAttribute(Es),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=et._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ee]=!0,this.setAttribute(Es,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ee]?this._deactivate():this.activityType===t&&!this[ee]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!et._activityRegistry[this.activityKey]}get isActivityActive(){return this[ee]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;et._activityRegistry||(et._activityRegistry=Object.create(null)),et._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),et._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(et._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===r);n=(e=l==null?void 0:l.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},g=et;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ie=33.333333333333336,y=1,Di=24,As=6;function Ot(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function Y(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Ot(t,i),t}function $s(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Ss(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Is(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function ks({rect:s,delta:[i,t],imageBox:e}){return zt({...s,x:s.x+i,y:s.y+t},e)}function zt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function eo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Rs(s,i){return Math.abs(s.width/s.height-i)<.1}function jt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ps(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Ht(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function wt(s,i,t){return Math.min(Math.max(s,i),t)}var Pe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var Z=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Ms=s=>s?s.split(",").map(i=>i.trim()):[],Lt=s=>s?s.join(","):"";var Ns="blocks",Ds="0.30.5";function Fs(s){return Si({...s,libraryName:Ns,libraryVersion:Ds})}var Bs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Me=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Bs(i)).join("/-/"),M=(...s)=>{let i=Me(...s);return i?`-/${i}/`:""};function Vs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function js(s){let i=Hs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Bs(n))}function Hs(s){let i=new URL(s),t=Vs(s),e=Ws(t)?Xs(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ws(s){return s.startsWith("http")}function Xs(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var O=(s,i,t)=>{let e=new URL(Hs(s));if(t=t||Vs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ws(t)){let r=Xs(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},Tt=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var se=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Fi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],Bi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),qs=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),re=s=>{let i=s==null?void 0:s.type;return i?Bi(i,se):!1};var st=1e3,Ut=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ne=s=>Math.ceil(s*100)/100,Gs=(s,i=Ut.AUTO)=>{let t=i===Ut.AUTO;if(i===Ut.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(co+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var De=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Zt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new Ne(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var Ys=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:pt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!1);h(this,"isCtxOwner",!1);h(this,"init$",Ue(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",I(this._runValidators.bind(this),100));h(this,"_flushOutputItems",I(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(S.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));h(this,"_handleCollectonUpdate",(t,e,r)=>{var n;this._runValidators();for(let o of r)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()});h(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,this.emit(S.UPLOAD_PROGRESS,l,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&this.emit(S.UPLOAD_FINISH,l,{debounce:!0})}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(S.UPLOAD_ERROR,e.readProp(o,"uploadError"))}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(S.VALIDATION_ERROR,e.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(S.CLOUD_MODIFICATION,e.readProp(o,"cdnUrlModifiers"))})})}setUploadMetadata(t){te("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof v?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new De({typedSchema:Ys,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:re(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:re(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Lt(Fi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?se:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Lt(se)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Z.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(S.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(S.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Fi([...e?se:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Bi(o,n),c=qs(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Gs(e)})}_validateMultipleLimit(t){let e=this.uploadCollection.items(),r=e.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&e.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Pe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ps(l,a,c),d=M(`crop/${u.width}x${u.height}/${u.x},${u.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:O(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,l;let e=E.getCtx(t).store,r=e.fileInfo||{name:e.fileName,originalFilename:e.fileName,size:e.fileSize,isImage:e.isImage,mimeType:e.mimeType};return{...r,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(l=(o=e.cdnUrl)!=null?o:r.cdnUrl)!=null?l:null,validationErrorMessage:e.validationErrorMsg,uploadError:e.uploadError,isUploaded:!!e.uuid&&!!e.fileInfo,isValid:!e.validationErrorMsg&&!e.uploadError,fullPath:e.fullPath,uploadProgress:e.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});var G={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function ho(s,i){if(typeof i=="number")return G[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&G[s]!==i?`${s}`:"";if(s==="filter"){if(!i||G[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Js=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function xt(s){return Me(...Js.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return ho(i,t)}).filter(i=>!!i))}var Fe=Me("format/auto","progressive/yes"),mt=([s])=>typeof s!="undefined"?Number(s):void 0,Zs=()=>!0,uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),po=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),fo={enhance:mt,brightness:mt,exposure:mt,gamma:mt,contrast:mt,saturation:mt,vibrance:mt,warmth:mt,filter:uo,mirror:Zs,flip:Zs,rotate:mt,crop:po};function Qs(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Js.includes(e))continue;let n=fo[e],o=n(r);i[e]=o}return i}var L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),W=[L.CROP,L.TUNING,L.FILTERS],tr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],er=["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"],ir=["rotate","mirror","flip"],rt=Object.freeze({brightness:{zero:G.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:G.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:G.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:G.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:G.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:G.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:G.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:G.enhance,range:[0,100],keypointsNumber:1},filter:{zero:G.filter,range:[0,100],keypointsNumber:1}});var mo="https://ucarecdn.com",go="https://upload.uploadcare.com",bo="https://social.uploadcare.com",Et={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Lt(W),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:mo,baseUrl:go,socialBaseUrl:bo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var X=s=>String(s),nt=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},k=s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},_o=s=>s==="auto"?s:k(s),yo={pubkey:X,multiple:k,multipleMin:nt,multipleMax:nt,confirmUpload:k,imgOnly:k,accept:X,externalSourcesPreferredTypes:X,store:_o,cameraMirror:k,sourceList:X,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:X,removeCopyright:k,cropPreset:X,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:X,cdnCname:X,baseUrl:X,socialBaseUrl:X,secureSignature:X,secureExpire:X,secureDeliveryProxy:X,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:X},sr=(s,i)=>{if(!(typeof i=="undefined"||i===null))try{return yo[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),Et[s]}};var Be=Object.keys(Et),vo=["metadata"],Co=s=>vo.includes(s),Ve=Be.filter(s=>!Co(s)),wo={...Object.fromEntries(Ve.map(s=>[ut(s),s])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),s]))},To={...Object.fromEntries(Be.map(s=>[ut(s),H(s)])),...Object.fromEntries(Be.map(s=>[s.toLowerCase(),H(s)]))},ze=class extends _{constructor(){super();h(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Et).map(([t,e])=>[H(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of Ve)this.sub(H(e),r=>{r!==Et[e]&&(t[e]=r)},!1);for(let e of Be){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,Ve.includes(e)){let o=[...new Set([ut(e),e.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[H(e)]!==n&&(typeof n=="undefined"||n===null?this.$[H(e)]=Et[e]:this.$[H(e)]=n)},get:()=>this.$[H(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=wo[t],o=sr(n,r),l=o!=null?o:Et[n],a=this;a[n]=l}};ze.bindAttributes(To);var xo=ze;var oe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};oe.template=``;oe.bindAttributes({name:"name",size:"size"});var Eo="https://ucarecdn.com",Rt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Eo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var rr=s=>[...new Set(s)];var le="--lr-img-",nr="unresolved",Wt=2,Xt=3,or=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ar=Object.create(null),lr;for(let s in Rt)ar[le+s]=((lr=Rt[s])==null?void 0:lr.default)||"";var je=class extends Dt{constructor(){super(...arguments);h(this,"cssInit$",ar)}$$(t){return this.$[le+t]}set$$(t){for(let e in t)this.$[le+e]=t[e]}sub$$(t,e){this.sub(le+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!or&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return M(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Rt.format.default}`,`quality/${this.$$("quality")||Rt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(or&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Qt(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(nr,""),this.img.onload=()=>{this.img.removeAttribute(nr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Rt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?rr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Wt+"x")}") ${n*Wt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Xt+"x")}") ${n*Xt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Wt))}") ${Wt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Xt))}") ${Xt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Wt+"x")+` ${e*Wt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Xt+"x")+` ${e*Xt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(Rt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[le+t]=r})}};var Vi=class extends je{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var ae=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=k(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};ae.template=` `;ae.bindAttributes({dropzone:null});var He=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};He.template=' ';function Ao(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function $o(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function cr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Ao(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var F={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},hr=["focus"],So=100,zi=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function ji(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=F.INACTIVE,o=f=>{s.shouldIgnore()&&f!==F.INACTIVE||(n!==f&&e.forEach(b=>b(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(F.INACTIVE)},c=()=>{i+=1,n===F.INACTIVE&&o(F.ACTIVE)},u=()=>{i-=1,l()||o(F.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(F.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let b=[f.x,f.y],$=s.element.getBoundingClientRect(),x=Math.floor(Io(b,$)),T=x{if(s.shouldIgnore())return;f.preventDefault();let b=await cr(f.dataTransfer);s.onItems(b),o(F.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),hr.forEach(f=>{window.addEventListener(f,a)}),()=>{zi.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),hr.forEach(f=>{window.removeEventListener(f,a)})}}var ur="lr-drop-area",qt=`${ur}/registry`,ce=class extends v{constructor(){super(),this.init$={...this.init$,state:F.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[qt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[qt]||(this.$[qt]=new Set),this.$[qt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=ji({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Z.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Z.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=ji({element:i,onChange:t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[qt]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[qt];i&&(i.delete(this),i.size===0&&E.deleteCtx(ur)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ce.template=` {{text}} `;ce.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var ko="src-type-",he=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${ko}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};he.template=` `;he.bindAttributes({type:null});var Hi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=` `}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function dr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function pr(s="#fff",i="rgba(0, 0, 0, .1)"){return dr(``)}function ue(s="hsl(209, 21%, 65%)",i=32,t=32){return dr(``)}function fr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),gt=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",I(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",I(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);this.emit(S.REMOVE,e,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(Tt(this.cfg.cdnCname,this._entry.getValue("uuid")),M(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await fr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{gt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),gt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),gt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));this.emit(S.UPLOAD_START,r,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=this.getUploadClientOptions();return Ri(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal,metadata:await this.getMetadataFor(t.uid)})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};gt.template=` {{itemName}}{{errorText}} `;gt.activeInstances=new Set;var de=class extends _{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogMouseDown",t=>{this._mouseDownTarget=t.target});h(this,"_handleDialogMouseUp",t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};h(de,"StateConsumerScope","modal");de.template=``;var We=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Xe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Xe.template=` {{msgTxt}}`;var qe=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",I(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));this.emit(S.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new We,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};qe.template=`{{headerText}} `;var Ge=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Z.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ge.template=` `;var Wi=()=>typeof navigator.permissions!="undefined";var Ke=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Wi(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{Wi()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",I(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Z.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ke.template=` `;var Xi=class extends v{constructor(){super(...arguments);h(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},Oo=Xi;var Ye=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ue(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=re(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=O(n,M("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};Ye.template=` `;var qi=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Ze=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new qi);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Ze.template=`{{activityCaption}} `;var Je=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};Je.template=` `;var Qe=class extends _{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};Qe.template='';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var pe=class extends _{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${pr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};pe.template=' ';pe.bindAttributes({checkerboard:"checkerboard"});var mr="--cfg-ctx-name",U=class extends _{get cfgCssCtxName(){return this.getCssData(mr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(mr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function gr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function D(...s){let i=gr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function br(s,...i){let t=gr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var _r=s=>{if(!s)return W;let i=Ms(s).filter(t=>W.includes(t));return i.length===0?W:i};function yr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":W,"*tabId":L.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Lt(W),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=M(xt(i),"preview"),r=O(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var vr=` Network error `;var ot=class extends U{constructor(){super();h(this,"_debouncedShowLoader",I(this._showLoader.bind(this),300));this.init$={...this.init$,...yr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$["*tabId"]===L.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=zs(this.$.cdnUrl);this.$["*originalUrl"]=Tt(this.$.cdnUrl,t);let e=js(this.$.cdnUrl),r=Qs(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=Tt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=O(this.$["*originalUrl"],M("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===L.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Pe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=_r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=D("image",{image_hidden_to_cropper:t===L.CROP,image_hidden_effects:t!==L.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=M(xt(t),"preview"),n=O(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(ot,"className","cloud-image-editor");ot.template=vr;ot.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ti=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=Y("mask",{id:"backdrop-mask"}),a=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=Y("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Ot(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Ot(n,f)}else{let f=wt(Math.min(d,p)/(24*2+34)/2,0,1),{d:b,center:$}=a?$s(i,e,f):Ss(i,e,f),x=Math.max(Di*wt(Math.min(d,p)/Di/3,0,1),As);Ot(n,{x:$[0]-x,y:$[1]-x,width:x*2,height:x*2}),Ot(r,{d:b})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",D("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ot(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=Y("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=Y("rect",{fill:"transparent"}),l=Y("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=Y("svg"),t=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=Y("line",{x1:`${ie*e}%`,y1:"0%",x2:`${ie*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=Y("line",{x1:"0%",y1:`${ie*e}%`,x2:"100%",y2:`${ie*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=ks({rect:o,delta:[e,r],imageBox:n}):o=Os({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return zt(Ht(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Ls(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Is(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",D("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",D({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ti.template='';var bt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=D({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};bt.template=` {{title}}`;function Uo(s){let i=s+90;return i=i>=360?0:i,i}function Ro(s,i){return s==="rotate"?Uo(i):["mirror","flip"].includes(s)?!i:null}var fe=class extends bt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Ro(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var me={FILTER:"filter",COLOR_OPERATION:"color_operation"},lt="original",ei=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?me.FILTER:me.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===lt?void 0:this.$.value,filter:this._filter===lt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=rt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===me.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===me.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===me.FILTER?this._filter===lt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ei.template=` `;function ge(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function be(s){let i=[];for(let n of s){let o=ge(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Gt=class extends bt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==lt?{name:this._filter,amount:o}:void 0,O(this._originalUrl,M(Fe,xt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ge(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===lt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Gt.template=` `;var _e=class extends bt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=rt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Cr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function wr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Kt(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,M(Fe,xt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Po(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ii=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=I(this._commit.bind(this),300),this._handleResizeThrottled=Cr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=wr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=jt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Ht(l)}_alignCrop(){var d;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[p,m],coords:[f,b]}=n,{width:$}=jt(this._imageSize,r),x=o/$;i=zt(Ht({x:l+f*x,y:a+b*x,width:p*x,height:m*x}),this.$["*imageBox"])}let c=(d=this.$["*cropPresetList"])==null?void 0:d[0],u=c?c.width/c.height:void 0;if(!Us(i,t)||u&&!Rs(i,u)){let p=t.width/t.height,m=t.width,f=t.height;u&&(p>u?m=Math.min(t.height*u,t.width):f=Math.min(t.width/u,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=zt(Ht(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=jt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=D({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=jt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[wt(Math.round(c/d),1,l),wt(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=jt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,b=this._getCropDimensions(),$={dimensions:b,coords:[wt(Math.round((d-l)/m),0,c-b[0]),wt(Math.round((p-a)/f),0,u-b[1])]};if(!Po($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(b[0]===c&&b[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=D({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Kt(i,e,t)),{promise:n,cancel:o,image:l}=ge(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ii.template=` `;function Gi(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Mo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Do(s,i){return s.map((t,e)=>tn-o)}var Ki=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=I(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Kt(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=rt[i],r=this._keypoints.map(l=>l.value),n=No(r,t,e),o=Do(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=be(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Tr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=be(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Tr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=D({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Fo=1,si=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Fo?this.scrollLeft+=e:this.scrollLeft+=t})}};si.template=" ";function Bo(s){return` `}function Vo(s){return` `}var ri=class extends U{constructor(){super();h(this,"_updateInfoTooltip",I(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===L.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(lt);else if(this.$["*tabId"]===L.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||rt[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":lt,"*currentOperation":null,showLoader:!1,filters:er,colorOperations:tr,cropOperations:ir,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=I(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===L.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new _e;return e.operation=t,e}_createFilterControl(t){let e=new Gt;return e.filter=t,e}_createToggleControl(t){let e=new fe;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===L.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===L.FILTERS?[lt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===L.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===L.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of W){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Kt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=be([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of W){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};ri.template=` {{*operationTooltip}} `;var ye=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return D("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};ye.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ye.template=` {{text}}`;var ni=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};ni.template=``;var oi={transition:"transition",visible:"visible",hidden:"hidden"},li=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=oi.visible,this._hiddenStyle=oi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",br(this,{[oi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(oi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};li.template=" ";var ai=class extends _{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d`;var Yi=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ot,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};var zo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},xr=function(s,i="i"){let t=s.split("*").map(zo);return new RegExp("^"+t.join(".+")+"$",i)};var jo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Er({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return jo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var At={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in At){let t=At[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ar=function(s,i,t){s in At||(At[s]=[]),At[s].push([i,t])},$r=function(s,i){s in At&&(At[s]=At[s].filter(t=>t[0]!==i))};function Sr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var ci=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=xr(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Er(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Sr(n),o.toString()}mountIframe(){let t=Jt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ar("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&$r("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};ci.template=` {{activityCaption}} `;var ve=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=Jt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ve.bindAttributes({"tab-list":null,default:null});ve.template=` `;var hi=class extends v{constructor(){super();h(this,"processInnerHtml",!0);h(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return Ir.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,vi(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var e,r;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(l=>l.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,a.value=l!=null?l:"",this._dynamicInputsContainer.appendChild(a)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let l=o.find(d=>!d.isValid),a=(r=l==null?void 0:l.validationErrorMessage)!=null?r:(e=l==null?void 0:l.uploadError)==null?void 0:e.message,c=this.$["*message"];c=c!=null&&c.isError?`${c.caption}. ${c.text}`:void 0;let u=a!=null?a:c;u?this._validationInputElement.setCustomValidity(u):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(l=>l.isUploaded&&l.isValid)){this.$.output={groupData:void 0,files:t};return}let r=this.getUploadClientOptions(),n=t.map(l=>l.uuid+(l.cdnUrlModifiers?`/${l.cdnUrlModifiers}`:"")),o=await Ts(n,r);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};hi.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var Ir=hi;var Zi=class extends g{};var ui=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};ui.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},kr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?kr.exitFullscreen():kr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};Q.template=` `;Q.bindAttributes({video:"video",src:"src"});var Ho="css-src";function di(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0);h(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ae({element:this,attribute:Ho,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Ce=class extends di(_){};var pi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(pi,"template",`Powered by Uploadcare`);var $t=class extends Ce{constructor(){super(...arguments);h(this,"requireCtxName",!0);h(this,"init$",Ue(this));h(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};var fi=class extends $t{};fi.template=` `;var mi=class extends $t{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};mi.template=` `;var gi=class extends $t{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==g.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};gi.template=` `;var Ji=class extends di(ot){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function Qi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var ts="LR";async function Wo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ts]){t(window[ts]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ts];i&&Qi(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,Zi as ActivityHeader,Dt as BaseComponent,_ as Block,Ke as CameraSource,Ji as CloudImageEditor,Yi as CloudImageEditorActivity,ot as CloudImageEditorBlock,xo as Config,Ze as ConfirmationDialog,pi as Copyright,ti as CropFrame,E as Data,Ir as DataOutput,ce as DropArea,fe as EditorCropButtonControl,Gt as EditorFilterControl,ii as EditorImageCropper,Ki as EditorImageFader,_e as EditorOperationControl,si as EditorScroller,ei as EditorSlider,ri as EditorToolbar,ci as ExternalSource,gt as FileItem,pe as FilePreview,gi as FileUploaderInline,mi as FileUploaderMinimal,fi as FileUploaderRegular,oe as Icon,Vi as Img,ni as LineLoaderUi,ye as LrBtnUi,Xe as MessageBox,de as Modal,Ns as PACKAGE_NAME,Ds as PACKAGE_VERSION,li as PresenceToggle,Qe as ProgressBar,Je as ProgressBarCommon,ui as Select,Ce as ShadowWrapper,ae as SimpleBtn,ai as SliderUi,he as SourceBtn,Hi as SourceList,He as StartFrom,ve as Tabs,Oo as UploadCtxProvider,Ye as UploadDetails,qe as UploadList,v as UploaderBlock,Ge as UrlSource,Q as Video,Wo as connectBlocksFrom,Qi as registerBlocks,di as shadowed,ut as toKebabCase};
\ No newline at end of file
diff --git a/web/lr-file-uploader-inline.min.js b/web/lr-file-uploader-inline.min.js
index d89b21f23..092fa7930 100644
--- a/web/lr-file-uploader-inline.min.js
+++ b/web/lr-file-uploader-inline.min.js
@@ -24,4 +24,4 @@
*
*/
var Lr=Object.defineProperty;var Ur=(s,i,t)=>i in s?Lr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Ur(s,typeof i!="symbol"?i+"":i,t),t);var Rr=Object.defineProperty,Pr=(s,i,t)=>i in s?Rr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,yi=(s,i,t)=>(Pr(s,typeof i!="symbol"?i+"":i,t),t);function Mr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Mr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.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"}),ss="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Nr=ss.length-1,Zt=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Fr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var es="__default__";function Br(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||es;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=es;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function Vr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function zr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Dr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):rs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var we="{{",Yt="}}",jr="skip-text";function Hr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(jr))&&r.textContent.includes(we)&&r.textContent.includes(Yt)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Wr=function(s,i){Hr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(Yt);)e.textContent.startsWith(we)?(n=e.textContent.indexOf(Yt)+Yt.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(we),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(we,"").replace(Yt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Xr=[Fr,Br,Vr,zr,Wr],Te="'",Nt='"',qr=/\\([0-9a-fA-F]{1,6} ?)/g;function Gr(s){return(s[0]===Nt||s[0]===Te)&&(s[s.length-1]===Nt||s[s.length-1]===Te)}function Kr(s){return(s[0]===Nt||s[0]===Te)&&(s=s.slice(1)),(s[s.length-1]===Nt||s[s.length-1]===Te)&&(s=s.slice(0,-1)),s}function Yr(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\
-`,"\\n"),i=Yr(i),i=Nt+i+Nt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var is=0,Mt=null,ht=null,_t=class extends HTMLElement{constructor(){super(),yi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 _t}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Zt.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 s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=_t.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=_t.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=_t.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=_t.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=_t.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=_t.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])rs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Xr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ht==null||ht.delete(this.updateCssData),ht!=null&&ht.size||(Mt==null||Mt.disconnect(),Mt=null,ht=null)},100)))}static reg(s,i=!1){s||(is++,s=`${C.AUTO_TAG_PRFX}-${is}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" 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(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Zr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){ht||(ht=new Set),ht.add(this.updateCssData),Mt||(Mt=new MutationObserver(s=>{s[0].type==="attributes"&&ht.forEach(i=>{i()})}),Mt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},Dt=_t;yi(Dt,"template");var _i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(_i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),_i.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}};_i.appMap=Object.create(null);function vi(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function Jr(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function Jt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&Jr(i,s.attributes),s.styles&&vi(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Jt(t);i.appendChild(e)}),i}var ns="idb-store-ready",Qr="symbiote-db",tn="symbiote-idb-update_",en=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ns,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return tn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,os.clear(this.name)}},os=class{static get readyEventName(){return ns}static open(s=Qr,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new en(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};yi(os,"_reg",Object.create(null));var S=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),sn=Object.freeze({[S.UPLOAD_START]:"LR_UPLOAD_START",[S.REMOVE]:"LR_REMOVE",[S.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[S.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[S.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[S.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[S.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[S.DATA_OUTPUT]:"LR_DATA_OUTPUT",[S.DONE_FLOW]:"LR_DONE_FLOW",[S.INIT_FLOW]:"LR_INIT_FLOW"}),xe=class{constructor(i){h(this,"_timeoutStore",new Map);h(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));let e=sn[i];window.dispatchEvent(new CustomEvent(e,{detail:{ctx:this._getCtxName(),type:e,data:t}}))}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};function I(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var ls="--uploadcare-blocks-window-height",It=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(ls)}};h(It,"clientsRegistry",new Set),h(It,"flush",I(()=>{document.documentElement.style.setProperty(ls,`${window.innerHeight}px`)},100));var Ee=(s,i)=>new Intl.PluralRules(s).select(i);var rn=s=>s,Ci="{{",cs="}}",as="plural:";function Qt(s,i,t={}){var o;let{openToken:e=Ci,closeToken:r=cs,transform:n=rn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function hs(s){let i=[],t=s.indexOf(Ci);for(;t!==-1;){let e=s.indexOf(cs,t),r=s.substring(t+2,e);if(r.startsWith(as)){let n=s.substring(t+2,e).replace(as,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ci,e)}return i}var ut=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ae=({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=setTimeout(()=>{a.disconnect(),e()},r),o=c=>{let u=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&u!==null&&(clearTimeout(n),a.disconnect(),t(u))},l=s.getAttribute(i);l!==null&&(clearTimeout(n),t(l));let a=new MutationObserver(c=>{let u=c[c.length-1];o(u)});a.observe(s,{attributes:!0,attributeFilter:[i]})};var us=new Set;function te(s){us.has(s)||(us.add(s),console.warn(s))}function ds(s){return Object.prototype.toString.call(s)==="[object Object]"}var nn=/\W|_/g;function on(s){return s.split(nn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ps(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>ft(t,{ignoreKeys:i})):s}function ft(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ps(s,{ignoreKeys:i});if(!ds(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ds(r)?r=ft(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ps(r,{ignoreKeys:i})),t[on(e)]=r}return t}var ln=s=>new Promise(i=>setTimeout(i,s));function Si({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var an={factor:2,time:100};function cn(s,i=an){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>ln(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Ft=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Ft.prototype),this.originalProgressEvent=t}},Se=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},yt=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,yt.prototype)}},hn=500,ms=({check:s,interval:i=hn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Se(e,()=>{o&&clearTimeout(o),n(new yt("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new yt("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),A={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"},Ie="application/octet-stream",gs="original",vt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Se(r,()=>{u=!0,a.abort(),l(new yt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let x=$.split(": "),T=x.shift(),w=x.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,b=a.status;o({request:d,data:f,headers:m,status:b})}},a.onerror=d=>{u||l(new Ft(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function un(s,...i){return s}var dn=({name:s})=>s?[s]:[],pn=un,fn=()=>new FormData,bs=s=>!1,ke=s=>typeof Blob!="undefined"&&s instanceof Blob,Oe=s=>typeof File!="undefined"&&s instanceof File,Le=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Bt=s=>ke(s)||Oe(s)||bs()||Le(s),mn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",gn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),bn=s=>!!s&&typeof s=="object"&&"data"in s&&Bt(s.data);function _n(s,i,t){if(bn(t)){let{name:e,contentType:r}=t,n=pn(t.data,e,r!=null?r:Ie),o=dn({name:e,contentType:r});s.push([i,n,...o])}else if(gn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else mn(t)&&t&&s.push([i,t.toString()])}function yn(s){let i=[];for(let[t,e]of Object.entries(s))_n(i,t,e);return i}function Ii(s){let i=fn(),t=yn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},vn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},dt=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=vn(t)),e.toString()},Cn="6.8.0",wn="UploadcareUploadClient",Tn=Cn;function kt(s){return Si({libraryName:wn,libraryVersion:Tn,...s})}var xn="RequestThrottledError",fs=15e3,En=1e3;function An(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return fs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:fs}function Ct(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return cn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===xn&&r{let i="";return(ke(s)||Oe(s)||Le(s))&&(i=s.type),i||Ie},ys=s=>{let i="";return Oe(s)&&s.name?i=s.name:ke(s)||bs()?i="":Le(s)&&s.name&&(i=s.name),i||gs};function ki(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function $n(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=A.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({file:{data:s,name:t||ys(s),contentType:e||_s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ki(l),signature:n,expire:o,source:u,metadata:b}),signal:a,onProgress:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var xi;(function(s){s.Token="token",s.FileInfo="file_info"})(xi||(xi={}));function Sn(s,{publicKey:i,baseURL:t=A.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},url:dt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:ki(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:b}),signal:u}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var j;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(j||(j={}));var In=s=>"status"in s&&s.status===j.Error;function kn(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=A.retryNetworkErrorMaxTimes}={}){return Ct(()=>vt({method:"GET",headers:i?{"X-UC-User-Agent":kt({publicKey:i,integration:r,userAgent:n})}:void 0,url:dt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=ft(JSON.parse(a));if("error"in d&&!In(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function On(s,{publicKey:i,baseURL:t=A.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:a,userAgent:c})},url:dt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let b=ft(JSON.parse(p));if("error"in b)throw new P(b.error.content,b.error.errorCode,f,b,m);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function vs(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"GET",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},url:dt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Ln(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=A.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({filename:e||gs,size:s,content_type:t||Ie,part_size:r,UPLOADCARE_STORE:ki(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:b}),signal:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w.parts=Object.keys(w.parts).map(V=>w.parts[V]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Un(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Ie}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Rn(s,{publicKey:i,baseURL:t=A.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",url:dt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},data:Ii({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Oi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return ms({check:u=>vs(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function Pn(s){return"defaultEffects"in s}var pt=class{constructor(i,{baseCDN:t=A.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);h(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=dt(t,`${r}/`),l=n?dt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,Pn(i)&&(this.defaultEffects=i.defaultEffects)}},Mn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:b,metadata:$})=>$n(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:x})=>Oi(x,{publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(x=>new pt(x,{baseCDN:b})),Nn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>vs(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new pt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Dn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Se(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Fn=window.WebSocket,Ei=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Bn=(s,i)=>s==="success"?{status:j.Success,...i}:s==="progress"?{status:j.Progress,...i}:{status:j.Error,...i},Ai=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ei);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Fn(i),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 e=JSON.parse(t.data.toString());switch(e.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(e.channel,Bn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},wi=null,Li=s=>{if(!wi){let i=typeof window=="undefined"?0:3e4;wi=new Ai(s,i)}return wi},Vn=s=>{Li(s).connect()};function zn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ms({check:c=>kn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case j.Error:return new P(u.error,u.errorCode);case j.Waiting:return!1;case j.Unknown:return new P(`Token "${s}" was not found.`);case j.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case j.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var jn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Li(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Se(t,()=>{a(),n(new yt("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case j.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case j.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case j.Error:a(),n(new P(c.msg,c.error_code))}})}),Hn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,pusherKey:$=A.pusherKey,metadata:x})=>Promise.resolve(Vn($)).then(()=>Sn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,metadata:x})).catch(T=>{let w=Li($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===xi.FileInfo?T:Dn([({signal:w})=>zn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:w}),({signal:w})=>jn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof P)throw T;return T}).then(T=>Oi(T.uuid,{publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:u})).then(T=>new pt(T,{baseCDN:r})),Ti=new WeakMap,Wn=async s=>{if(Ti.has(s))return Ti.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Ti.set(s,i),i},Cs=async s=>{if(Oe(s)||ke(s))return s.size;if(Le(s))return(await Wn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Xn=(s,i=A.multipartMinFileSize)=>s>=i,ws=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Bt(s)&&t.test(s)},Ui=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Bt(s)&&t.test(s)},qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},Kn=async(s,i,t)=>e=>Gn(s,e,i,t),Yn=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Un(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Zn=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:b,multipartChunkSize:$=A.multipartChunkSize,maxConcurrentRequests:x=A.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let V=e!=null?e:await Cs(s),at,St=(R,z)=>{if(!c)return;at||(at=Array(R).fill(0));let J=tt=>tt.reduce((ct,bi)=>ct+bi,0);return tt=>{tt.isComputable&&(at[z]=tt.value,c({isComputable:!0,value:J(at)/R}))}};return b||(b=_s(s)),Ln(V,{publicKey:i,contentType:b,fileName:t||ys(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:z})=>{let J=await Kn(s,V,$);return Promise.all([R,qn(x,z.map((tt,ct)=>()=>Yn(J(ct),tt,{publicKey:i,contentType:b,onProgress:St(z.length,ct),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Rn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Oi(R.uuid,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new pt(R,{baseCDN:T}))};async function Ri(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:b,multipartChunkSize:$,maxConcurrentRequests:x,baseCDN:T=A.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,pusherKey:at,metadata:St}){if(Bt(s)){let R=await Cs(s);return Xn(R,b)?Zn(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:x,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St}):Mn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St})}if(Ui(s))return Hn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:at,metadata:St});if(ws(s))return Nn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var $i=class{constructor(i,{baseCDN:t=A.baseCDN}={}){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new pt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Jn=s=>{for(let i of s)if(!Bt(i))return!1;return!0},Qn=s=>{for(let i of s)if(!ws(i))return!1;return!0},to=s=>{for(let i of s)if(!Ui(i))return!1;return!0};function Ts(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b=A.multipartChunkSize,baseCDN:$=A.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!Jn(s)&&!to(s)&&!Qn(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let V,at=!0,St=s.length,R=(z,J)=>{if(!a)return;V||(V=Array(z).fill(0));let tt=ct=>ct.reduce((bi,Or)=>bi+Or)/z;return ct=>{if(!ct.isComputable||!at){at=!1,a({isComputable:!1});return}V[J]=ct.value,a({isComputable:!0,value:tt(V)})}};return Promise.all(s.map((z,J)=>Bt(z)||Ui(z)?Ri(z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(St,J),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b,baseCDN:$,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T}).then(tt=>tt.uuid):z)).then(z=>On(z,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(J=>new $i(J,{baseCDN:$})).then(J=>(a&&a({isComputable:!0,value:1}),J)))}var $e=class{constructor(i){h(this,"_concurrency",1);h(this,"_pending",[]);h(this,"_running",0);h(this,"_resolvers",new Map);h(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var Pi=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),Mi=s=>({...Pi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Ue=s=>({...Mi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $e(1),"*uploadCollection":null});function xs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var H=s=>`*cfg/${s}`;var Ni="lr-",_=class extends Dt{constructor(){super();h(this,"requireCtxName",!1);h(this,"allowCustomTemplate",!0);h(this,"init$",Pi());h(this,"updateCtxCssData",()=>{te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(xs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=hs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Qt(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Ee(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ni}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ae({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),It.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),It.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new xe(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Qt(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=H(r);return this.$[o]=n,!0},get:(e,r)=>{let n=H(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ut(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(H(t));r.ctx.has(r.name)?this.sub(H(t),e):(this.bindCssData(`--cfg-${ut(t)}`),this.sub(`--cfg-${ut(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ni)?t:Ni+t)}};h(_,"StateConsumerScope",null),h(_,"className","");var Es="active",ee="___ACTIVITY_IS_ACTIVE___",et=class extends _{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Mi(this));h(this,"_debouncedHistoryFlush",I(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=et._activityRegistry[this.activityKey];this[ee]=!1,this.removeAttribute(Es),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=et._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ee]=!0,this.setAttribute(Es,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ee]?this._deactivate():this.activityType===t&&!this[ee]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!et._activityRegistry[this.activityKey]}get isActivityActive(){return this[ee]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;et._activityRegistry||(et._activityRegistry=Object.create(null)),et._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),et._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(et._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===r);n=(e=l==null?void 0:l.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},g=et;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ie=33.333333333333336,y=1,Di=24,As=6;function Ot(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function Y(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Ot(t,i),t}function $s(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Ss(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Is(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function ks({rect:s,delta:[i,t],imageBox:e}){return zt({...s,x:s.x+i,y:s.y+t},e)}function zt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function eo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Rs(s,i){return Math.abs(s.width/s.height-i)<.1}function jt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ps(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Ht(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function wt(s,i,t){return Math.min(Math.max(s,i),t)}var Pe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var Z=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Ms=s=>s?s.split(",").map(i=>i.trim()):[],Lt=s=>s?s.join(","):"";var Ns="blocks",Ds="0.30.4";function Fs(s){return Si({...s,libraryName:Ns,libraryVersion:Ds})}var Bs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Me=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Bs(i)).join("/-/"),M=(...s)=>{let i=Me(...s);return i?`-/${i}/`:""};function Vs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function js(s){let i=Hs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Bs(n))}function Hs(s){let i=new URL(s),t=Vs(s),e=Ws(t)?Xs(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ws(s){return s.startsWith("http")}function Xs(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var O=(s,i,t)=>{let e=new URL(Hs(s));if(t=t||Vs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ws(t)){let r=Xs(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},Tt=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var se=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Fi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],Bi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),qs=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),re=s=>{let i=s==null?void 0:s.type;return i?Bi(i,se):!1};var st=1e3,Ut=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ne=s=>Math.ceil(s*100)/100,Gs=(s,i=Ut.AUTO)=>{let t=i===Ut.AUTO;if(i===Ut.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(co+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var De=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Zt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new Ne(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var Ys=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:pt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!1);h(this,"isCtxOwner",!1);h(this,"init$",Ue(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",I(this._runValidators.bind(this),100));h(this,"_flushOutputItems",I(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(S.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));h(this,"_handleCollectonUpdate",(t,e,r)=>{var n;this._runValidators();for(let o of r)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()});h(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,this.emit(S.UPLOAD_PROGRESS,l,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&this.emit(S.UPLOAD_FINISH,l,{debounce:!0})}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(S.UPLOAD_ERROR,e.readProp(o,"uploadError"))}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(S.VALIDATION_ERROR,e.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(S.CLOUD_MODIFICATION,e.readProp(o,"cdnUrlModifiers"))})})}setUploadMetadata(t){te("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof v?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new De({typedSchema:Ys,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:re(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:re(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Lt(Fi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?se:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Lt(se)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Z.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(S.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(S.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Fi([...e?se:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Bi(o,n),c=qs(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Gs(e)})}_validateMultipleLimit(t){let e=this.uploadCollection.items(),r=e.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&e.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Pe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ps(l,a,c),d=M(`crop/${u.width}x${u.height}/${u.x},${u.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:O(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,l;let e=E.getCtx(t).store,r=e.fileInfo||{name:e.fileName,originalFilename:e.fileName,size:e.fileSize,isImage:e.isImage,mimeType:e.mimeType};return{...r,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(l=(o=e.cdnUrl)!=null?o:r.cdnUrl)!=null?l:null,validationErrorMessage:e.validationErrorMsg,uploadError:e.uploadError,isUploaded:!!e.uuid&&!!e.fileInfo,isValid:!e.validationErrorMsg&&!e.uploadError,fullPath:e.fullPath,uploadProgress:e.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});var G={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function ho(s,i){if(typeof i=="number")return G[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&G[s]!==i?`${s}`:"";if(s==="filter"){if(!i||G[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Js=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function xt(s){return Me(...Js.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return ho(i,t)}).filter(i=>!!i))}var Fe=Me("format/auto","progressive/yes"),mt=([s])=>typeof s!="undefined"?Number(s):void 0,Zs=()=>!0,uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),po=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),fo={enhance:mt,brightness:mt,exposure:mt,gamma:mt,contrast:mt,saturation:mt,vibrance:mt,warmth:mt,filter:uo,mirror:Zs,flip:Zs,rotate:mt,crop:po};function Qs(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Js.includes(e))continue;let n=fo[e],o=n(r);i[e]=o}return i}var L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),W=[L.CROP,L.TUNING,L.FILTERS],tr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],er=["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"],ir=["rotate","mirror","flip"],rt=Object.freeze({brightness:{zero:G.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:G.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:G.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:G.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:G.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:G.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:G.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:G.enhance,range:[0,100],keypointsNumber:1},filter:{zero:G.filter,range:[0,100],keypointsNumber:1}});var mo="https://ucarecdn.com",go="https://upload.uploadcare.com",bo="https://social.uploadcare.com",Et={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Lt(W),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:mo,baseUrl:go,socialBaseUrl:bo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var X=s=>String(s),nt=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},k=s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},_o=s=>s==="auto"?s:k(s),yo={pubkey:X,multiple:k,multipleMin:nt,multipleMax:nt,confirmUpload:k,imgOnly:k,accept:X,externalSourcesPreferredTypes:X,store:_o,cameraMirror:k,sourceList:X,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:X,removeCopyright:k,cropPreset:X,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:X,cdnCname:X,baseUrl:X,socialBaseUrl:X,secureSignature:X,secureExpire:X,secureDeliveryProxy:X,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:X},sr=(s,i)=>{if(!(typeof i=="undefined"||i===null))try{return yo[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),Et[s]}};var Be=Object.keys(Et),vo=["metadata"],Co=s=>vo.includes(s),Ve=Be.filter(s=>!Co(s)),wo={...Object.fromEntries(Ve.map(s=>[ut(s),s])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),s]))},To={...Object.fromEntries(Be.map(s=>[ut(s),H(s)])),...Object.fromEntries(Be.map(s=>[s.toLowerCase(),H(s)]))},ze=class extends _{constructor(){super();h(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Et).map(([t,e])=>[H(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of Ve)this.sub(H(e),r=>{r!==Et[e]&&(t[e]=r)},!1);for(let e of Be){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,Ve.includes(e)){let o=[...new Set([ut(e),e.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[H(e)]!==n&&(typeof n=="undefined"||n===null?this.$[H(e)]=Et[e]:this.$[H(e)]=n)},get:()=>this.$[H(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=wo[t],o=sr(n,r),l=o!=null?o:Et[n],a=this;a[n]=l}};ze.bindAttributes(To);var xo=ze;var oe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};oe.template=``;oe.bindAttributes({name:"name",size:"size"});var Eo="https://ucarecdn.com",Rt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Eo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var rr=s=>[...new Set(s)];var le="--lr-img-",nr="unresolved",Wt=2,Xt=3,or=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ar=Object.create(null),lr;for(let s in Rt)ar[le+s]=((lr=Rt[s])==null?void 0:lr.default)||"";var je=class extends Dt{constructor(){super(...arguments);h(this,"cssInit$",ar)}$$(t){return this.$[le+t]}set$$(t){for(let e in t)this.$[le+e]=t[e]}sub$$(t,e){this.sub(le+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!or&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return M(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Rt.format.default}`,`quality/${this.$$("quality")||Rt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(or&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Qt(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(nr,""),this.img.onload=()=>{this.img.removeAttribute(nr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Rt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?rr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Wt+"x")}") ${n*Wt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Xt+"x")}") ${n*Xt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Wt))}") ${Wt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Xt))}") ${Xt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Wt+"x")+` ${e*Wt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Xt+"x")+` ${e*Xt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(Rt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[le+t]=r})}};var Vi=class extends je{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var ae=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=k(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};ae.template=` `;ae.bindAttributes({dropzone:null});var He=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};He.template=' ';function Ao(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function $o(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function cr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Ao(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var F={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},hr=["focus"],So=100,zi=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function ji(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=F.INACTIVE,o=f=>{s.shouldIgnore()&&f!==F.INACTIVE||(n!==f&&e.forEach(b=>b(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(F.INACTIVE)},c=()=>{i+=1,n===F.INACTIVE&&o(F.ACTIVE)},u=()=>{i-=1,l()||o(F.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(F.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let b=[f.x,f.y],$=s.element.getBoundingClientRect(),x=Math.floor(Io(b,$)),T=x{if(s.shouldIgnore())return;f.preventDefault();let b=await cr(f.dataTransfer);s.onItems(b),o(F.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),hr.forEach(f=>{window.addEventListener(f,a)}),()=>{zi.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),hr.forEach(f=>{window.removeEventListener(f,a)})}}var ur="lr-drop-area",qt=`${ur}/registry`,ce=class extends v{constructor(){super(),this.init$={...this.init$,state:F.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[qt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[qt]||(this.$[qt]=new Set),this.$[qt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=ji({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Z.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Z.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=ji({element:i,onChange:t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[qt]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[qt];i&&(i.delete(this),i.size===0&&E.deleteCtx(ur)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ce.template=` {{text}} `;ce.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var ko="src-type-",he=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${ko}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};he.template=` `;he.bindAttributes({type:null});var Hi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=` `}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function dr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function pr(s="#fff",i="rgba(0, 0, 0, .1)"){return dr(``)}function ue(s="hsl(209, 21%, 65%)",i=32,t=32){return dr(``)}function fr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),gt=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",I(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",I(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);this.emit(S.REMOVE,e,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(Tt(this.cfg.cdnCname,this._entry.getValue("uuid")),M(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await fr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{gt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),gt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),gt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));this.emit(S.UPLOAD_START,r,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=this.getUploadClientOptions();return Ri(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal,metadata:await this.getMetadataFor(t.uid)})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};gt.template=` {{itemName}}{{errorText}} `;gt.activeInstances=new Set;var de=class extends _{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogMouseDown",t=>{this._mouseDownTarget=t.target});h(this,"_handleDialogMouseUp",t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};h(de,"StateConsumerScope","modal");de.template=``;var We=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Xe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Xe.template=` {{msgTxt}}`;var qe=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",I(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));this.emit(S.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new We,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};qe.template=`{{headerText}} `;var Ge=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Z.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ge.template=` `;var Wi=()=>typeof navigator.permissions!="undefined";var Ke=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Wi(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{Wi()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",I(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Z.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ke.template=` `;var Xi=class extends v{constructor(){super(...arguments);h(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},Oo=Xi;var Ye=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ue(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=re(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=O(n,M("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};Ye.template=` `;var qi=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Ze=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new qi);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Ze.template=`{{activityCaption}} `;var Je=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};Je.template=` `;var Qe=class extends _{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};Qe.template='';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var pe=class extends _{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${pr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};pe.template=' ';pe.bindAttributes({checkerboard:"checkerboard"});var mr="--cfg-ctx-name",U=class extends _{get cfgCssCtxName(){return this.getCssData(mr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(mr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function gr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function D(...s){let i=gr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function br(s,...i){let t=gr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var _r=s=>{if(!s)return W;let i=Ms(s).filter(t=>W.includes(t));return i.length===0?W:i};function yr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":W,"*tabId":L.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Lt(W),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=M(xt(i),"preview"),r=O(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var vr=` Network error `;var ot=class extends U{constructor(){super();h(this,"_debouncedShowLoader",I(this._showLoader.bind(this),300));this.init$={...this.init$,...yr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$["*tabId"]===L.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=zs(this.$.cdnUrl);this.$["*originalUrl"]=Tt(this.$.cdnUrl,t);let e=js(this.$.cdnUrl),r=Qs(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=Tt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=O(this.$["*originalUrl"],M("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===L.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Pe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=_r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=D("image",{image_hidden_to_cropper:t===L.CROP,image_hidden_effects:t!==L.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=M(xt(t),"preview"),n=O(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(ot,"className","cloud-image-editor");ot.template=vr;ot.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ti=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=Y("mask",{id:"backdrop-mask"}),a=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=Y("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Ot(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Ot(n,f)}else{let f=wt(Math.min(d,p)/(24*2+34)/2,0,1),{d:b,center:$}=a?$s(i,e,f):Ss(i,e,f),x=Math.max(Di*wt(Math.min(d,p)/Di/3,0,1),As);Ot(n,{x:$[0]-x,y:$[1]-x,width:x*2,height:x*2}),Ot(r,{d:b})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",D("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ot(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=Y("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=Y("rect",{fill:"transparent"}),l=Y("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=Y("svg"),t=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=Y("line",{x1:`${ie*e}%`,y1:"0%",x2:`${ie*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=Y("line",{x1:"0%",y1:`${ie*e}%`,x2:"100%",y2:`${ie*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=ks({rect:o,delta:[e,r],imageBox:n}):o=Os({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return zt(Ht(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Ls(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Is(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",D("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",D({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ti.template='';var bt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=D({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};bt.template=` {{title}}`;function Uo(s){let i=s+90;return i=i>=360?0:i,i}function Ro(s,i){return s==="rotate"?Uo(i):["mirror","flip"].includes(s)?!i:null}var fe=class extends bt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Ro(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var me={FILTER:"filter",COLOR_OPERATION:"color_operation"},lt="original",ei=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?me.FILTER:me.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===lt?void 0:this.$.value,filter:this._filter===lt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=rt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===me.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===me.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===me.FILTER?this._filter===lt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ei.template=` `;function ge(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function be(s){let i=[];for(let n of s){let o=ge(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Gt=class extends bt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==lt?{name:this._filter,amount:o}:void 0,O(this._originalUrl,M(Fe,xt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ge(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===lt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Gt.template=` `;var _e=class extends bt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=rt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Cr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function wr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Kt(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,M(Fe,xt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Po(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ii=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=I(this._commit.bind(this),300),this._handleResizeThrottled=Cr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=wr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=jt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Ht(l)}_alignCrop(){var d;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[p,m],coords:[f,b]}=n,{width:$}=jt(this._imageSize,r),x=o/$;i=zt(Ht({x:l+f*x,y:a+b*x,width:p*x,height:m*x}),this.$["*imageBox"])}let c=(d=this.$["*cropPresetList"])==null?void 0:d[0],u=c?c.width/c.height:void 0;if(!Us(i,t)||u&&!Rs(i,u)){let p=t.width/t.height,m=t.width,f=t.height;u&&(p>u?m=Math.min(t.height*u,t.width):f=Math.min(t.width/u,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=zt(Ht(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=jt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=D({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=jt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[wt(Math.round(c/d),1,l),wt(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=jt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,b=this._getCropDimensions(),$={dimensions:b,coords:[wt(Math.round((d-l)/m),0,c-b[0]),wt(Math.round((p-a)/f),0,u-b[1])]};if(!Po($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(b[0]===c&&b[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=D({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Kt(i,e,t)),{promise:n,cancel:o,image:l}=ge(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ii.template=` `;function Gi(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Mo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Do(s,i){return s.map((t,e)=>tn-o)}var Ki=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=I(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Kt(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=rt[i],r=this._keypoints.map(l=>l.value),n=No(r,t,e),o=Do(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=be(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Tr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=be(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Tr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=D({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Fo=1,si=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Fo?this.scrollLeft+=e:this.scrollLeft+=t})}};si.template=" ";function Bo(s){return` `}function Vo(s){return` `}var ri=class extends U{constructor(){super();h(this,"_updateInfoTooltip",I(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===L.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(lt);else if(this.$["*tabId"]===L.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||rt[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":lt,"*currentOperation":null,showLoader:!1,filters:er,colorOperations:tr,cropOperations:ir,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=I(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===L.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new _e;return e.operation=t,e}_createFilterControl(t){let e=new Gt;return e.filter=t,e}_createToggleControl(t){let e=new fe;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===L.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===L.FILTERS?[lt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===L.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===L.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of W){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Kt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=be([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of W){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};ri.template=` {{*operationTooltip}} `;var ye=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return D("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};ye.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ye.template=` {{text}}`;var ni=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};ni.template=``;var oi={transition:"transition",visible:"visible",hidden:"hidden"},li=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=oi.visible,this._hiddenStyle=oi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",br(this,{[oi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(oi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};li.template=" ";var ai=class extends _{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d`;var Yi=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ot,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};var zo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},xr=function(s,i="i"){let t=s.split("*").map(zo);return new RegExp("^"+t.join(".+")+"$",i)};var jo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Er({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return jo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var At={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in At){let t=At[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ar=function(s,i,t){s in At||(At[s]=[]),At[s].push([i,t])},$r=function(s,i){s in At&&(At[s]=At[s].filter(t=>t[0]!==i))};function Sr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var ci=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=xr(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Er(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Sr(n),o.toString()}mountIframe(){let t=Jt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ar("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&$r("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};ci.template=` {{activityCaption}} `;var ve=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=Jt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ve.bindAttributes({"tab-list":null,default:null});ve.template=` `;var hi=class extends v{constructor(){super();h(this,"processInnerHtml",!0);h(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return Ir.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,vi(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var e,r;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(l=>l.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,a.value=l!=null?l:"",this._dynamicInputsContainer.appendChild(a)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let l=o.find(d=>!d.isValid),a=(r=l==null?void 0:l.validationErrorMessage)!=null?r:(e=l==null?void 0:l.uploadError)==null?void 0:e.message,c=this.$["*message"];c=c!=null&&c.isError?`${c.caption}. ${c.text}`:void 0;let u=a!=null?a:c;u?this._validationInputElement.setCustomValidity(u):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(l=>l.isUploaded&&l.isValid)){this.$.output={groupData:void 0,files:t};return}let r=this.getUploadClientOptions(),n=t.map(l=>l.uuid+(l.cdnUrlModifiers?`/${l.cdnUrlModifiers}`:"")),o=await Ts(n,r);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};hi.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var Ir=hi;var Zi=class extends g{};var ui=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};ui.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},kr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?kr.exitFullscreen():kr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};Q.template=` `;Q.bindAttributes({video:"video",src:"src"});var Ho="css-src";function di(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0);h(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ae({element:this,attribute:Ho,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Ce=class extends di(_){};var pi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(pi,"template",`Powered by Uploadcare`);var $t=class extends Ce{constructor(){super(...arguments);h(this,"requireCtxName",!0);h(this,"init$",Ue(this));h(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};var fi=class extends $t{};fi.template=` `;var mi=class extends $t{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};mi.template=` `;var gi=class extends $t{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==g.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};gi.template=` `;var Ji=class extends di(ot){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function Qi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var ts="LR";async function Wo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ts]){t(window[ts]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ts];i&&Qi(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,Zi as ActivityHeader,Dt as BaseComponent,_ as Block,Ke as CameraSource,Ji as CloudImageEditor,Yi as CloudImageEditorActivity,ot as CloudImageEditorBlock,xo as Config,Ze as ConfirmationDialog,pi as Copyright,ti as CropFrame,E as Data,Ir as DataOutput,ce as DropArea,fe as EditorCropButtonControl,Gt as EditorFilterControl,ii as EditorImageCropper,Ki as EditorImageFader,_e as EditorOperationControl,si as EditorScroller,ei as EditorSlider,ri as EditorToolbar,ci as ExternalSource,gt as FileItem,pe as FilePreview,gi as FileUploaderInline,mi as FileUploaderMinimal,fi as FileUploaderRegular,oe as Icon,Vi as Img,ni as LineLoaderUi,ye as LrBtnUi,Xe as MessageBox,de as Modal,Ns as PACKAGE_NAME,Ds as PACKAGE_VERSION,li as PresenceToggle,Qe as ProgressBar,Je as ProgressBarCommon,ui as Select,Ce as ShadowWrapper,ae as SimpleBtn,ai as SliderUi,he as SourceBtn,Hi as SourceList,He as StartFrom,ve as Tabs,Oo as UploadCtxProvider,Ye as UploadDetails,qe as UploadList,v as UploaderBlock,Ge as UrlSource,Q as Video,Wo as connectBlocksFrom,Qi as registerBlocks,di as shadowed,ut as toKebabCase};
\ No newline at end of file
+`,"\\n"),i=Yr(i),i=Nt+i+Nt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var is=0,Mt=null,ht=null,_t=class extends HTMLElement{constructor(){super(),yi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 _t}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Zt.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 s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=_t.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=_t.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=_t.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=_t.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=_t.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=_t.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])rs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Xr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ht==null||ht.delete(this.updateCssData),ht!=null&&ht.size||(Mt==null||Mt.disconnect(),Mt=null,ht=null)},100)))}static reg(s,i=!1){s||(is++,s=`${C.AUTO_TAG_PRFX}-${is}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" 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(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Zr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){ht||(ht=new Set),ht.add(this.updateCssData),Mt||(Mt=new MutationObserver(s=>{s[0].type==="attributes"&&ht.forEach(i=>{i()})}),Mt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},Dt=_t;yi(Dt,"template");var _i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(_i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),_i.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}};_i.appMap=Object.create(null);function vi(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function Jr(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function Jt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&Jr(i,s.attributes),s.styles&&vi(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Jt(t);i.appendChild(e)}),i}var ns="idb-store-ready",Qr="symbiote-db",tn="symbiote-idb-update_",en=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ns,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return tn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,os.clear(this.name)}},os=class{static get readyEventName(){return ns}static open(s=Qr,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new en(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};yi(os,"_reg",Object.create(null));var S=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),sn=Object.freeze({[S.UPLOAD_START]:"LR_UPLOAD_START",[S.REMOVE]:"LR_REMOVE",[S.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[S.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[S.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[S.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[S.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[S.DATA_OUTPUT]:"LR_DATA_OUTPUT",[S.DONE_FLOW]:"LR_DONE_FLOW",[S.INIT_FLOW]:"LR_INIT_FLOW"}),xe=class{constructor(i){h(this,"_timeoutStore",new Map);h(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));let e=sn[i];window.dispatchEvent(new CustomEvent(e,{detail:{ctx:this._getCtxName(),type:e,data:t}}))}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};function I(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var ls="--uploadcare-blocks-window-height",It=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(ls)}};h(It,"clientsRegistry",new Set),h(It,"flush",I(()=>{document.documentElement.style.setProperty(ls,`${window.innerHeight}px`)},100));var Ee=(s,i)=>new Intl.PluralRules(s).select(i);var rn=s=>s,Ci="{{",cs="}}",as="plural:";function Qt(s,i,t={}){var o;let{openToken:e=Ci,closeToken:r=cs,transform:n=rn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function hs(s){let i=[],t=s.indexOf(Ci);for(;t!==-1;){let e=s.indexOf(cs,t),r=s.substring(t+2,e);if(r.startsWith(as)){let n=s.substring(t+2,e).replace(as,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ci,e)}return i}var ut=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ae=({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=setTimeout(()=>{a.disconnect(),e()},r),o=c=>{let u=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&u!==null&&(clearTimeout(n),a.disconnect(),t(u))},l=s.getAttribute(i);l!==null&&(clearTimeout(n),t(l));let a=new MutationObserver(c=>{let u=c[c.length-1];o(u)});a.observe(s,{attributes:!0,attributeFilter:[i]})};var us=new Set;function te(s){us.has(s)||(us.add(s),console.warn(s))}function ds(s){return Object.prototype.toString.call(s)==="[object Object]"}var nn=/\W|_/g;function on(s){return s.split(nn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ps(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>ft(t,{ignoreKeys:i})):s}function ft(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ps(s,{ignoreKeys:i});if(!ds(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ds(r)?r=ft(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ps(r,{ignoreKeys:i})),t[on(e)]=r}return t}var ln=s=>new Promise(i=>setTimeout(i,s));function Si({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var an={factor:2,time:100};function cn(s,i=an){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>ln(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Ft=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Ft.prototype),this.originalProgressEvent=t}},Se=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},yt=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,yt.prototype)}},hn=500,ms=({check:s,interval:i=hn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Se(e,()=>{o&&clearTimeout(o),n(new yt("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new yt("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),A={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"},Ie="application/octet-stream",gs="original",vt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Se(r,()=>{u=!0,a.abort(),l(new yt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let x=$.split(": "),T=x.shift(),w=x.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,b=a.status;o({request:d,data:f,headers:m,status:b})}},a.onerror=d=>{u||l(new Ft(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function un(s,...i){return s}var dn=({name:s})=>s?[s]:[],pn=un,fn=()=>new FormData,bs=s=>!1,ke=s=>typeof Blob!="undefined"&&s instanceof Blob,Oe=s=>typeof File!="undefined"&&s instanceof File,Le=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Bt=s=>ke(s)||Oe(s)||bs()||Le(s),mn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",gn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),bn=s=>!!s&&typeof s=="object"&&"data"in s&&Bt(s.data);function _n(s,i,t){if(bn(t)){let{name:e,contentType:r}=t,n=pn(t.data,e,r!=null?r:Ie),o=dn({name:e,contentType:r});s.push([i,n,...o])}else if(gn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else mn(t)&&t&&s.push([i,t.toString()])}function yn(s){let i=[];for(let[t,e]of Object.entries(s))_n(i,t,e);return i}function Ii(s){let i=fn(),t=yn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},vn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},dt=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=vn(t)),e.toString()},Cn="6.8.0",wn="UploadcareUploadClient",Tn=Cn;function kt(s){return Si({libraryName:wn,libraryVersion:Tn,...s})}var xn="RequestThrottledError",fs=15e3,En=1e3;function An(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return fs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:fs}function Ct(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return cn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===xn&&r{let i="";return(ke(s)||Oe(s)||Le(s))&&(i=s.type),i||Ie},ys=s=>{let i="";return Oe(s)&&s.name?i=s.name:ke(s)||bs()?i="":Le(s)&&s.name&&(i=s.name),i||gs};function ki(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function $n(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=A.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({file:{data:s,name:t||ys(s),contentType:e||_s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ki(l),signature:n,expire:o,source:u,metadata:b}),signal:a,onProgress:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var xi;(function(s){s.Token="token",s.FileInfo="file_info"})(xi||(xi={}));function Sn(s,{publicKey:i,baseURL:t=A.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},url:dt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:ki(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:b}),signal:u}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var j;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(j||(j={}));var In=s=>"status"in s&&s.status===j.Error;function kn(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=A.retryNetworkErrorMaxTimes}={}){return Ct(()=>vt({method:"GET",headers:i?{"X-UC-User-Agent":kt({publicKey:i,integration:r,userAgent:n})}:void 0,url:dt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=ft(JSON.parse(a));if("error"in d&&!In(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function On(s,{publicKey:i,baseURL:t=A.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:a,userAgent:c})},url:dt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let b=ft(JSON.parse(p));if("error"in b)throw new P(b.error.content,b.error.errorCode,f,b,m);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function vs(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"GET",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},url:dt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Ln(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=A.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({filename:e||gs,size:s,content_type:t||Ie,part_size:r,UPLOADCARE_STORE:ki(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:b}),signal:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w.parts=Object.keys(w.parts).map(V=>w.parts[V]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Un(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Ie}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Rn(s,{publicKey:i,baseURL:t=A.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",url:dt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},data:Ii({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Oi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return ms({check:u=>vs(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function Pn(s){return"defaultEffects"in s}var pt=class{constructor(i,{baseCDN:t=A.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);h(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=dt(t,`${r}/`),l=n?dt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,Pn(i)&&(this.defaultEffects=i.defaultEffects)}},Mn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:b,metadata:$})=>$n(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:x})=>Oi(x,{publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(x=>new pt(x,{baseCDN:b})),Nn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>vs(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new pt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Dn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Se(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Fn=window.WebSocket,Ei=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Bn=(s,i)=>s==="success"?{status:j.Success,...i}:s==="progress"?{status:j.Progress,...i}:{status:j.Error,...i},Ai=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ei);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Fn(i),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 e=JSON.parse(t.data.toString());switch(e.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(e.channel,Bn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},wi=null,Li=s=>{if(!wi){let i=typeof window=="undefined"?0:3e4;wi=new Ai(s,i)}return wi},Vn=s=>{Li(s).connect()};function zn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ms({check:c=>kn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case j.Error:return new P(u.error,u.errorCode);case j.Waiting:return!1;case j.Unknown:return new P(`Token "${s}" was not found.`);case j.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case j.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var jn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Li(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Se(t,()=>{a(),n(new yt("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case j.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case j.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case j.Error:a(),n(new P(c.msg,c.error_code))}})}),Hn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,pusherKey:$=A.pusherKey,metadata:x})=>Promise.resolve(Vn($)).then(()=>Sn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,metadata:x})).catch(T=>{let w=Li($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===xi.FileInfo?T:Dn([({signal:w})=>zn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:w}),({signal:w})=>jn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof P)throw T;return T}).then(T=>Oi(T.uuid,{publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:u})).then(T=>new pt(T,{baseCDN:r})),Ti=new WeakMap,Wn=async s=>{if(Ti.has(s))return Ti.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Ti.set(s,i),i},Cs=async s=>{if(Oe(s)||ke(s))return s.size;if(Le(s))return(await Wn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Xn=(s,i=A.multipartMinFileSize)=>s>=i,ws=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Bt(s)&&t.test(s)},Ui=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Bt(s)&&t.test(s)},qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},Kn=async(s,i,t)=>e=>Gn(s,e,i,t),Yn=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Un(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Zn=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:b,multipartChunkSize:$=A.multipartChunkSize,maxConcurrentRequests:x=A.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let V=e!=null?e:await Cs(s),at,St=(R,z)=>{if(!c)return;at||(at=Array(R).fill(0));let J=tt=>tt.reduce((ct,bi)=>ct+bi,0);return tt=>{tt.isComputable&&(at[z]=tt.value,c({isComputable:!0,value:J(at)/R}))}};return b||(b=_s(s)),Ln(V,{publicKey:i,contentType:b,fileName:t||ys(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:z})=>{let J=await Kn(s,V,$);return Promise.all([R,qn(x,z.map((tt,ct)=>()=>Yn(J(ct),tt,{publicKey:i,contentType:b,onProgress:St(z.length,ct),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Rn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Oi(R.uuid,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new pt(R,{baseCDN:T}))};async function Ri(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:b,multipartChunkSize:$,maxConcurrentRequests:x,baseCDN:T=A.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,pusherKey:at,metadata:St}){if(Bt(s)){let R=await Cs(s);return Xn(R,b)?Zn(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:x,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St}):Mn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St})}if(Ui(s))return Hn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:at,metadata:St});if(ws(s))return Nn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var $i=class{constructor(i,{baseCDN:t=A.baseCDN}={}){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new pt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Jn=s=>{for(let i of s)if(!Bt(i))return!1;return!0},Qn=s=>{for(let i of s)if(!ws(i))return!1;return!0},to=s=>{for(let i of s)if(!Ui(i))return!1;return!0};function Ts(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b=A.multipartChunkSize,baseCDN:$=A.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!Jn(s)&&!to(s)&&!Qn(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let V,at=!0,St=s.length,R=(z,J)=>{if(!a)return;V||(V=Array(z).fill(0));let tt=ct=>ct.reduce((bi,Or)=>bi+Or)/z;return ct=>{if(!ct.isComputable||!at){at=!1,a({isComputable:!1});return}V[J]=ct.value,a({isComputable:!0,value:tt(V)})}};return Promise.all(s.map((z,J)=>Bt(z)||Ui(z)?Ri(z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(St,J),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b,baseCDN:$,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T}).then(tt=>tt.uuid):z)).then(z=>On(z,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(J=>new $i(J,{baseCDN:$})).then(J=>(a&&a({isComputable:!0,value:1}),J)))}var $e=class{constructor(i){h(this,"_concurrency",1);h(this,"_pending",[]);h(this,"_running",0);h(this,"_resolvers",new Map);h(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var Pi=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),Mi=s=>({...Pi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Ue=s=>({...Mi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $e(1),"*uploadCollection":null});function xs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var H=s=>`*cfg/${s}`;var Ni="lr-",_=class extends Dt{constructor(){super();h(this,"requireCtxName",!1);h(this,"allowCustomTemplate",!0);h(this,"init$",Pi());h(this,"updateCtxCssData",()=>{te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(xs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=hs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Qt(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Ee(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ni}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ae({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),It.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),It.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new xe(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Qt(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=H(r);return this.$[o]=n,!0},get:(e,r)=>{let n=H(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ut(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(H(t));r.ctx.has(r.name)?this.sub(H(t),e):(this.bindCssData(`--cfg-${ut(t)}`),this.sub(`--cfg-${ut(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ni)?t:Ni+t)}};h(_,"StateConsumerScope",null),h(_,"className","");var Es="active",ee="___ACTIVITY_IS_ACTIVE___",et=class extends _{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Mi(this));h(this,"_debouncedHistoryFlush",I(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=et._activityRegistry[this.activityKey];this[ee]=!1,this.removeAttribute(Es),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=et._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ee]=!0,this.setAttribute(Es,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ee]?this._deactivate():this.activityType===t&&!this[ee]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!et._activityRegistry[this.activityKey]}get isActivityActive(){return this[ee]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;et._activityRegistry||(et._activityRegistry=Object.create(null)),et._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),et._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(et._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===r);n=(e=l==null?void 0:l.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},g=et;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ie=33.333333333333336,y=1,Di=24,As=6;function Ot(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function Y(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Ot(t,i),t}function $s(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Ss(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Is(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function ks({rect:s,delta:[i,t],imageBox:e}){return zt({...s,x:s.x+i,y:s.y+t},e)}function zt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function eo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Rs(s,i){return Math.abs(s.width/s.height-i)<.1}function jt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ps(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Ht(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function wt(s,i,t){return Math.min(Math.max(s,i),t)}var Pe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var Z=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Ms=s=>s?s.split(",").map(i=>i.trim()):[],Lt=s=>s?s.join(","):"";var Ns="blocks",Ds="0.30.5";function Fs(s){return Si({...s,libraryName:Ns,libraryVersion:Ds})}var Bs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Me=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Bs(i)).join("/-/"),M=(...s)=>{let i=Me(...s);return i?`-/${i}/`:""};function Vs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function js(s){let i=Hs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Bs(n))}function Hs(s){let i=new URL(s),t=Vs(s),e=Ws(t)?Xs(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ws(s){return s.startsWith("http")}function Xs(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var O=(s,i,t)=>{let e=new URL(Hs(s));if(t=t||Vs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ws(t)){let r=Xs(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},Tt=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var se=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Fi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],Bi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),qs=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),re=s=>{let i=s==null?void 0:s.type;return i?Bi(i,se):!1};var st=1e3,Ut=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ne=s=>Math.ceil(s*100)/100,Gs=(s,i=Ut.AUTO)=>{let t=i===Ut.AUTO;if(i===Ut.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(co+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var De=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Zt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new Ne(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var Ys=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:pt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!1);h(this,"isCtxOwner",!1);h(this,"init$",Ue(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",I(this._runValidators.bind(this),100));h(this,"_flushOutputItems",I(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(S.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));h(this,"_handleCollectonUpdate",(t,e,r)=>{var n;this._runValidators();for(let o of r)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()});h(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,this.emit(S.UPLOAD_PROGRESS,l,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&this.emit(S.UPLOAD_FINISH,l,{debounce:!0})}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(S.UPLOAD_ERROR,e.readProp(o,"uploadError"))}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(S.VALIDATION_ERROR,e.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(S.CLOUD_MODIFICATION,e.readProp(o,"cdnUrlModifiers"))})})}setUploadMetadata(t){te("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof v?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new De({typedSchema:Ys,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:re(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:re(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Lt(Fi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?se:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Lt(se)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Z.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(S.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(S.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Fi([...e?se:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Bi(o,n),c=qs(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Gs(e)})}_validateMultipleLimit(t){let e=this.uploadCollection.items(),r=e.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&e.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Pe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ps(l,a,c),d=M(`crop/${u.width}x${u.height}/${u.x},${u.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:O(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,l;let e=E.getCtx(t).store,r=e.fileInfo||{name:e.fileName,originalFilename:e.fileName,size:e.fileSize,isImage:e.isImage,mimeType:e.mimeType};return{...r,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(l=(o=e.cdnUrl)!=null?o:r.cdnUrl)!=null?l:null,validationErrorMessage:e.validationErrorMsg,uploadError:e.uploadError,isUploaded:!!e.uuid&&!!e.fileInfo,isValid:!e.validationErrorMsg&&!e.uploadError,fullPath:e.fullPath,uploadProgress:e.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});var G={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function ho(s,i){if(typeof i=="number")return G[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&G[s]!==i?`${s}`:"";if(s==="filter"){if(!i||G[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Js=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function xt(s){return Me(...Js.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return ho(i,t)}).filter(i=>!!i))}var Fe=Me("format/auto","progressive/yes"),mt=([s])=>typeof s!="undefined"?Number(s):void 0,Zs=()=>!0,uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),po=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),fo={enhance:mt,brightness:mt,exposure:mt,gamma:mt,contrast:mt,saturation:mt,vibrance:mt,warmth:mt,filter:uo,mirror:Zs,flip:Zs,rotate:mt,crop:po};function Qs(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Js.includes(e))continue;let n=fo[e],o=n(r);i[e]=o}return i}var L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),W=[L.CROP,L.TUNING,L.FILTERS],tr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],er=["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"],ir=["rotate","mirror","flip"],rt=Object.freeze({brightness:{zero:G.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:G.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:G.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:G.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:G.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:G.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:G.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:G.enhance,range:[0,100],keypointsNumber:1},filter:{zero:G.filter,range:[0,100],keypointsNumber:1}});var mo="https://ucarecdn.com",go="https://upload.uploadcare.com",bo="https://social.uploadcare.com",Et={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Lt(W),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:mo,baseUrl:go,socialBaseUrl:bo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var X=s=>String(s),nt=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},k=s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},_o=s=>s==="auto"?s:k(s),yo={pubkey:X,multiple:k,multipleMin:nt,multipleMax:nt,confirmUpload:k,imgOnly:k,accept:X,externalSourcesPreferredTypes:X,store:_o,cameraMirror:k,sourceList:X,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:X,removeCopyright:k,cropPreset:X,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:X,cdnCname:X,baseUrl:X,socialBaseUrl:X,secureSignature:X,secureExpire:X,secureDeliveryProxy:X,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:X},sr=(s,i)=>{if(!(typeof i=="undefined"||i===null))try{return yo[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),Et[s]}};var Be=Object.keys(Et),vo=["metadata"],Co=s=>vo.includes(s),Ve=Be.filter(s=>!Co(s)),wo={...Object.fromEntries(Ve.map(s=>[ut(s),s])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),s]))},To={...Object.fromEntries(Be.map(s=>[ut(s),H(s)])),...Object.fromEntries(Be.map(s=>[s.toLowerCase(),H(s)]))},ze=class extends _{constructor(){super();h(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Et).map(([t,e])=>[H(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of Ve)this.sub(H(e),r=>{r!==Et[e]&&(t[e]=r)},!1);for(let e of Be){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,Ve.includes(e)){let o=[...new Set([ut(e),e.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[H(e)]!==n&&(typeof n=="undefined"||n===null?this.$[H(e)]=Et[e]:this.$[H(e)]=n)},get:()=>this.$[H(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=wo[t],o=sr(n,r),l=o!=null?o:Et[n],a=this;a[n]=l}};ze.bindAttributes(To);var xo=ze;var oe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};oe.template=``;oe.bindAttributes({name:"name",size:"size"});var Eo="https://ucarecdn.com",Rt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Eo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var rr=s=>[...new Set(s)];var le="--lr-img-",nr="unresolved",Wt=2,Xt=3,or=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ar=Object.create(null),lr;for(let s in Rt)ar[le+s]=((lr=Rt[s])==null?void 0:lr.default)||"";var je=class extends Dt{constructor(){super(...arguments);h(this,"cssInit$",ar)}$$(t){return this.$[le+t]}set$$(t){for(let e in t)this.$[le+e]=t[e]}sub$$(t,e){this.sub(le+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!or&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return M(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Rt.format.default}`,`quality/${this.$$("quality")||Rt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(or&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Qt(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(nr,""),this.img.onload=()=>{this.img.removeAttribute(nr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Rt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?rr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Wt+"x")}") ${n*Wt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Xt+"x")}") ${n*Xt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Wt))}") ${Wt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Xt))}") ${Xt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Wt+"x")+` ${e*Wt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Xt+"x")+` ${e*Xt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(Rt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[le+t]=r})}};var Vi=class extends je{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var ae=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=k(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};ae.template=` `;ae.bindAttributes({dropzone:null});var He=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};He.template=' ';function Ao(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function $o(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function cr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Ao(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var F={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},hr=["focus"],So=100,zi=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function ji(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=F.INACTIVE,o=f=>{s.shouldIgnore()&&f!==F.INACTIVE||(n!==f&&e.forEach(b=>b(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(F.INACTIVE)},c=()=>{i+=1,n===F.INACTIVE&&o(F.ACTIVE)},u=()=>{i-=1,l()||o(F.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(F.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let b=[f.x,f.y],$=s.element.getBoundingClientRect(),x=Math.floor(Io(b,$)),T=x{if(s.shouldIgnore())return;f.preventDefault();let b=await cr(f.dataTransfer);s.onItems(b),o(F.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),hr.forEach(f=>{window.addEventListener(f,a)}),()=>{zi.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),hr.forEach(f=>{window.removeEventListener(f,a)})}}var ur="lr-drop-area",qt=`${ur}/registry`,ce=class extends v{constructor(){super(),this.init$={...this.init$,state:F.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[qt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[qt]||(this.$[qt]=new Set),this.$[qt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=ji({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Z.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Z.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=ji({element:i,onChange:t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[qt]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[qt];i&&(i.delete(this),i.size===0&&E.deleteCtx(ur)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ce.template=` {{text}} `;ce.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var ko="src-type-",he=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${ko}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};he.template=` `;he.bindAttributes({type:null});var Hi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=` `}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function dr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function pr(s="#fff",i="rgba(0, 0, 0, .1)"){return dr(``)}function ue(s="hsl(209, 21%, 65%)",i=32,t=32){return dr(``)}function fr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),gt=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",I(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",I(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);this.emit(S.REMOVE,e,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(Tt(this.cfg.cdnCname,this._entry.getValue("uuid")),M(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await fr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{gt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),gt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),gt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));this.emit(S.UPLOAD_START,r,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=this.getUploadClientOptions();return Ri(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal,metadata:await this.getMetadataFor(t.uid)})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};gt.template=` {{itemName}}{{errorText}} `;gt.activeInstances=new Set;var de=class extends _{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogMouseDown",t=>{this._mouseDownTarget=t.target});h(this,"_handleDialogMouseUp",t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};h(de,"StateConsumerScope","modal");de.template=``;var We=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Xe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Xe.template=` {{msgTxt}}`;var qe=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",I(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));this.emit(S.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new We,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};qe.template=`{{headerText}} `;var Ge=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Z.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ge.template=` `;var Wi=()=>typeof navigator.permissions!="undefined";var Ke=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Wi(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{Wi()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",I(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Z.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ke.template=` `;var Xi=class extends v{constructor(){super(...arguments);h(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},Oo=Xi;var Ye=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ue(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=re(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=O(n,M("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};Ye.template=` `;var qi=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Ze=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new qi);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Ze.template=`{{activityCaption}} `;var Je=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};Je.template=` `;var Qe=class extends _{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};Qe.template='';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var pe=class extends _{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${pr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};pe.template=' ';pe.bindAttributes({checkerboard:"checkerboard"});var mr="--cfg-ctx-name",U=class extends _{get cfgCssCtxName(){return this.getCssData(mr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(mr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function gr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function D(...s){let i=gr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function br(s,...i){let t=gr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var _r=s=>{if(!s)return W;let i=Ms(s).filter(t=>W.includes(t));return i.length===0?W:i};function yr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":W,"*tabId":L.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Lt(W),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=M(xt(i),"preview"),r=O(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var vr=` Network error `;var ot=class extends U{constructor(){super();h(this,"_debouncedShowLoader",I(this._showLoader.bind(this),300));this.init$={...this.init$,...yr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$["*tabId"]===L.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=zs(this.$.cdnUrl);this.$["*originalUrl"]=Tt(this.$.cdnUrl,t);let e=js(this.$.cdnUrl),r=Qs(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=Tt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=O(this.$["*originalUrl"],M("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===L.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Pe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=_r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=D("image",{image_hidden_to_cropper:t===L.CROP,image_hidden_effects:t!==L.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=M(xt(t),"preview"),n=O(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(ot,"className","cloud-image-editor");ot.template=vr;ot.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ti=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=Y("mask",{id:"backdrop-mask"}),a=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=Y("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Ot(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Ot(n,f)}else{let f=wt(Math.min(d,p)/(24*2+34)/2,0,1),{d:b,center:$}=a?$s(i,e,f):Ss(i,e,f),x=Math.max(Di*wt(Math.min(d,p)/Di/3,0,1),As);Ot(n,{x:$[0]-x,y:$[1]-x,width:x*2,height:x*2}),Ot(r,{d:b})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",D("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ot(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=Y("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=Y("rect",{fill:"transparent"}),l=Y("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=Y("svg"),t=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=Y("line",{x1:`${ie*e}%`,y1:"0%",x2:`${ie*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=Y("line",{x1:"0%",y1:`${ie*e}%`,x2:"100%",y2:`${ie*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=ks({rect:o,delta:[e,r],imageBox:n}):o=Os({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return zt(Ht(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Ls(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Is(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",D("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",D({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ti.template='';var bt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=D({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};bt.template=` {{title}}`;function Uo(s){let i=s+90;return i=i>=360?0:i,i}function Ro(s,i){return s==="rotate"?Uo(i):["mirror","flip"].includes(s)?!i:null}var fe=class extends bt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Ro(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var me={FILTER:"filter",COLOR_OPERATION:"color_operation"},lt="original",ei=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?me.FILTER:me.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===lt?void 0:this.$.value,filter:this._filter===lt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=rt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===me.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===me.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===me.FILTER?this._filter===lt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ei.template=` `;function ge(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function be(s){let i=[];for(let n of s){let o=ge(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Gt=class extends bt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==lt?{name:this._filter,amount:o}:void 0,O(this._originalUrl,M(Fe,xt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ge(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===lt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Gt.template=` `;var _e=class extends bt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=rt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Cr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function wr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Kt(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,M(Fe,xt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Po(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ii=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=I(this._commit.bind(this),300),this._handleResizeThrottled=Cr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=wr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=jt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Ht(l)}_alignCrop(){var d;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[p,m],coords:[f,b]}=n,{width:$}=jt(this._imageSize,r),x=o/$;i=zt(Ht({x:l+f*x,y:a+b*x,width:p*x,height:m*x}),this.$["*imageBox"])}let c=(d=this.$["*cropPresetList"])==null?void 0:d[0],u=c?c.width/c.height:void 0;if(!Us(i,t)||u&&!Rs(i,u)){let p=t.width/t.height,m=t.width,f=t.height;u&&(p>u?m=Math.min(t.height*u,t.width):f=Math.min(t.width/u,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=zt(Ht(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=jt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=D({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=jt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[wt(Math.round(c/d),1,l),wt(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=jt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,b=this._getCropDimensions(),$={dimensions:b,coords:[wt(Math.round((d-l)/m),0,c-b[0]),wt(Math.round((p-a)/f),0,u-b[1])]};if(!Po($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(b[0]===c&&b[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=D({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Kt(i,e,t)),{promise:n,cancel:o,image:l}=ge(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ii.template=` `;function Gi(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Mo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Do(s,i){return s.map((t,e)=>tn-o)}var Ki=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=I(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Kt(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=rt[i],r=this._keypoints.map(l=>l.value),n=No(r,t,e),o=Do(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=be(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Tr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=be(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Tr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=D({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Fo=1,si=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Fo?this.scrollLeft+=e:this.scrollLeft+=t})}};si.template=" ";function Bo(s){return` `}function Vo(s){return` `}var ri=class extends U{constructor(){super();h(this,"_updateInfoTooltip",I(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===L.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(lt);else if(this.$["*tabId"]===L.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||rt[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":lt,"*currentOperation":null,showLoader:!1,filters:er,colorOperations:tr,cropOperations:ir,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=I(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===L.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new _e;return e.operation=t,e}_createFilterControl(t){let e=new Gt;return e.filter=t,e}_createToggleControl(t){let e=new fe;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===L.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===L.FILTERS?[lt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===L.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===L.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of W){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Kt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=be([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of W){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};ri.template=` {{*operationTooltip}} `;var ye=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return D("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};ye.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ye.template=` {{text}}`;var ni=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};ni.template=``;var oi={transition:"transition",visible:"visible",hidden:"hidden"},li=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=oi.visible,this._hiddenStyle=oi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",br(this,{[oi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(oi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};li.template=" ";var ai=class extends _{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d`;var Yi=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ot,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};var zo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},xr=function(s,i="i"){let t=s.split("*").map(zo);return new RegExp("^"+t.join(".+")+"$",i)};var jo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Er({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return jo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var At={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in At){let t=At[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ar=function(s,i,t){s in At||(At[s]=[]),At[s].push([i,t])},$r=function(s,i){s in At&&(At[s]=At[s].filter(t=>t[0]!==i))};function Sr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var ci=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=xr(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Er(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Sr(n),o.toString()}mountIframe(){let t=Jt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ar("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&$r("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};ci.template=` {{activityCaption}} `;var ve=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=Jt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ve.bindAttributes({"tab-list":null,default:null});ve.template=` `;var hi=class extends v{constructor(){super();h(this,"processInnerHtml",!0);h(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return Ir.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,vi(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var e,r;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(l=>l.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,a.value=l!=null?l:"",this._dynamicInputsContainer.appendChild(a)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let l=o.find(d=>!d.isValid),a=(r=l==null?void 0:l.validationErrorMessage)!=null?r:(e=l==null?void 0:l.uploadError)==null?void 0:e.message,c=this.$["*message"];c=c!=null&&c.isError?`${c.caption}. ${c.text}`:void 0;let u=a!=null?a:c;u?this._validationInputElement.setCustomValidity(u):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(l=>l.isUploaded&&l.isValid)){this.$.output={groupData:void 0,files:t};return}let r=this.getUploadClientOptions(),n=t.map(l=>l.uuid+(l.cdnUrlModifiers?`/${l.cdnUrlModifiers}`:"")),o=await Ts(n,r);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};hi.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var Ir=hi;var Zi=class extends g{};var ui=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};ui.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},kr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?kr.exitFullscreen():kr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};Q.template=` `;Q.bindAttributes({video:"video",src:"src"});var Ho="css-src";function di(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0);h(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ae({element:this,attribute:Ho,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Ce=class extends di(_){};var pi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(pi,"template",`Powered by Uploadcare`);var $t=class extends Ce{constructor(){super(...arguments);h(this,"requireCtxName",!0);h(this,"init$",Ue(this));h(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};var fi=class extends $t{};fi.template=` `;var mi=class extends $t{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};mi.template=` `;var gi=class extends $t{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==g.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};gi.template=` `;var Ji=class extends di(ot){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function Qi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var ts="LR";async function Wo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ts]){t(window[ts]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ts];i&&Qi(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,Zi as ActivityHeader,Dt as BaseComponent,_ as Block,Ke as CameraSource,Ji as CloudImageEditor,Yi as CloudImageEditorActivity,ot as CloudImageEditorBlock,xo as Config,Ze as ConfirmationDialog,pi as Copyright,ti as CropFrame,E as Data,Ir as DataOutput,ce as DropArea,fe as EditorCropButtonControl,Gt as EditorFilterControl,ii as EditorImageCropper,Ki as EditorImageFader,_e as EditorOperationControl,si as EditorScroller,ei as EditorSlider,ri as EditorToolbar,ci as ExternalSource,gt as FileItem,pe as FilePreview,gi as FileUploaderInline,mi as FileUploaderMinimal,fi as FileUploaderRegular,oe as Icon,Vi as Img,ni as LineLoaderUi,ye as LrBtnUi,Xe as MessageBox,de as Modal,Ns as PACKAGE_NAME,Ds as PACKAGE_VERSION,li as PresenceToggle,Qe as ProgressBar,Je as ProgressBarCommon,ui as Select,Ce as ShadowWrapper,ae as SimpleBtn,ai as SliderUi,he as SourceBtn,Hi as SourceList,He as StartFrom,ve as Tabs,Oo as UploadCtxProvider,Ye as UploadDetails,qe as UploadList,v as UploaderBlock,Ge as UrlSource,Q as Video,Wo as connectBlocksFrom,Qi as registerBlocks,di as shadowed,ut as toKebabCase};
\ No newline at end of file
diff --git a/web/lr-file-uploader-minimal.min.js b/web/lr-file-uploader-minimal.min.js
index 0fc0a778f..c6d87b7ce 100644
--- a/web/lr-file-uploader-minimal.min.js
+++ b/web/lr-file-uploader-minimal.min.js
@@ -24,4 +24,4 @@
*
*/
var Ti=Object.defineProperty;var Ai=(e,i,t)=>i in e?Ti(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t;var u=(e,i,t)=>(Ai(e,typeof i!="symbol"?i+"":i,t),t);function wi(e){for(let i in e){let t=[...i].reduce((r,s)=>(s.toUpperCase()===s&&(s="-"+s.toLowerCase()),r+=s),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),e[i].reg&&e[i].reg(t)}}function $(e,i){let t,r=(...s)=>{clearTimeout(t),t=setTimeout(()=>e(...s),i)};return r.cancel=()=>{clearTimeout(t)},r}var xi=Object.defineProperty,Si=(e,i,t)=>i in e?xi(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t,ee=(e,i,t)=>(Si(e,typeof i!="symbol"?i+"":i,t),t);function Oi(e){let i=t=>{var r;for(let s in t)((r=t[s])==null?void 0:r.constructor)===Object&&(t[s]=i(t[s]));return{...t}};return i(e)}var v=class{constructor(e){e.constructor===Object?this.store=Oi(e):(this._storeIsProxy=!0,this.store=e),this.callbackMap=Object.create(null)}static warn(e,i){console.warn(`Symbiote Data: cannot ${e}. Prop name: `+i)}read(e){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(v.warn("read",e),null):this.store[e]}has(e){return this._storeIsProxy?this.store[e]!==void 0:this.store.hasOwnProperty(e)}add(e,i,t=!1){!t&&Object.keys(this.store).includes(e)||(this.store[e]=i,this.notify(e))}pub(e,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(e)){v.warn("publish",e);return}this.store[e]=i,this.notify(e)}multiPub(e){for(let i in e)this.pub(i,e[i])}notify(e){this.callbackMap[e]&&this.callbackMap[e].forEach(i=>{i(this.store[e])})}sub(e,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(v.warn("subscribe",e),null):(this.callbackMap[e]||(this.callbackMap[e]=new Set),this.callbackMap[e].add(i),t&&i(this.store[e]),{remove:()=>{this.callbackMap[e].delete(i),this.callbackMap[e].size||delete this.callbackMap[e]},callback:i})}static registerCtx(e,i=Symbol()){let t=v.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new v(e),v.globalStore.set(i,t)),t}static deleteCtx(e){v.globalStore.delete(e)}static getCtx(e,i=!0){return v.globalStore.get(e)||(i&&console.warn('State: wrong context UID - "'+e+'"'),null)}};v.globalStore=new Map;var _=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),Le="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Ii=Le.length-1,_t=class{static generate(e="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Ri(e,i){[...e.querySelectorAll(`[${_.REPEAT_ATTR}]`)].forEach(t=>{let r=t.getAttribute(_.REPEAT_ITEM_TAG_ATTR),s;if(r&&(s=window.customElements.get(r)),!s){s=class extends i.BaseComponent{constructor(){super(),r||(this.style.display="contents")}};let o=t.innerHTML;s.template=o,s.reg(r)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(_.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=h=>{h.forEach((f,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(f)});else for(let p in f)l[m][p]=f[p];else{a||(a=new DocumentFragment);let p=new s;Object.assign(p.init$,f),a.appendChild(p)}}),a&&t.appendChild(a);let d=l.slice(h.length,l.length);for(let f of d)f.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let h=[];for(let d in o){let f=o[d];Object.defineProperty(f,"_KEY_",{value:d,enumerable:!0}),h.push(f)}c(h)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(_.REPEAT_ATTR),t.removeAttribute(_.REPEAT_ITEM_TAG_ATTR)})}var Ue="__default__";function Li(e,i){if(i.shadowRoot)return;let t=[...e.querySelectorAll("slot")];if(!t.length)return;let r={};t.forEach(s=>{let n=s.getAttribute("name")||Ue;r[n]={slot:s,fr:document.createDocumentFragment()}}),i.initChildren.forEach(s=>{var n;let o=Ue;s instanceof Element&&s.hasAttribute("slot")&&(o=s.getAttribute("slot"),s.removeAttribute("slot")),(n=r[o])==null||n.fr.appendChild(s)}),Object.values(r).forEach(s=>{if(s.fr.childNodes.length)s.slot.parentNode.replaceChild(s.fr,s.slot);else if(s.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...s.slot.childNodes),s.slot.parentNode.replaceChild(n,s.slot)}else s.slot.remove()})}function Pi(e,i){[...e.querySelectorAll(`[${_.EL_REF_ATTR}]`)].forEach(t=>{let r=t.getAttribute(_.EL_REF_ATTR);i.ref[r]=t,t.removeAttribute(_.EL_REF_ATTR)})}function Mi(e,i){[...e.querySelectorAll(`[${_.BIND_ATTR}]`)].forEach(t=>{let s=t.getAttribute(_.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Ui(n.name.replace("-",""));s.push(o+":"+n.value),t.removeAttribute(n.name)}}),s.forEach(n=>{if(!n)return;let o=n.split(":").map(h=>h.trim()),l=o[0],a;l.indexOf(_.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(_.ATTR_BIND_PRFX,""));let c=o[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("!","")),i.sub(h,f=>{d==="double"?f=!!f:d==="single"&&(f=!f),a?(f==null?void 0:f.constructor)===Boolean?f?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,f):Pe(t,l,f)||(t[_.SET_LATER_KEY]||(t[_.SET_LATER_KEY]=Object.create(null)),t[_.SET_LATER_KEY][l]=f)})}}),t.removeAttribute(_.BIND_ATTR)})}var At="{{",mt="}}",ki="skip-text";function Ni(e){let i,t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var n;return!((n=s.parentElement)!=null&&n.hasAttribute(ki))&&s.textContent.includes(At)&&s.textContent.includes(mt)&&1}});for(;i=r.nextNode();)t.push(i);return t}var Di=function(e,i){Ni(e).forEach(r=>{let s=[],n;for(;r.textContent.includes(mt);)r.textContent.startsWith(At)?(n=r.textContent.indexOf(mt)+mt.length,r.splitText(n),s.push(r)):(n=r.textContent.indexOf(At),r.splitText(n)),r=r.nextSibling;s.forEach(o=>{let l=o.textContent.replace(At,"").replace(mt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},$i=[Ri,Li,Pi,Mi,Di],wt="'",ct='"',Fi=/\\([0-9a-fA-F]{1,6} ?)/g;function Vi(e){return(e[0]===ct||e[0]===wt)&&(e[e.length-1]===ct||e[e.length-1]===wt)}function zi(e){return(e[0]===ct||e[0]===wt)&&(e=e.slice(1)),(e[e.length-1]===ct||e[e.length-1]===wt)&&(e=e.slice(0,-1)),e}function ji(e){let i="",t="";for(var r=0;rString.fromCodePoint(parseInt(r.trim(),16))),i=i.replaceAll(`\\
-`,"\\n"),i=ji(i),i=ct+i+ct);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${e}`)}}var Re=0,ut=null,G=null,Z=class extends HTMLElement{constructor(){super(),ee(this,"updateCssData",()=>{var e;this.dropCssDataCache(),(e=this.__boundCssProps)==null||e.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 Z}initCallback(){}__initCallback(){var e;this.__initialized||(this.__initialized=!0,(e=this.initCallback)==null||e.call(this))}render(e,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(_.USE_TPL);if(s){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(s))||document.querySelector(s);o?e=o.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(this,this);if(e||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(e==null?void 0:e.constructor)===DocumentFragment)t=e;else if((e==null?void 0:e.constructor)===String){let s=document.createElement("template");s.innerHTML=e,t=s.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(t,this)}let r=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=r,this.shadowRoot.prepend(s)}else r()}addTemplateProcessor(e){this.tplProcessors.add(e)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=_t.generate(),this.style.setProperty(_.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(_.CSS_CTX_PROP,!0)}get ctxName(){var e;let i=((e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=v.registerCtx({},this)),this.__localCtx}get nodeCtx(){return v.getCtx(this.ctxName,!1)||v.registerCtx({},this.ctxName)}static __parseProp(e,i){let t,r;if(e.startsWith(_.EXT_DATA_CTX_PRFX))t=i.nodeCtx,r=e.replace(_.EXT_DATA_CTX_PRFX,"");else if(e.includes(_.NAMED_DATA_CTX_SPLTR)){let s=e.split(_.NAMED_DATA_CTX_SPLTR);t=v.getCtx(s[0]),r=s[1]}else t=i.localCtx,r=e;return{ctx:t,name:r}}sub(e,i,t=!0){let r=n=>{this.isConnected&&i(n)},s=Z.__parseProp(e,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,r,t)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,r,t))})}notify(e){let i=Z.__parseProp(e,this);i.ctx.notify(i.name)}has(e){let i=Z.__parseProp(e,this);return i.ctx.has(i.name)}add(e,i,t=!1){let r=Z.__parseProp(e,this);r.ctx.add(r.name,i,t)}add$(e,i=!1){for(let t in e)this.add(t,e[t],i)}get $(){if(!this.__stateProxy){let e=Object.create(null);this.__stateProxy=new Proxy(e,{set:(i,t,r)=>{let s=Z.__parseProp(t,this);return s.ctx.pub(s.name,r),!0},get:(i,t)=>{let r=Z.__parseProp(t,this);return r.ctx.read(r.name)}})}return this.__stateProxy}set$(e,i=!1){for(let t in e){let r=e[t];i||![String,Number,Boolean].includes(r==null?void 0:r.constructor)?this.$[t]=r:this.$[t]!==r&&(this.$[t]=r)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(_.CTX_OWNER_ATTR)&&this.getAttribute(_.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let e=this.constructor.__attrDesc;if(e)for(let i of Object.values(e))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(_.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(_.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(_.NAMED_DATA_CTX_SPLTR)){let t=i.split(_.NAMED_DATA_CTX_SPLTR),r=t[0].trim(),s=t[1].trim();if(r&&s){let n=v.getCtx(r,!1);n||(n=v.registerCtx({},r)),n.add(s,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var e;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim();if(i&&this.style.setProperty(_.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[_.SET_LATER_KEY]){for(let t in this[_.SET_LATER_KEY])Pe(this,t,this[_.SET_LATER_KEY][t]);delete this[_.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of $i)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${_.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(_.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(s):t.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 e of this.allSubs)e.remove(),this.allSubs.delete(e);for(let e of this.tplProcessors)this.tplProcessors.delete(e);G==null||G.delete(this.updateCssData),G!=null&&G.size||(ut==null||ut.disconnect(),ut=null,G=null)},100)))}static reg(e,i=!1){e||(Re++,e=`${_.AUTO_TAG_PRFX}-${Re}`),this.__tag=e;let t=window.customElements.get(e);if(t){!i&&t!==this&&console.warn([`Element with tag name "${e}" 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(e,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(e){this.observedAttributes=Object.keys(e),this.__attrDesc=e}attributeChangedCallback(e,i,t){var r;if(i===t)return;let s=(r=this.constructor.__attrDesc)==null?void 0:r[e];s?this.__dataCtxInitialized?this.$[s]=t:this.init$[s]=t:this[e]=t}getCssData(e,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(e)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(e).trim();try{this.__cssDataCache[e]=Xi(t)}catch{!i&&console.warn(`CSS Data error: ${e}`),this.__cssDataCache[e]=null}}return this.__cssDataCache[e]}__extractCssName(e){return e.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){G||(G=new Set),G.add(this.updateCssData),ut||(ut=new MutationObserver(e=>{e[0].type==="attributes"&&G.forEach(i=>{i()})}),ut.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(e,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(e);let t=this.getCssData(this.__extractCssName(e),!0);t===null&&(t=i),this.add(e,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(e,i,t){let r="__"+e;this[r]=this[e],Object.defineProperty(this,e,{set:s=>{this[r]=s,t?window.setTimeout(()=>{i==null||i(s)}):i==null||i(s)},get:()=>this[r]}),this[e]=this[r]}static set shadowStyles(e){let i=new Blob([e],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(e){if(!this.__rootStylesLink){let i=new Blob([e],{type:"text/css"}),t=URL.createObjectURL(i),r=document.createElement("link");r.href=t,r.rel="stylesheet",this.__rootStylesLink=r}}},ie=Z;ee(ie,"template");var te=class{static _print(e){console.warn(e)}static setDefaultTitle(e){this.defaultTitle=e}static setRoutingMap(e){Object.assign(this.appMap,e);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(e){this.__routingEventName=e}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let e={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))e.route=t.replace("?","");else if(t.includes("=")){let r=t.split("=");e.options[r[0]]=decodeURI(r[1])}else e.options[t]=!0}),e}static notify(){let e=this.readAddressBar(),i=this.appMap[e.route];if(i&&i.title&&(document.title=i.title),e.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${e.route}" not found...`);return}let t=new CustomEvent(te.routingEventName,{detail:{route:e.route,options:Object.assign(i||{},e.options)}});window.dispatchEvent(t)}static reflect(e,i={}){let t=this.appMap[e];if(!t){this._print("Wrong route: "+e);return}let r="?"+e;for(let n in i)i[n]===!0?r+=this.separator+n:r+=this.separator+n+`=${i[n]}`;let s=t.title||this.defaultTitle||"";window.history.pushState(null,s,r),document.title=s}static applyRoute(e,i={}){this.reflect(e,i),this.notify()}static setSeparator(e){this._separator=e}static get separator(){return this._separator||"&"}static createRouterData(e,i){this.setRoutingMap(i);let t=v.registerCtx({route:null,options:null,title:null},e);return window.addEventListener(this.routingEventName,r=>{var s;t.multiPub({route:r.detail.route,options:r.detail.options,title:((s=r.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),te.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}};te.appMap=Object.create(null);function Me(e,i){for(let t in i)t.includes("-")?e.style.setProperty(t,i[t]):e.style[t]=i[t]}var ke="idb-store-ready",Bi="symbiote-db",Hi="symbiote-idb-update_",Wi=class{_notifyWhenReady(e=null){window.dispatchEvent(new CustomEvent(ke,{detail:{dbName:this.name,storeName:this.storeName,event:e}}))}get _updEventName(){return Hi+this.name}_getUpdateEvent(e){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:e}})}_notifySubscribers(e){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,e),window.dispatchEvent(this._getUpdateEvent(e))}constructor(e,i){this.name=e,this.storeName=i,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(i,{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 s=>{s(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(e){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(e);return new Promise((r,s)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?r(n.target.result._value):(r(null),console.warn(`IDB: cannot read "${e}"`))},t.onerror=n=>{s(n)}})}write(e,i,t=!1){let r={_key:e,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(r);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(e),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(e,i=!1){let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);return new Promise((s,n)=>{r.onsuccess=o=>{i||this._notifySubscribers(e),s(o)},r.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,r)=>{i.onsuccess=s=>{let n=s.target.result;t(n.map(o=>o._value))},i.onerror=s=>{r(s)}})}subscribe(e,i){this._subscriptionsMap[e]||(this._subscriptionsMap[e]=new Set);let t=this._subscriptionsMap[e];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[e]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Ne.clear(this.name)}},Ne=class{static get readyEventName(){return ke}static open(e=Bi,i="store"){let t=e+"/"+i;return this._reg[t]||(this._reg[t]=new Wi(e,i)),this._reg[t]}static clear(e){window.indexedDB.deleteDatabase(e);for(let i in this._reg)i.split("/")[0]===e&&delete this._reg[i]}};ee(Ne,"_reg",Object.create(null));var A=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),Gi=Object.freeze({[A.UPLOAD_START]:"LR_UPLOAD_START",[A.REMOVE]:"LR_REMOVE",[A.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[A.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[A.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[A.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[A.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[A.DATA_OUTPUT]:"LR_DATA_OUTPUT",[A.DONE_FLOW]:"LR_DONE_FLOW",[A.INIT_FLOW]:"LR_INIT_FLOW"}),xt=class{constructor(i){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let s of this._targets)s.dispatchEvent(new CustomEvent(i,{detail:t}));let r=Gi[i];window.dispatchEvent(new CustomEvent(r,{detail:{ctx:this._getCtxName(),type:r,data:t}}))}emit(i,t,{debounce:r}={}){if(typeof r!="number"&&!r){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let s=typeof r=="number"?r:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},s);this._timeoutStore.set(i,n)}};var De="--uploadcare-blocks-window-height",ot=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(De)}};u(ot,"clientsRegistry",new Set),u(ot,"flush",$(()=>{document.documentElement.style.setProperty(De,`${window.innerHeight}px`)},100));var St=(e,i)=>new Intl.PluralRules(e).select(i);var qi=e=>e,re="{{",Fe="}}",$e="plural:";function se(e,i,t={}){var o;let{openToken:r=re,closeToken:s=Fe,transform:n=qi}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();e=e.replaceAll(r+l+s,typeof a=="string"?n(a):a)}return e}function Ve(e){let i=[],t=e.indexOf(re);for(;t!==-1;){let r=e.indexOf(Fe,t),s=e.substring(t+2,r);if(s.startsWith($e)){let n=e.substring(t+2,r).replace($e,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:s,pluralKey:o,countVariable:l})}t=e.indexOf(re,r)}return i}var Q=e=>{var i;return(i=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ot=({element:e,attribute:i,onSuccess:t,onTimeout:r,timeout:s=300})=>{let n=setTimeout(()=>{a.disconnect(),r()},s),o=c=>{let h=e.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&h!==null&&(clearTimeout(n),a.disconnect(),t(h))},l=e.getAttribute(i);l!==null&&(clearTimeout(n),t(l));let a=new MutationObserver(c=>{let h=c[c.length-1];o(h)});a.observe(e,{attributes:!0,attributeFilter:[i]})};var ze=new Set;function gt(e){ze.has(e)||(ze.add(e),console.warn(e))}function je(e){return Object.prototype.toString.call(e)==="[object Object]"}var Ki=/\W|_/g;function Yi(e){return e.split(Ki).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Xe(e,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(e)?e.map(t=>Y(t,{ignoreKeys:i})):e}function Y(e,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(e))return Xe(e,{ignoreKeys:i});if(!je(e))return e;let t={};for(let r of Object.keys(e)){let s=e[r];if(i.includes(r)){t[r]=s;continue}je(s)?s=Y(s,{ignoreKeys:i}):Array.isArray(s)&&(s=Xe(s,{ignoreKeys:i})),t[Yi(r)]=s}return t}var Ji=e=>new Promise(i=>setTimeout(i,e));function he({libraryName:e,libraryVersion:i,userAgent:t,publicKey:r="",integration:s=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:r,libraryName:e,libraryVersion:i,languageName:n,integration:s});let o=[e,i,r].filter(Boolean).join("/"),l=[n,s].filter(Boolean).join("; ");return`${o} (${l})`}var Zi={factor:2,time:100};function Qi(e,i=Zi){let t=0;function r(s){let n=Math.round(i.time*i.factor**t);return s({attempt:t,retry:l=>Ji(l!=null?l:n).then(()=>(t+=1,r(s)))})}return r(e)}var ht=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,ht.prototype),this.originalProgressEvent=t}},Ut=(e,i)=>{e&&(e.aborted?Promise.resolve().then(i):e.addEventListener("abort",()=>i(),{once:!0}))},tt=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,tt.prototype)}},tr=500,He=({check:e,interval:i=tr,timeout:t,signal:r})=>new Promise((s,n)=>{let o,l;Ut(r,()=>{o&&clearTimeout(o),n(new tt("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new tt("Timed out"))},t));let a=()=>{try{Promise.resolve(e(r)).then(c=>{c?(l&&clearTimeout(l),s(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),y={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"},Rt="application/octet-stream",We="original",et=({method:e,url:i,data:t,headers:r={},signal:s,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(e==null?void 0:e.toUpperCase())||"GET",h=!1;a.open(c,i,!0),r&&Object.entries(r).forEach(d=>{let[f,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(f,m)}),a.responseType="text",Ut(s,()=>{h=!0,a.abort(),l(new tt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:r||void 0,signal:s,onProgress:n},f=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};f.forEach(function(w){let T=w.split(": "),b=T.shift(),g=T.join(": ");b&&typeof b!="undefined"&&(m[b]=g)});let p=a.response,C=a.status;o({request:d,data:p,headers:m,status:C})}},a.onerror=d=>{h||l(new ht(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function er(e,...i){return e}var ir=({name:e})=>e?[e]:[],rr=er,sr=()=>new FormData,Ge=e=>!1,Lt=e=>typeof Blob!="undefined"&&e instanceof Blob,Pt=e=>typeof File!="undefined"&&e instanceof File,Mt=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&"uri"in e&&typeof e.uri=="string",dt=e=>Lt(e)||Pt(e)||Ge()||Mt(e),nr=e=>typeof e=="string"||typeof e=="number"||typeof e=="undefined",or=e=>!!e&&typeof e=="object"&&!Array.isArray(e),lr=e=>!!e&&typeof e=="object"&&"data"in e&&dt(e.data);function ar(e,i,t){if(lr(t)){let{name:r,contentType:s}=t,n=rr(t.data,r,s!=null?s:Rt),o=ir({name:r,contentType:s});e.push([i,n,...o])}else if(or(t))for(let[r,s]of Object.entries(t))typeof s!="undefined"&&e.push([`${i}[${r}]`,String(s)]);else nr(t)&&t&&e.push([i,t.toString()])}function ur(e){let i=[];for(let[t,r]of Object.entries(e))ar(i,t,r);return i}function de(e){let i=sr(),t=ur(e);for(let r of t){let[s,n,...o]=r;i.append(s,n,...o)}return i}var U=class extends Error{constructor(t,r,s,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=r,this.request=s,this.response=n,this.headers=o,Object.setPrototypeOf(this,U.prototype)}},cr=e=>{let i=new URLSearchParams;for(let[t,r]of Object.entries(e))r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(s=>{var n;return(n=s[1])!=null?n:!1}).forEach(s=>i.set(`${t}[${s[0]}]`,String(s[1]))):Array.isArray(r)?r.forEach(s=>{i.append(`${t}[]`,s)}):typeof r=="string"&&r?i.set(t,r):typeof r=="number"&&i.set(t,r.toString());return i.toString()},q=(e,i,t)=>{let r=new URL(e);return r.pathname=(r.pathname+i).replace("//","/"),t&&(r.search=cr(t)),r.toString()},hr="6.8.0",dr="UploadcareUploadClient",fr=hr;function lt(e){return he({libraryName:dr,libraryVersion:fr,...e})}var pr="RequestThrottledError",Be=15e3,mr=1e3;function _r(e){let{headers:i}=e||{};if(!i||typeof i["retry-after"]!="string")return Be;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Be}function it(e,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:r}=i;return Qi(({attempt:s,retry:n})=>e().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===pr&&s{let i="";return(Lt(e)||Pt(e)||Mt(e))&&(i=e.type),i||Rt},Ke=e=>{let i="";return Pt(e)&&e.name?i=e.name:Lt(e)||Ge()?i="":Mt(e)&&e.name&&(i=e.name),i||We};function fe(e){return typeof e=="undefined"||e==="auto"?"auto":e?"1":"0"}function gr(e,{publicKey:i,fileName:t,contentType:r,baseURL:s=y.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:h="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=y.retryNetworkErrorMaxTimes,metadata:C}){return it(()=>et({method:"POST",url:q(s,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":lt({publicKey:i,integration:d,userAgent:f})},data:de({file:{data:e,name:t||Ke(e),contentType:r||qe(e)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:fe(l),signature:n,expire:o,source:h,metadata:C}),signal:a,onProgress:c}).then(({data:w,headers:T,request:b})=>{let g=Y(JSON.parse(w));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,T);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var le;(function(e){e.Token="token",e.FileInfo="file_info"})(le||(le={}));function br(e,{publicKey:i,baseURL:t=y.baseURL,store:r,fileName:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=y.retryNetworkErrorMaxTimes,metadata:C}){return it(()=>et({method:"POST",headers:{"X-UC-User-Agent":lt({publicKey:i,integration:d,userAgent:f})},url:q(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:e,store:fe(r),filename:s,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:C}),signal:h}).then(({data:w,headers:T,request:b})=>{let g=Y(JSON.parse(w));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,T);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var k;(function(e){e.Unknown="unknown",e.Waiting="waiting",e.Progress="progress",e.Error="error",e.Success="success"})(k||(k={}));var yr=e=>"status"in e&&e.status===k.Error;function Cr(e,{publicKey:i,baseURL:t=y.baseURL,signal:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=y.retryNetworkErrorMaxTimes}={}){return it(()=>et({method:"GET",headers:i?{"X-UC-User-Agent":lt({publicKey:i,integration:s,userAgent:n})}:void 0,url:q(t,"/from_url/status/",{jsonerrors:1,token:e}),signal:r}).then(({data:a,headers:c,request:h})=>{let d=Y(JSON.parse(a));if("error"in d&&!yr(d))throw new U(d.error.content,void 0,h,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function vr(e,{publicKey:i,baseURL:t=y.baseURL,jsonpCallback:r,secureSignature:s,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=y.retryNetworkErrorMaxTimes}){return it(()=>et({method:"POST",headers:{"X-UC-User-Agent":lt({publicKey:i,integration:a,userAgent:c})},url:q(t,"/group/",{jsonerrors:1,pub_key:i,files:e,callback:r,signature:s,expire:n,source:l}),signal:o}).then(({data:f,headers:m,request:p})=>{let C=Y(JSON.parse(f));if("error"in C)throw new U(C.error.content,C.error.errorCode,p,C,m);return C}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function Ye(e,{publicKey:i,baseURL:t=y.baseURL,signal:r,source:s,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=y.retryNetworkErrorMaxTimes}){return it(()=>et({method:"GET",headers:{"X-UC-User-Agent":lt({publicKey:i,integration:n,userAgent:o})},url:q(t,"/info/",{jsonerrors:1,pub_key:i,file_id:e,source:s}),signal:r}).then(({data:c,headers:h,request:d})=>{let f=Y(JSON.parse(c));if("error"in f)throw new U(f.error.content,f.error.errorCode,d,f,h);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Er(e,{publicKey:i,contentType:t,fileName:r,multipartChunkSize:s=y.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:h="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=y.retryNetworkErrorMaxTimes,metadata:C}){return it(()=>et({method:"POST",url:q(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":lt({publicKey:i,integration:d,userAgent:f})},data:de({filename:r||We,size:e,content_type:t||Rt,part_size:s,UPLOADCARE_STORE:fe(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:h,metadata:C}),signal:c}).then(({data:w,headers:T,request:b})=>{let g=Y(JSON.parse(w));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,T);return g.parts=Object.keys(g.parts).map(P=>g.parts[P]),g}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})}function Tr(e,i,{contentType:t,signal:r,onProgress:s,retryThrottledRequestMaxTimes:n=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=y.retryNetworkErrorMaxTimes}){return it(()=>et({method:"PUT",url:i,data:e,onProgress:s,signal:r,headers:{"Content-Type":t||Rt}}).then(l=>(s&&s({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Ar(e,{publicKey:i,baseURL:t=y.baseURL,source:r="local",signal:s,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=y.retryNetworkErrorMaxTimes}){return it(()=>et({method:"POST",url:q(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":lt({publicKey:i,integration:n,userAgent:o})},data:de({uuid:e,UPLOADCARE_PUB_KEY:i,source:r}),signal:s}).then(({data:c,headers:h,request:d})=>{let f=Y(JSON.parse(c));if("error"in f)throw new U(f.error.content,f.error.errorCode,d,f,h);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function pe(e,{publicKey:i,baseURL:t,source:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return He({check:h=>Ye(e,{publicKey:i,baseURL:t,signal:h,source:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function wr(e){return"defaultEffects"in e}var K=class{constructor(i,{baseCDN:t=y.baseCDN,fileName:r}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);u(this,"defaultEffects",null);let{uuid:s,s3Bucket:n}=i,o=q(t,`${s}/`),l=n?q(`https://${n}.s3.amazonaws.com/`,`${s}/${i.filename}`):null;this.uuid=s,this.name=r||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,wr(i)&&(this.defaultEffects=i.defaultEffects)}},xr=(e,{publicKey:i,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,baseCDN:C,metadata:w})=>gr(e,{publicKey:i,fileName:t,contentType:l,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:w}).then(({file:T})=>pe(T,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:c,signal:a})).then(T=>new K(T,{baseCDN:C})),Sr=(e,{publicKey:i,fileName:t,baseURL:r,signal:s,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h,baseCDN:d})=>Ye(e,{publicKey:i,baseURL:r,signal:s,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h}).then(f=>new K(f,{baseCDN:d,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),Or=(e,{signal:i}={})=>{let t=null,r=null,s=e.map(()=>new AbortController),n=o=>()=>{r=o,s.forEach((l,a)=>a!==o&&l.abort())};return Ut(i,()=>{s.forEach(o=>o.abort())}),Promise.all(e.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:s[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(r===null)throw t;return o[r]})},Ir=window.WebSocket,ae=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var r;(r=this.events[i])==null||r.forEach(s=>s(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(r=>r!==t):this.events[i]=[]}},Ur=(e,i)=>e==="success"?{status:k.Success,...i}:e==="progress"?{status:k.Progress,...i}:{status:k.Error,...i},ue=class{constructor(i,t=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 ae);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Ir(i),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,Ur(r.event,JSON.parse(r.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var s;let r=JSON.stringify({event:i,data:t});(s=this.ws)==null||s.send(r)}subscribe(i,t){this.subscribers+=1,this.connect();let r=`task-status-${i}`,s={event:"pusher:subscribe",data:{channel:r}};this.emmitter.on(r,t),this.isConnected?this.send(s.event,s.data):this.queue.push(s)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,r={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(r.event,r.data):this.queue=this.queue.filter(s=>s.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},ne=null,me=e=>{if(!ne){let i=typeof window=="undefined"?0:3e4;ne=new ue(e,i)}return ne},Rr=e=>{me(e).connect()};function Lr({token:e,publicKey:i,baseURL:t,integration:r,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return He({check:c=>Cr(e,{publicKey:i,baseURL:t,integration:r,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(h=>{switch(h.status){case k.Error:return new U(h.error,h.errorCode);case k.Waiting:return!1;case k.Unknown:return new U(`Token "${e}" was not found.`);case k.Progress:return l&&(h.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:h.done/h.total})),!1;case k.Success:return l&&l({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:a})}var Pr=({token:e,pusherKey:i,signal:t,onProgress:r})=>new Promise((s,n)=>{let o=me(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(e)};Ut(t,()=>{a(),n(new tt("pusher cancelled"))}),o.subscribe(e,c=>{switch(c.status){case k.Progress:{r&&(c.total==="unknown"?r({isComputable:!1}):r({isComputable:!0,value:c.done/c.total}));break}case k.Success:{a(),r&&r({isComputable:!0,value:c.done/c.total}),s(c);break}case k.Error:a(),n(new U(c.msg,c.error_code))}})}),Mr=(e,{publicKey:i,fileName:t,baseURL:r,baseCDN:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:h,onProgress:d,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:C,pusherKey:w=y.pusherKey,metadata:T})=>Promise.resolve(Rr(w)).then(()=>br(e,{publicKey:i,fileName:t,baseURL:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:h,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:C,metadata:T})).catch(b=>{let g=me(w);return g==null||g.disconnect(),Promise.reject(b)}).then(b=>b.type===le.FileInfo?b:Or([({signal:g})=>Lr({token:b.token,publicKey:i,baseURL:r,integration:m,userAgent:p,retryThrottledRequestMaxTimes:C,onProgress:d,signal:g}),({signal:g})=>Pr({token:b.token,pusherKey:w,signal:g,onProgress:d})],{signal:h})).then(b=>{if(b instanceof U)throw b;return b}).then(b=>pe(b.uuid,{publicKey:i,baseURL:r,integration:m,userAgent:p,retryThrottledRequestMaxTimes:C,onProgress:d,signal:h})).then(b=>new K(b,{baseCDN:s})),oe=new WeakMap,kr=async e=>{if(oe.has(e))return oe.get(e);let i=await fetch(e.uri).then(t=>t.blob());return oe.set(e,i),i},Je=async e=>{if(Pt(e)||Lt(e))return e.size;if(Mt(e))return(await kr(e)).size;throw new Error("Unknown file type. Cannot determine file size.")},Nr=(e,i=y.multipartMinFileSize)=>e>=i,Ze=e=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!dt(e)&&t.test(e)},_e=e=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!dt(e)&&t.test(e)},Dr=(e,i)=>new Promise((t,r)=>{let s=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,h=l.shift();h&&h().then(d=>{n||(s[c]=d,o-=1,o?a():t(s))}).catch(d=>{n=!0,r(d)})};for(let c=0;c{let s=r*i,n=Math.min(s+r,t);return e.slice(s,n)},Fr=async(e,i,t)=>r=>$r(e,r,i,t),Vr=(e,i,{publicKey:t,contentType:r,onProgress:s,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Tr(e,i,{publicKey:t,contentType:r,onProgress:s,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),zr=async(e,{publicKey:i,fileName:t,fileSize:r,baseURL:s,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,contentType:C,multipartChunkSize:w=y.multipartChunkSize,maxConcurrentRequests:T=y.maxConcurrentRequests,baseCDN:b,metadata:g})=>{let P=r!=null?r:await Je(e),H,nt=(I,M)=>{if(!c)return;H||(H=Array(I).fill(0));let F=V=>V.reduce((W,Qt)=>W+Qt,0);return V=>{V.isComputable&&(H[M]=V.value,c({isComputable:!0,value:F(H)/I}))}};return C||(C=qe(e)),Er(P,{publicKey:i,contentType:C,fileName:t||Ke(e),baseURL:s,secureSignature:n,secureExpire:o,store:l,signal:a,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:g}).then(async({uuid:I,parts:M})=>{let F=await Fr(e,P,w);return Promise.all([I,Dr(T,M.map((V,W)=>()=>Vr(F(W),V,{publicKey:i,contentType:C,onProgress:nt(M.length,W),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})))])}).then(([I])=>Ar(I,{publicKey:i,baseURL:s,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})).then(I=>I.isReady?I:pe(I.uuid,{publicKey:i,baseURL:s,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:c,signal:a})).then(I=>new K(I,{baseCDN:b}))};async function ge(e,{publicKey:i,fileName:t,baseURL:r=y.baseURL,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartMinFileSize:C,multipartChunkSize:w,maxConcurrentRequests:T,baseCDN:b=y.baseCDN,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:P,pusherKey:H,metadata:nt}){if(dt(e)){let I=await Je(e);return Nr(I,C)?zr(e,{publicKey:i,contentType:p,multipartChunkSize:w,fileSize:I,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,maxConcurrentRequests:T,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:nt}):xr(e,{publicKey:i,fileName:t,contentType:p,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:nt})}if(_e(e))return Mr(e,{publicKey:i,fileName:t,baseURL:r,baseCDN:b,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:P,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,pusherKey:H,metadata:nt});if(Ze(e))return Sr(e,{publicKey:i,fileName:t,baseURL:r,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b});throw new TypeError(`File uploading from "${e}" is not supported`)}var ce=class{constructor(i,{baseCDN:t=y.baseCDN}={}){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let r=i.files.filter(Boolean);this.totalSize=Object.values(r).reduce((s,n)=>s+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(r).filter(s=>s.isImage).length,this.cdnUrl=i.cdnUrl,this.files=r.map(s=>new K(s,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},jr=e=>{for(let i of e)if(!dt(i))return!1;return!0},Xr=e=>{for(let i of e)if(!Ze(i))return!1;return!0},Br=e=>{for(let i of e)if(!_e(i))return!1;return!0};function Qe(e,{publicKey:i,fileName:t,baseURL:r=y.baseURL,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:C=y.multipartChunkSize,baseCDN:w=y.baseCDN,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:b,jsonpCallback:g}){if(!jr(e)&&!Br(e)&&!Xr(e))throw new TypeError(`Group uploading from "${e}" is not supported`);let P,H=!0,nt=e.length,I=(M,F)=>{if(!a)return;P||(P=Array(M).fill(0));let V=W=>W.reduce((Qt,Ei)=>Qt+Ei)/M;return W=>{if(!W.isComputable||!H){H=!1,a({isComputable:!1});return}P[F]=W.value,a({isComputable:!0,value:V(P)})}};return Promise.all(e.map((M,F)=>dt(M)||_e(M)?ge(M,{publicKey:i,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:I(nt,F),source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:C,baseCDN:w,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:b}).then(V=>V.uuid):M)).then(M=>vr(M,{publicKey:i,baseURL:r,jsonpCallback:g,secureSignature:s,secureExpire:n,signal:l,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m}).then(F=>new ce(F,{baseCDN:w})).then(F=>(a&&a({isComputable:!0,value:1}),F)))}var It=class{constructor(i){u(this,"_concurrency",1);u(this,"_pending",[]);u(this,"_running",0);u(this,"_resolvers",new Map);u(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(r),this._rejectors.delete(r),this._running-=1,this._run()}).then(o=>s(o)).catch(o=>n(o))}}add(i){return new Promise((t,r)=>{this._resolvers.set(i,t),this._rejectors.set(i,r),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var be=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),ye=e=>({...be(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{e.set$({"*modalActive":!1,"*currentActivity":""})}}),kt=e=>({...ye(e),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new It(1),"*uploadCollection":null});function ti(e,i){[...e.querySelectorAll("[l10n]")].forEach(t=>{let r=t.getAttribute("l10n"),s="textContent";if(r.includes(":")){let o=r.split(":");s=o[0],r=o[1]}let n="l10n:"+r;i.__l10nKeys.push(n),i.add(n,r),i.sub(n,o=>{t[s]=i.l10n(o)}),t.removeAttribute("l10n")})}var N=e=>`*cfg/${e}`;var Ce="lr-",O=class extends ie{constructor(){super();u(this,"requireCtxName",!1);u(this,"allowCustomTemplate",!0);u(this,"init$",be());u(this,"updateCtxCssData",()=>{gt("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let r of t)r.isConnected&&r.updateCssData()});this.activityType=null,this.addTemplateProcessor(ti),this.__l10nKeys=[]}l10n(t,r={}){if(!t)return"";let s=this.getCssData("--l10n-"+t,!0)||t,n=Ve(s);for(let l of n)r[l.variable]=this.pluralize(l.pluralKey,Number(r[l.countVariable]));return se(s,r)}pluralize(t,r){let s=this.l10n("locale-name")||"en-US",n=St(s,r);return this.l10n(`${t}__${n}`)}emit(t,r,s){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,r,s)}applyL10nKey(t,r){let s="l10n:"+t;this.$[s]=r,this.__l10nKeys.push(t)}hasBlockInCtx(t){let r=this.$["*blocksRegistry"];for(let s of r)if(t(s))return!0;return!1}setOrAddState(t,r){this.add$({[t]:r},!0)}setActivity(t){if(this.hasBlockInCtx(r=>r.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ce}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ot({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),ot.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),ot.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new xt(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),v.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){v.deleteCtx(this.ctxName)}fileSizeFmt(t,r=2){let s=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(s[0])}`;let o=1024,l=r<0?0:r,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(s[a])}proxyUrl(t){let r=this.cfg.secureDeliveryProxy;return r?se(r,{previewUrl:t},{transform:s=>window.encodeURIComponent(s)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(r,s,n)=>{if(typeof s!="string")return!1;let o=N(s);return this.$[o]=n,!0},get:(r,s)=>{let n=N(s),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(gt("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${Q(s)}`))}})}return this.__cfgProxy}subConfigValue(t,r){let s=this.parseCfgProp(N(t));s.ctx.has(s.name)?this.sub(N(t),r):(this.bindCssData(`--cfg-${Q(t)}`),this.sub(`--cfg-${Q(t)}`,r))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ce)?t:Ce+t)}};u(O,"StateConsumerScope",null),u(O,"className","");var ei="active",bt="___ACTIVITY_IS_ACTIVE___",z=class extends O{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",ye(this));u(this,"_debouncedHistoryFlush",$(this._historyFlush.bind(this),10))}_deactivate(){var r;let t=z._activityRegistry[this.activityKey];this[bt]=!1,this.removeAttribute(ei),(r=t==null?void 0:t.deactivateCallback)==null||r.call(t)}_activate(){var r;let t=z._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[bt]=!0,this.setAttribute(ei,""),(r=t==null?void 0:t.activateCallback)==null||r.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[bt]?this._deactivate():this.activityType===t&&!this[bt]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!z._activityRegistry[this.activityKey]}get isActivityActive(){return this[bt]}get couldOpenActivity(){return!0}registerActivity(t,r={}){let{onActivate:s,onDeactivate:n}=r;z._activityRegistry||(z._activityRegistry=Object.create(null)),z._activityRegistry[this.activityKey]={activateCallback:s,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),z._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(z._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var r;let t=this.$["*history"];if(t){let s=t.pop();for(;s===this.activityType;)s=t.pop();let n=!!s;if(s){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===s);n=(r=l==null?void 0:l.couldOpenActivity)!=null?r:!1}s=n?s:void 0,this.$["*currentActivity"]=s,this.$["*history"]=t,s||this.setOrAddState("*modalActive",!1)}}},E=z;u(E,"_activityRegistry",Object.create(null));E.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Hr="css-src";function Wr(e){return class extends e{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0);u(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ot({element:this,attribute:Hr,onSuccess:t=>{this.attachShadow({mode:"open"});let r=document.createElement("link");r.rel="stylesheet",r.type="text/css",r.href=t,r.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(r)},onTimeout:()=>{console.error("Attribute `css-src`is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Nt=class extends Wr(O){};var Dt=class extends Nt{constructor(){super(...arguments);u(this,"requireCtxName",!0);u(this,"init$",kt(this));u(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};var $t=class extends Dt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",r=>{r||(this.$["*currentActivity"]=t.initActivity||E.activities.START_FROM)}),this.sub("*uploadList",r=>{(r==null?void 0:r.length)>0?this.$["*currentActivity"]=E.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||E.activities.START_FROM}),this.subConfigValue("sourceList",r=>{r!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",r=>{r!==!1&&(this.cfg.confirmUpload=!1)})}};$t.template=` `;var Ft=class extends E{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};Ft.template=' ';function ii(e,i,t){let r=e/i,s,n;r>t?(s=Math.round(i*t),n=i):(s=e,n=Math.round(e/t));let o=Math.round((e-s)/2),l=Math.round((i-n)/2);return o+s>e&&(s=e-o),l+n>i&&(n=i-l),{x:o,y:l,width:s,height:n}}var ri=e=>{if(!e)return[];let[i,t]=e.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${e}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var rt=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var yt=e=>e?e.join(","):"";var si="blocks",ni="0.30.4";function oi(e){return he({...e,libraryName:si,libraryVersion:ni})}var Gr=e=>{if(typeof e!="string"||!e)return"";let i=e.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},ve=(...e)=>e.filter(i=>typeof i=="string"&&i).map(i=>Gr(i)).join("/-/"),Vt=(...e)=>{let i=ve(...e);return i?`-/${i}/`:""};function li(e){let i=new URL(e),t=i.pathname+i.search+i.hash,r=t.lastIndexOf("http"),s=t.lastIndexOf("/"),n="";return r>=0?n=t.slice(r):s>=0&&(n=t.slice(s+1)),n}function qr(e){let i=new URL(e),t=li(e),r=ai(t)?ui(t).pathname:t;return i.pathname=i.pathname.replace(r,""),i.search="",i.hash="",i.toString()}function ai(e){return e.startsWith("http")}function ui(e){let i=new URL(e);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var zt=(e,i,t)=>{let r=new URL(qr(e));if(t=t||li(e),r.pathname.startsWith("//")&&(r.pathname=r.pathname.replace("//","/")),ai(t)){let s=ui(t);r.pathname=r.pathname+(i||"")+(s.pathname||""),r.search=s.search,r.hash=s.hash}else r.pathname=r.pathname+(i||"")+(t||"");return r.toString()},ci=(e,i)=>{let t=new URL(e);return t.pathname=i+"/",t.toString()};var ft=(e,i=",")=>e.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var Ct=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Ee=e=>e?e.filter(i=>typeof i=="string").map(i=>ft(i)).flat():[],Te=(e,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),e.startsWith(t)):e===t),hi=(e,i)=>i.some(t=>t.startsWith(".")?e.toLowerCase().endsWith(t.toLowerCase()):!1),Ae=e=>{let i=e==null?void 0:e.type;return i?Te(i,Ct):!1};var j=1e3,at=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),vt=e=>Math.ceil(e*100)/100,di=(e,i=at.AUTO)=>{let t=i===at.AUTO;if(i===at.BYTE||t&&e(r[s]=i[s].value,r),{}),this.__data=v.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(fi+i);return}let r=this.__typedSchema[i];if((t==null?void 0:t.constructor)===r.type||t instanceof r.type||r.nullable&&t===null){this.__data.pub(i,t);return}console.warn(Kr+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(fi+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){v.deleteCtx(this.__ctxId)}};var Xt=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||_t.generate(),this.__data=v.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(r,s)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[r]||(t[r]=new Set),t[r].add(s),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let r of this.__collectionObservers)r==null||r([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new jt(this.__typedSchema);for(let r in i)t.setValue(r,i[r]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(r=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(r,()=>{this.__notifyObservers(r,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,r){this.read(i).setValue(t,r)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(r=>{let s=this.read(r);i(s)&&t.push(r)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){v.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var pi=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:K,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var S=class extends E{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!1);u(this,"isCtxOwner",!1);u(this,"init$",kt(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",$(this._runValidators.bind(this),100));u(this,"_flushOutputItems",$(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(A.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));u(this,"_handleCollectonUpdate",(t,r,s)=>{var n;this._runValidators();for(let o of s)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()});u(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let r=this.uploadCollection,s=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>r.read(n)).filter(Boolean);for(let n of s)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=r.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=r.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,this.emit(A.UPLOAD_PROGRESS,l,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=r.findItems(l=>!!l.getValue("fileInfo")),o=r.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(r.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&this.emit(A.UPLOAD_FINISH,l,{debounce:!0})}}t.uploadError&&r.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(A.UPLOAD_ERROR,r.readProp(o,"uploadError"))}),t.validationErrorMsg&&r.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(A.VALIDATION_ERROR,r.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&r.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(A.CLOUD_MODIFICATION,r.readProp(o,"cdnUrlModifiers"))})})}setUploadMetadata(t){gt("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof S?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new Xt({typedSchema:pi,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,r;(t=this._unobserveCollectionProperties)==null||t.call(this),(r=this._unobserveCollection)==null||r.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:s!=null?s:null,silentUpload:r!=null?r:!1,source:n!=null?n:rt.API})}addFileFromUuid(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({uuid:t,fileName:s!=null?s:null,silentUpload:r!=null?r:!1,source:n!=null?n:rt.API})}addFileFromObject(t,{silent:r,fileName:s,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:Ae(t),mimeType:t.type,fileName:s!=null?s:t.name,fileSize:t.size,silentUpload:r!=null?r:!1,source:n!=null?n:rt.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(r=>{this.uploadCollection.add({file:r,isImage:Ae(r),mimeType:r.type,fileName:r.name,fileSize:r.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var s;let r=yt(Ee([(s=this.cfg.accept)!=null?s:"",...this.cfg.imgOnly?Ct:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=yt(Ct)):this.fileInput.accept=r,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:rt.LOCAL})),this.$["*currentActivity"]=E.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=ft(this.cfg.sourceList)),t}initFlow(t=!1){var r;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":E.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let s=this.sourceList[0];s==="local"?(this.$["*currentActivity"]=E.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(S.extSrcList).includes(s)?this.set$({"*currentActivityParams":{externalSourceType:s},"*currentActivity":E.activities.EXTERNAL}):this.$["*currentActivity"]=s,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":E.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(A.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(A.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let r=this.cfg.imgOnly,s=this.cfg.accept,n=Ee([...r?Ct:[],s]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Te(o,n),c=hi(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let r=this.cfg.maxLocalFileSizeBytes,s=t.getValue("fileSize");if(r&&s&&s>r)return this.l10n("files-max-size-limit-error",{maxFileSize:di(r)})}_validateMultipleLimit(t){let r=this.uploadCollection.items(),s=r.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let r=this.cfg.imgOnly,s=t.getValue("isImage");if(!(!r||s)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let r of this._validators){let s=r(t);if(s){t.setValue("validationErrorMsg",s);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let r=this.uploadCollection.read(t);r&&this._runValidatorsForEntry(r)})}setInitialCrop(){let t=ri(this.cfg.cropPreset);if(t){let[r]=t,s=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of s){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=r.width/r.height,h=ii(l,a,c),d=Vt(`crop/${h.width}x${h.height}/${h.x},${h.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:zt(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===E.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=E.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var s;let r=(s=this.cfg.metadata)!=null?s:this.$["*uploadMetadata"];if(typeof r=="function"){let n=this.getOutputItem(t);return await r(n)}return r}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:oi,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,l;let r=v.getCtx(t).store,s=r.fileInfo||{name:r.fileName,originalFilename:r.fileName,size:r.fileSize,isImage:r.isImage,mimeType:r.mimeType};return{...s,file:r.file,externalUrl:r.externalUrl,cdnUrlModifiers:r.cdnUrlModifiers,cdnUrl:(l=(o=r.cdnUrl)!=null?o:s.cdnUrl)!=null?l:null,validationErrorMessage:r.validationErrorMsg,uploadError:r.uploadError,isUploaded:!!r.uuid&&!!r.fileInfo,isValid:!r.validationErrorMsg&&!r.uploadError,fullPath:r.fullPath,uploadProgress:r.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};S.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});S.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...S.extSrcList});var X={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};var ao=ve("format/auto","progressive/yes");var we=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),mi=[we.CROP,we.TUNING,we.FILTERS];var ho=Object.freeze({brightness:{zero:X.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:X.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:X.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:X.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:X.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:X.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:X.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:X.enhance,range:[0,100],keypointsNumber:1},filter:{zero:X.filter,range:[0,100],keypointsNumber:1}});var Yr="https://ucarecdn.com",Jr="https://upload.uploadcare.com",Zr="https://social.uploadcare.com",st={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:yt(mi),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Yr,baseUrl:Jr,socialBaseUrl:Zr,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var D=e=>String(e),B=e=>{let i=Number(e);if(Number.isNaN(i))throw new Error(`Invalid number: "${e}"`);return i},x=e=>{if(typeof e=="undefined"||e===null)return!1;if(typeof e=="boolean")return e;if(e==="true"||e==="")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean: "${e}"`)},Qr=e=>e==="auto"?e:x(e),ts={pubkey:D,multiple:x,multipleMin:B,multipleMax:B,confirmUpload:x,imgOnly:x,accept:D,externalSourcesPreferredTypes:D,store:Qr,cameraMirror:x,sourceList:D,maxLocalFileSizeBytes:B,thumbSize:B,showEmptyList:x,useLocalImageEditor:x,useCloudImageEditor:x,cloudImageEditorTabs:D,removeCopyright:x,cropPreset:D,modalScrollLock:x,modalBackdropStrokes:x,sourceListWrap:x,remoteTabSessionKey:D,cdnCname:D,baseUrl:D,socialBaseUrl:D,secureSignature:D,secureExpire:D,secureDeliveryProxy:D,retryThrottledRequestMaxTimes:B,multipartMinFileSize:B,multipartChunkSize:B,maxConcurrentRequests:B,multipartMaxConcurrentRequests:B,multipartMaxAttempts:B,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:x,groupOutput:x,userAgentIntegration:D},_i=(e,i)=>{if(!(typeof i=="undefined"||i===null))try{return ts[e](i)}catch(t){return console.error(`Invalid value for config key "${e}".`,t),st[e]}};function es(e){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let r=s=>{s.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=r,t.onprogress=r,t.readAsDataURL(e)}catch{i(!1)}})}function is(e,i){return new Promise(t=>{let r=0,s=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(r++,l.file(a=>{r--;let c=new File([a],a.name,{type:a.type||i});s.push({type:"file",file:c,fullPath:l.fullPath}),r===0&&t(s)})):l.isDirectory&&o(l.createReader())},o=l=>{r++,l.readEntries(a=>{r--;for(let c of a)n(c);r===0&&t(s)})};n(e)})}function gi(e){let i=[],t=[];for(let r=0;r{a&&i.push(...a)}));continue}let o=s.getAsFile();o&&t.push(es(o).then(l=>{l||i.push({type:"file",file:o})}))}else s.kind==="string"&&s.type.match("^text/uri-list")&&t.push(new Promise(n=>{s.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var R={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},bi=["focus"],rs=100,xe=new Map;function ss(e,i){let t=Math.max(Math.min(e[0],i.x+i.width),i.x),r=Math.max(Math.min(e[1],i.y+i.height),i.y);return Math.sqrt((e[0]-t)*(e[0]-t)+(e[1]-r)*(e[1]-r))}function Se(e){let i=0,t=document.body,r=new Set,s=p=>r.add(p),n=R.INACTIVE,o=p=>{e.shouldIgnore()&&p!==R.INACTIVE||(n!==p&&r.forEach(C=>C(p)),n=p)},l=()=>i>0;s(p=>e.onChange(p));let a=()=>{i=0,o(R.INACTIVE)},c=()=>{i+=1,n===R.INACTIVE&&o(R.ACTIVE)},h=()=>{i-=1,l()||o(R.INACTIVE)},d=p=>{p.preventDefault(),i=0,o(R.INACTIVE)},f=p=>{if(e.shouldIgnore())return;l()||(i+=1);let C=[p.x,p.y],w=e.element.getBoundingClientRect(),T=Math.floor(ss(C,w)),b=T{if(e.shouldIgnore())return;p.preventDefault();let C=await gi(p.dataTransfer);e.onItems(C),o(R.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",h),t.addEventListener("dragenter",c),t.addEventListener("dragover",f),e.element.addEventListener("drop",m),bi.forEach(p=>{window.addEventListener(p,a)}),()=>{xe.delete(e.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",h),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",f),e.element.removeEventListener("drop",m),bi.forEach(p=>{window.removeEventListener(p,a)})}}var yi="lr-drop-area",pt=`${yi}/registry`,Et=class extends S{constructor(){super(),this.init$={...this.init$,state:R.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[pt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,r=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),s=window.getComputedStyle(this),n=s.visibility!=="hidden"&&s.display!=="none";return t&&n&&r}initCallback(){super.initCallback(),this.$[pt]||(this.$[pt]=new Set),this.$[pt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!x(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:x(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:x(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:x(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Se({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(r=>{r.type==="url"?this.addFileFromUrl(r.url,{source:rt.DROP_AREA}):r.type==="file"&&this.addFileFromObject(r.file,{source:rt.DROP_AREA,fullPath:r.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":E.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Se({element:i,onChange:t=>{var s;let r=(s=Object.entries(R).find(([,n])=>n===t))==null?void 0:s[0].toLowerCase();r&&i.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var s;let r=(s=Object.entries(R).find(([,n])=>n===t))==null?void 0:s[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",t=>{let r=ft(t);this.$.isEnabled=r.includes(S.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[pt]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,r=this.uploadCollection.size;return!(i&&t&&r>=t||!i&&r>0)}destroyCallback(){var t,r;super.destroyCallback();let i=this.$[pt];i&&(i.delete(this),i.size===0&&v.deleteCtx(yi)),(t=this._destroyDropzone)==null||t.call(this),(r=this._destroyContentWrapperDropzone)==null||r.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};Et.template=` {{text}} `;Et.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Bt=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}},Ht=class extends O{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Ht.template=` {{msgTxt}}`;var Wt=class extends S{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",E.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",$(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(r=>!!r.getValue("fileInfo"));this.emit(A.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var h,d;let t=!!this.cfg.multiple,r=t?(h=this.cfg.multipleMin)!=null?h:0:1,s=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=r?ns:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:r,max:s,exact:s===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,r=this._validateFilesCount();if(t&&!r.passed){let s=new Bt,n=r.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";s.caption=this.l10n("files-count-limit-error-title"),s.text=this.l10n(n,{min:r.min,max:r.max,total:t}),s.isError=!0,this.set$({"*message":s})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),s={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let p=this.uploadCollection.read(m);p.getValue("fileInfo")&&!p.getValue("validationErrorMsg")&&(s.succeed+=1),p.getValue("isUploading")&&(s.uploading+=1),(p.getValue("validationErrorMsg")||p.getValue("uploadError"))&&(s.failed+=1),p.getValue("validationMultipleLimitMsg")&&(s.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=s.failed===0&&s.limitOverflow===0,c=!1,h=!1,d=!1;s.total-s.succeed-s.uploading-s.failed>0&&n?c=!0:(h=!0,d=s.total===s.succeed&&n&&a),this.set$({doneBtnVisible:h,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:s.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(s)})}_getHeaderText(t){let r=s=>{let n=t[s];return this.l10n(`header-${s}`,{count:n})};return t.uploading>0?r("uploading"):t.failed>0?r("failed"):t.succeed>0?r("succeed"):r("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};Wt.template=`{{headerText}} `;function ns(e){let i=new Blob([e],{type:"image/svg+xml"});return URL.createObjectURL(i)}function Oe(e="hsl(209, 21%, 65%)",i=32,t=32){return ns(``)}function Ci(e,i=40){if(e.type==="image/svg+xml")return URL.createObjectURL(e);let t=document.createElement("canvas"),r=t.getContext("2d"),s=new Image,n=new Promise((o,l)=>{s.onload=()=>{let a=s.height/s.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),r.fillStyle="rgb(240, 240, 240)",r.fillRect(0,0,t.width,t.height),r.drawImage(s,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let h=URL.createObjectURL(c);o(h)})},s.onerror=a=>{l(a)}});return s.src=URL.createObjectURL(e),n}var L=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),J=class extends S{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",$(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",$(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:L.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===E.activities.DETAILS)?this.$["*currentActivity"]=E.activities.DETAILS:this.$["*currentActivity"]=E.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let r=this.getOutputData(s=>s.getValue("uuid")===t);this.emit(A.REMOVE,r,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[r]=t;this._isIntersecting=r.isIntersecting,r.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),r.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,r=L.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?r=L.FAILED:t.getValue("validationMultipleLimitMsg")?r=L.LIMIT_OVERFLOW:t.getValue("isUploading")?r=L.UPLOADING:t.getValue("fileInfo")&&(r=L.FINISHED),this.$.state=r}async _generateThumbnail(){var r;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let s=this.cfg.thumbSize,n=this.proxyUrl(zt(ci(this.cfg.cdnCname,this._entry.getValue("uuid")),Vt(t.getValue("cdnUrlModifiers"),`scale_crop/${s}x${s}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((r=t.getValue("file"))!=null&&r.type.includes("image"))try{let s=await Ci(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",s)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Oe(n))}else{let s=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Oe(s))}}_subEntry(t,r){let s=this._entry.subscribe(t,n=>{this.isConnected&&r(n)});this._entrySubs.add(s)}_handleEntryId(t){var s;this._reset();let r=(s=this.uploadCollection)==null?void 0:s.read(t);this._entry=r,r&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||r.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=r.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{J.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),J.activeInstances.add(this)}_handleState(t){var r,s,n;this.set$({isFailed:t===L.FAILED,isLimitOverflow:t===L.LIMIT_OVERFLOW,isUploading:t===L.UPLOADING,isFinished:t===L.FINISHED,progressVisible:t===L.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((r=this._entry)==null?void 0:r.getValue("isImage"))&&((s=this._entry)==null?void 0:s.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===L.FAILED||t===L.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===L.FINISHED&&(this.$.badgeIcon="badge-success"),t===L.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),J.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let r=this.cfg.multiple?this.cfg.multipleMax:1;if(r&&this.uploadCollection.size>r)return;let s=this.getOutputData(a=>!a.getValue("fileInfo"));this.emit(A.UPLOAD_START,s,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=this.getUploadClientOptions();return ge(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let m=f.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!f.isComputable},signal:a.signal,metadata:await this.getMetadataFor(t.uid)})},h=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:h,isUploading:!1,fileName:h.originalFilename,fileSize:h.size,isImage:h.isImage,mimeType:(l=(o=(n=h.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:h.mimeType,uuid:h.uuid,cdnUrl:h.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof U?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};J.template=` {{itemName}}{{errorText}} `;J.activeInstances=new Set;var Tt=class extends O{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let r=this.getCssData(`--icon-${t}`);r&&(this.$.path=r)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};Tt.template=``;Tt.bindAttributes({name:"name",size:"size"});var Gt=class extends O{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};Gt.template='';var qt=class extends O{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};u(qt,"template",`Powered by Uploadcare`);var Kt=class extends S{constructor(){super();u(this,"processInnerHtml",!0);u(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return vi.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,Me(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var r,s;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(l=>l.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,a.value=l!=null?l:"",this._dynamicInputsContainer.appendChild(a)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let l=o.find(d=>!d.isValid),a=(s=l==null?void 0:l.validationErrorMessage)!=null?s:(r=l==null?void 0:l.uploadError)==null?void 0:r.message,c=this.$["*message"];c=c!=null&&c.isError?`${c.caption}. ${c.text}`:void 0;let h=a!=null?a:c;h?this._validationInputElement.setCustomValidity(h):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(l=>l.isUploaded&&l.isValid)){this.$.output={groupData:void 0,files:t};return}let s=this.getUploadClientOptions(),n=t.map(l=>l.uuid+(l.cdnUrlModifiers?`/${l.cdnUrlModifiers}`:"")),o=await Qe(n,s);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};Kt.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var vi=Kt;var Yt=Object.keys(st),os=["metadata"],ls=e=>os.includes(e),Jt=Yt.filter(e=>!ls(e)),as={...Object.fromEntries(Jt.map(e=>[Q(e),e])),...Object.fromEntries(Jt.map(e=>[e.toLowerCase(),e]))},us={...Object.fromEntries(Yt.map(e=>[Q(e),N(e)])),...Object.fromEntries(Yt.map(e=>[e.toLowerCase(),N(e)]))},Zt=class extends O{constructor(){super();u(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(st).map(([t,r])=>[N(t),r]))}}initCallback(){super.initCallback();let t=this;for(let r of Jt)this.sub(N(r),s=>{s!==st[r]&&(t[r]=s)},!1);for(let r of Yt){let s="__"+r;t[s]=t[r],Object.defineProperty(this,r,{set:n=>{if(t[s]=n,Jt.includes(r)){let o=[...new Set([Q(r),r.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[N(r)]!==n&&(typeof n=="undefined"||n===null?this.$[N(r)]=st[r]:this.$[N(r)]=n)},get:()=>this.$[N(r)]}),typeof t[r]!="undefined"&&t[r]!==null&&(t[r]=t[s])}}attributeChangedCallback(t,r,s){if(r===s)return;let n=as[t],o=_i(n,s),l=o!=null?o:st[n],a=this;a[n]=l}};Zt.bindAttributes(us);var cs=Zt;var Ie=class extends S{constructor(){super(...arguments);u(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},hs=Ie;export{cs as Config,qt as Copyright,vi as DataOutput,Et as DropArea,J as FileItem,$t as FileUploaderMinimal,Tt as Icon,Ht as MessageBox,Gt as ProgressBar,Ft as StartFrom,hs as UploadCtxProvider,Wt as UploadList,wi as registerBlocks};
\ No newline at end of file
+`,"\\n"),i=ji(i),i=ct+i+ct);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${e}`)}}var Re=0,ut=null,G=null,Z=class extends HTMLElement{constructor(){super(),ee(this,"updateCssData",()=>{var e;this.dropCssDataCache(),(e=this.__boundCssProps)==null||e.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 Z}initCallback(){}__initCallback(){var e;this.__initialized||(this.__initialized=!0,(e=this.initCallback)==null||e.call(this))}render(e,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(_.USE_TPL);if(s){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(s))||document.querySelector(s);o?e=o.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(this,this);if(e||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(e==null?void 0:e.constructor)===DocumentFragment)t=e;else if((e==null?void 0:e.constructor)===String){let s=document.createElement("template");s.innerHTML=e,t=s.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(t,this)}let r=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=r,this.shadowRoot.prepend(s)}else r()}addTemplateProcessor(e){this.tplProcessors.add(e)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=_t.generate(),this.style.setProperty(_.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(_.CSS_CTX_PROP,!0)}get ctxName(){var e;let i=((e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=v.registerCtx({},this)),this.__localCtx}get nodeCtx(){return v.getCtx(this.ctxName,!1)||v.registerCtx({},this.ctxName)}static __parseProp(e,i){let t,r;if(e.startsWith(_.EXT_DATA_CTX_PRFX))t=i.nodeCtx,r=e.replace(_.EXT_DATA_CTX_PRFX,"");else if(e.includes(_.NAMED_DATA_CTX_SPLTR)){let s=e.split(_.NAMED_DATA_CTX_SPLTR);t=v.getCtx(s[0]),r=s[1]}else t=i.localCtx,r=e;return{ctx:t,name:r}}sub(e,i,t=!0){let r=n=>{this.isConnected&&i(n)},s=Z.__parseProp(e,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,r,t)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,r,t))})}notify(e){let i=Z.__parseProp(e,this);i.ctx.notify(i.name)}has(e){let i=Z.__parseProp(e,this);return i.ctx.has(i.name)}add(e,i,t=!1){let r=Z.__parseProp(e,this);r.ctx.add(r.name,i,t)}add$(e,i=!1){for(let t in e)this.add(t,e[t],i)}get $(){if(!this.__stateProxy){let e=Object.create(null);this.__stateProxy=new Proxy(e,{set:(i,t,r)=>{let s=Z.__parseProp(t,this);return s.ctx.pub(s.name,r),!0},get:(i,t)=>{let r=Z.__parseProp(t,this);return r.ctx.read(r.name)}})}return this.__stateProxy}set$(e,i=!1){for(let t in e){let r=e[t];i||![String,Number,Boolean].includes(r==null?void 0:r.constructor)?this.$[t]=r:this.$[t]!==r&&(this.$[t]=r)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(_.CTX_OWNER_ATTR)&&this.getAttribute(_.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let e=this.constructor.__attrDesc;if(e)for(let i of Object.values(e))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(_.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(_.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(_.NAMED_DATA_CTX_SPLTR)){let t=i.split(_.NAMED_DATA_CTX_SPLTR),r=t[0].trim(),s=t[1].trim();if(r&&s){let n=v.getCtx(r,!1);n||(n=v.registerCtx({},r)),n.add(s,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var e;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim();if(i&&this.style.setProperty(_.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[_.SET_LATER_KEY]){for(let t in this[_.SET_LATER_KEY])Pe(this,t,this[_.SET_LATER_KEY][t]);delete this[_.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of $i)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${_.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(_.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(s):t.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 e of this.allSubs)e.remove(),this.allSubs.delete(e);for(let e of this.tplProcessors)this.tplProcessors.delete(e);G==null||G.delete(this.updateCssData),G!=null&&G.size||(ut==null||ut.disconnect(),ut=null,G=null)},100)))}static reg(e,i=!1){e||(Re++,e=`${_.AUTO_TAG_PRFX}-${Re}`),this.__tag=e;let t=window.customElements.get(e);if(t){!i&&t!==this&&console.warn([`Element with tag name "${e}" 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(e,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(e){this.observedAttributes=Object.keys(e),this.__attrDesc=e}attributeChangedCallback(e,i,t){var r;if(i===t)return;let s=(r=this.constructor.__attrDesc)==null?void 0:r[e];s?this.__dataCtxInitialized?this.$[s]=t:this.init$[s]=t:this[e]=t}getCssData(e,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(e)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(e).trim();try{this.__cssDataCache[e]=Xi(t)}catch{!i&&console.warn(`CSS Data error: ${e}`),this.__cssDataCache[e]=null}}return this.__cssDataCache[e]}__extractCssName(e){return e.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){G||(G=new Set),G.add(this.updateCssData),ut||(ut=new MutationObserver(e=>{e[0].type==="attributes"&&G.forEach(i=>{i()})}),ut.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(e,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(e);let t=this.getCssData(this.__extractCssName(e),!0);t===null&&(t=i),this.add(e,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(e,i,t){let r="__"+e;this[r]=this[e],Object.defineProperty(this,e,{set:s=>{this[r]=s,t?window.setTimeout(()=>{i==null||i(s)}):i==null||i(s)},get:()=>this[r]}),this[e]=this[r]}static set shadowStyles(e){let i=new Blob([e],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(e){if(!this.__rootStylesLink){let i=new Blob([e],{type:"text/css"}),t=URL.createObjectURL(i),r=document.createElement("link");r.href=t,r.rel="stylesheet",this.__rootStylesLink=r}}},ie=Z;ee(ie,"template");var te=class{static _print(e){console.warn(e)}static setDefaultTitle(e){this.defaultTitle=e}static setRoutingMap(e){Object.assign(this.appMap,e);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(e){this.__routingEventName=e}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let e={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))e.route=t.replace("?","");else if(t.includes("=")){let r=t.split("=");e.options[r[0]]=decodeURI(r[1])}else e.options[t]=!0}),e}static notify(){let e=this.readAddressBar(),i=this.appMap[e.route];if(i&&i.title&&(document.title=i.title),e.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${e.route}" not found...`);return}let t=new CustomEvent(te.routingEventName,{detail:{route:e.route,options:Object.assign(i||{},e.options)}});window.dispatchEvent(t)}static reflect(e,i={}){let t=this.appMap[e];if(!t){this._print("Wrong route: "+e);return}let r="?"+e;for(let n in i)i[n]===!0?r+=this.separator+n:r+=this.separator+n+`=${i[n]}`;let s=t.title||this.defaultTitle||"";window.history.pushState(null,s,r),document.title=s}static applyRoute(e,i={}){this.reflect(e,i),this.notify()}static setSeparator(e){this._separator=e}static get separator(){return this._separator||"&"}static createRouterData(e,i){this.setRoutingMap(i);let t=v.registerCtx({route:null,options:null,title:null},e);return window.addEventListener(this.routingEventName,r=>{var s;t.multiPub({route:r.detail.route,options:r.detail.options,title:((s=r.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),te.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}};te.appMap=Object.create(null);function Me(e,i){for(let t in i)t.includes("-")?e.style.setProperty(t,i[t]):e.style[t]=i[t]}var ke="idb-store-ready",Bi="symbiote-db",Hi="symbiote-idb-update_",Wi=class{_notifyWhenReady(e=null){window.dispatchEvent(new CustomEvent(ke,{detail:{dbName:this.name,storeName:this.storeName,event:e}}))}get _updEventName(){return Hi+this.name}_getUpdateEvent(e){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:e}})}_notifySubscribers(e){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,e),window.dispatchEvent(this._getUpdateEvent(e))}constructor(e,i){this.name=e,this.storeName=i,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(i,{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 s=>{s(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(e){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(e);return new Promise((r,s)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?r(n.target.result._value):(r(null),console.warn(`IDB: cannot read "${e}"`))},t.onerror=n=>{s(n)}})}write(e,i,t=!1){let r={_key:e,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(r);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(e),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(e,i=!1){let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);return new Promise((s,n)=>{r.onsuccess=o=>{i||this._notifySubscribers(e),s(o)},r.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,r)=>{i.onsuccess=s=>{let n=s.target.result;t(n.map(o=>o._value))},i.onerror=s=>{r(s)}})}subscribe(e,i){this._subscriptionsMap[e]||(this._subscriptionsMap[e]=new Set);let t=this._subscriptionsMap[e];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[e]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Ne.clear(this.name)}},Ne=class{static get readyEventName(){return ke}static open(e=Bi,i="store"){let t=e+"/"+i;return this._reg[t]||(this._reg[t]=new Wi(e,i)),this._reg[t]}static clear(e){window.indexedDB.deleteDatabase(e);for(let i in this._reg)i.split("/")[0]===e&&delete this._reg[i]}};ee(Ne,"_reg",Object.create(null));var A=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),Gi=Object.freeze({[A.UPLOAD_START]:"LR_UPLOAD_START",[A.REMOVE]:"LR_REMOVE",[A.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[A.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[A.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[A.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[A.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[A.DATA_OUTPUT]:"LR_DATA_OUTPUT",[A.DONE_FLOW]:"LR_DONE_FLOW",[A.INIT_FLOW]:"LR_INIT_FLOW"}),xt=class{constructor(i){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let s of this._targets)s.dispatchEvent(new CustomEvent(i,{detail:t}));let r=Gi[i];window.dispatchEvent(new CustomEvent(r,{detail:{ctx:this._getCtxName(),type:r,data:t}}))}emit(i,t,{debounce:r}={}){if(typeof r!="number"&&!r){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let s=typeof r=="number"?r:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},s);this._timeoutStore.set(i,n)}};var De="--uploadcare-blocks-window-height",ot=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(De)}};u(ot,"clientsRegistry",new Set),u(ot,"flush",$(()=>{document.documentElement.style.setProperty(De,`${window.innerHeight}px`)},100));var St=(e,i)=>new Intl.PluralRules(e).select(i);var qi=e=>e,re="{{",Fe="}}",$e="plural:";function se(e,i,t={}){var o;let{openToken:r=re,closeToken:s=Fe,transform:n=qi}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();e=e.replaceAll(r+l+s,typeof a=="string"?n(a):a)}return e}function Ve(e){let i=[],t=e.indexOf(re);for(;t!==-1;){let r=e.indexOf(Fe,t),s=e.substring(t+2,r);if(s.startsWith($e)){let n=e.substring(t+2,r).replace($e,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:s,pluralKey:o,countVariable:l})}t=e.indexOf(re,r)}return i}var Q=e=>{var i;return(i=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ot=({element:e,attribute:i,onSuccess:t,onTimeout:r,timeout:s=300})=>{let n=setTimeout(()=>{a.disconnect(),r()},s),o=c=>{let h=e.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&h!==null&&(clearTimeout(n),a.disconnect(),t(h))},l=e.getAttribute(i);l!==null&&(clearTimeout(n),t(l));let a=new MutationObserver(c=>{let h=c[c.length-1];o(h)});a.observe(e,{attributes:!0,attributeFilter:[i]})};var ze=new Set;function gt(e){ze.has(e)||(ze.add(e),console.warn(e))}function je(e){return Object.prototype.toString.call(e)==="[object Object]"}var Ki=/\W|_/g;function Yi(e){return e.split(Ki).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Xe(e,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(e)?e.map(t=>Y(t,{ignoreKeys:i})):e}function Y(e,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(e))return Xe(e,{ignoreKeys:i});if(!je(e))return e;let t={};for(let r of Object.keys(e)){let s=e[r];if(i.includes(r)){t[r]=s;continue}je(s)?s=Y(s,{ignoreKeys:i}):Array.isArray(s)&&(s=Xe(s,{ignoreKeys:i})),t[Yi(r)]=s}return t}var Ji=e=>new Promise(i=>setTimeout(i,e));function he({libraryName:e,libraryVersion:i,userAgent:t,publicKey:r="",integration:s=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:r,libraryName:e,libraryVersion:i,languageName:n,integration:s});let o=[e,i,r].filter(Boolean).join("/"),l=[n,s].filter(Boolean).join("; ");return`${o} (${l})`}var Zi={factor:2,time:100};function Qi(e,i=Zi){let t=0;function r(s){let n=Math.round(i.time*i.factor**t);return s({attempt:t,retry:l=>Ji(l!=null?l:n).then(()=>(t+=1,r(s)))})}return r(e)}var ht=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,ht.prototype),this.originalProgressEvent=t}},Ut=(e,i)=>{e&&(e.aborted?Promise.resolve().then(i):e.addEventListener("abort",()=>i(),{once:!0}))},tt=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,tt.prototype)}},tr=500,He=({check:e,interval:i=tr,timeout:t,signal:r})=>new Promise((s,n)=>{let o,l;Ut(r,()=>{o&&clearTimeout(o),n(new tt("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new tt("Timed out"))},t));let a=()=>{try{Promise.resolve(e(r)).then(c=>{c?(l&&clearTimeout(l),s(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),y={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"},Rt="application/octet-stream",We="original",et=({method:e,url:i,data:t,headers:r={},signal:s,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(e==null?void 0:e.toUpperCase())||"GET",h=!1;a.open(c,i,!0),r&&Object.entries(r).forEach(d=>{let[f,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(f,m)}),a.responseType="text",Ut(s,()=>{h=!0,a.abort(),l(new tt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:r||void 0,signal:s,onProgress:n},f=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};f.forEach(function(w){let T=w.split(": "),b=T.shift(),g=T.join(": ");b&&typeof b!="undefined"&&(m[b]=g)});let p=a.response,C=a.status;o({request:d,data:p,headers:m,status:C})}},a.onerror=d=>{h||l(new ht(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function er(e,...i){return e}var ir=({name:e})=>e?[e]:[],rr=er,sr=()=>new FormData,Ge=e=>!1,Lt=e=>typeof Blob!="undefined"&&e instanceof Blob,Pt=e=>typeof File!="undefined"&&e instanceof File,Mt=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&"uri"in e&&typeof e.uri=="string",dt=e=>Lt(e)||Pt(e)||Ge()||Mt(e),nr=e=>typeof e=="string"||typeof e=="number"||typeof e=="undefined",or=e=>!!e&&typeof e=="object"&&!Array.isArray(e),lr=e=>!!e&&typeof e=="object"&&"data"in e&&dt(e.data);function ar(e,i,t){if(lr(t)){let{name:r,contentType:s}=t,n=rr(t.data,r,s!=null?s:Rt),o=ir({name:r,contentType:s});e.push([i,n,...o])}else if(or(t))for(let[r,s]of Object.entries(t))typeof s!="undefined"&&e.push([`${i}[${r}]`,String(s)]);else nr(t)&&t&&e.push([i,t.toString()])}function ur(e){let i=[];for(let[t,r]of Object.entries(e))ar(i,t,r);return i}function de(e){let i=sr(),t=ur(e);for(let r of t){let[s,n,...o]=r;i.append(s,n,...o)}return i}var U=class extends Error{constructor(t,r,s,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=r,this.request=s,this.response=n,this.headers=o,Object.setPrototypeOf(this,U.prototype)}},cr=e=>{let i=new URLSearchParams;for(let[t,r]of Object.entries(e))r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(s=>{var n;return(n=s[1])!=null?n:!1}).forEach(s=>i.set(`${t}[${s[0]}]`,String(s[1]))):Array.isArray(r)?r.forEach(s=>{i.append(`${t}[]`,s)}):typeof r=="string"&&r?i.set(t,r):typeof r=="number"&&i.set(t,r.toString());return i.toString()},q=(e,i,t)=>{let r=new URL(e);return r.pathname=(r.pathname+i).replace("//","/"),t&&(r.search=cr(t)),r.toString()},hr="6.8.0",dr="UploadcareUploadClient",fr=hr;function lt(e){return he({libraryName:dr,libraryVersion:fr,...e})}var pr="RequestThrottledError",Be=15e3,mr=1e3;function _r(e){let{headers:i}=e||{};if(!i||typeof i["retry-after"]!="string")return Be;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Be}function it(e,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:r}=i;return Qi(({attempt:s,retry:n})=>e().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===pr&&s{let i="";return(Lt(e)||Pt(e)||Mt(e))&&(i=e.type),i||Rt},Ke=e=>{let i="";return Pt(e)&&e.name?i=e.name:Lt(e)||Ge()?i="":Mt(e)&&e.name&&(i=e.name),i||We};function fe(e){return typeof e=="undefined"||e==="auto"?"auto":e?"1":"0"}function gr(e,{publicKey:i,fileName:t,contentType:r,baseURL:s=y.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:h="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=y.retryNetworkErrorMaxTimes,metadata:C}){return it(()=>et({method:"POST",url:q(s,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":lt({publicKey:i,integration:d,userAgent:f})},data:de({file:{data:e,name:t||Ke(e),contentType:r||qe(e)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:fe(l),signature:n,expire:o,source:h,metadata:C}),signal:a,onProgress:c}).then(({data:w,headers:T,request:b})=>{let g=Y(JSON.parse(w));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,T);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var le;(function(e){e.Token="token",e.FileInfo="file_info"})(le||(le={}));function br(e,{publicKey:i,baseURL:t=y.baseURL,store:r,fileName:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=y.retryNetworkErrorMaxTimes,metadata:C}){return it(()=>et({method:"POST",headers:{"X-UC-User-Agent":lt({publicKey:i,integration:d,userAgent:f})},url:q(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:e,store:fe(r),filename:s,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:C}),signal:h}).then(({data:w,headers:T,request:b})=>{let g=Y(JSON.parse(w));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,T);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var k;(function(e){e.Unknown="unknown",e.Waiting="waiting",e.Progress="progress",e.Error="error",e.Success="success"})(k||(k={}));var yr=e=>"status"in e&&e.status===k.Error;function Cr(e,{publicKey:i,baseURL:t=y.baseURL,signal:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=y.retryNetworkErrorMaxTimes}={}){return it(()=>et({method:"GET",headers:i?{"X-UC-User-Agent":lt({publicKey:i,integration:s,userAgent:n})}:void 0,url:q(t,"/from_url/status/",{jsonerrors:1,token:e}),signal:r}).then(({data:a,headers:c,request:h})=>{let d=Y(JSON.parse(a));if("error"in d&&!yr(d))throw new U(d.error.content,void 0,h,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function vr(e,{publicKey:i,baseURL:t=y.baseURL,jsonpCallback:r,secureSignature:s,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=y.retryNetworkErrorMaxTimes}){return it(()=>et({method:"POST",headers:{"X-UC-User-Agent":lt({publicKey:i,integration:a,userAgent:c})},url:q(t,"/group/",{jsonerrors:1,pub_key:i,files:e,callback:r,signature:s,expire:n,source:l}),signal:o}).then(({data:f,headers:m,request:p})=>{let C=Y(JSON.parse(f));if("error"in C)throw new U(C.error.content,C.error.errorCode,p,C,m);return C}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function Ye(e,{publicKey:i,baseURL:t=y.baseURL,signal:r,source:s,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=y.retryNetworkErrorMaxTimes}){return it(()=>et({method:"GET",headers:{"X-UC-User-Agent":lt({publicKey:i,integration:n,userAgent:o})},url:q(t,"/info/",{jsonerrors:1,pub_key:i,file_id:e,source:s}),signal:r}).then(({data:c,headers:h,request:d})=>{let f=Y(JSON.parse(c));if("error"in f)throw new U(f.error.content,f.error.errorCode,d,f,h);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Er(e,{publicKey:i,contentType:t,fileName:r,multipartChunkSize:s=y.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:h="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=y.retryNetworkErrorMaxTimes,metadata:C}){return it(()=>et({method:"POST",url:q(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":lt({publicKey:i,integration:d,userAgent:f})},data:de({filename:r||We,size:e,content_type:t||Rt,part_size:s,UPLOADCARE_STORE:fe(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:h,metadata:C}),signal:c}).then(({data:w,headers:T,request:b})=>{let g=Y(JSON.parse(w));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,T);return g.parts=Object.keys(g.parts).map(P=>g.parts[P]),g}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})}function Tr(e,i,{contentType:t,signal:r,onProgress:s,retryThrottledRequestMaxTimes:n=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=y.retryNetworkErrorMaxTimes}){return it(()=>et({method:"PUT",url:i,data:e,onProgress:s,signal:r,headers:{"Content-Type":t||Rt}}).then(l=>(s&&s({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Ar(e,{publicKey:i,baseURL:t=y.baseURL,source:r="local",signal:s,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=y.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=y.retryNetworkErrorMaxTimes}){return it(()=>et({method:"POST",url:q(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":lt({publicKey:i,integration:n,userAgent:o})},data:de({uuid:e,UPLOADCARE_PUB_KEY:i,source:r}),signal:s}).then(({data:c,headers:h,request:d})=>{let f=Y(JSON.parse(c));if("error"in f)throw new U(f.error.content,f.error.errorCode,d,f,h);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function pe(e,{publicKey:i,baseURL:t,source:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return He({check:h=>Ye(e,{publicKey:i,baseURL:t,signal:h,source:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function wr(e){return"defaultEffects"in e}var K=class{constructor(i,{baseCDN:t=y.baseCDN,fileName:r}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);u(this,"defaultEffects",null);let{uuid:s,s3Bucket:n}=i,o=q(t,`${s}/`),l=n?q(`https://${n}.s3.amazonaws.com/`,`${s}/${i.filename}`):null;this.uuid=s,this.name=r||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,wr(i)&&(this.defaultEffects=i.defaultEffects)}},xr=(e,{publicKey:i,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,baseCDN:C,metadata:w})=>gr(e,{publicKey:i,fileName:t,contentType:l,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:w}).then(({file:T})=>pe(T,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:c,signal:a})).then(T=>new K(T,{baseCDN:C})),Sr=(e,{publicKey:i,fileName:t,baseURL:r,signal:s,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h,baseCDN:d})=>Ye(e,{publicKey:i,baseURL:r,signal:s,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h}).then(f=>new K(f,{baseCDN:d,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),Or=(e,{signal:i}={})=>{let t=null,r=null,s=e.map(()=>new AbortController),n=o=>()=>{r=o,s.forEach((l,a)=>a!==o&&l.abort())};return Ut(i,()=>{s.forEach(o=>o.abort())}),Promise.all(e.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:s[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(r===null)throw t;return o[r]})},Ir=window.WebSocket,ae=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var r;(r=this.events[i])==null||r.forEach(s=>s(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(r=>r!==t):this.events[i]=[]}},Ur=(e,i)=>e==="success"?{status:k.Success,...i}:e==="progress"?{status:k.Progress,...i}:{status:k.Error,...i},ue=class{constructor(i,t=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 ae);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Ir(i),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,Ur(r.event,JSON.parse(r.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var s;let r=JSON.stringify({event:i,data:t});(s=this.ws)==null||s.send(r)}subscribe(i,t){this.subscribers+=1,this.connect();let r=`task-status-${i}`,s={event:"pusher:subscribe",data:{channel:r}};this.emmitter.on(r,t),this.isConnected?this.send(s.event,s.data):this.queue.push(s)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,r={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(r.event,r.data):this.queue=this.queue.filter(s=>s.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},ne=null,me=e=>{if(!ne){let i=typeof window=="undefined"?0:3e4;ne=new ue(e,i)}return ne},Rr=e=>{me(e).connect()};function Lr({token:e,publicKey:i,baseURL:t,integration:r,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return He({check:c=>Cr(e,{publicKey:i,baseURL:t,integration:r,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(h=>{switch(h.status){case k.Error:return new U(h.error,h.errorCode);case k.Waiting:return!1;case k.Unknown:return new U(`Token "${e}" was not found.`);case k.Progress:return l&&(h.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:h.done/h.total})),!1;case k.Success:return l&&l({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:a})}var Pr=({token:e,pusherKey:i,signal:t,onProgress:r})=>new Promise((s,n)=>{let o=me(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(e)};Ut(t,()=>{a(),n(new tt("pusher cancelled"))}),o.subscribe(e,c=>{switch(c.status){case k.Progress:{r&&(c.total==="unknown"?r({isComputable:!1}):r({isComputable:!0,value:c.done/c.total}));break}case k.Success:{a(),r&&r({isComputable:!0,value:c.done/c.total}),s(c);break}case k.Error:a(),n(new U(c.msg,c.error_code))}})}),Mr=(e,{publicKey:i,fileName:t,baseURL:r,baseCDN:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:h,onProgress:d,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:C,pusherKey:w=y.pusherKey,metadata:T})=>Promise.resolve(Rr(w)).then(()=>br(e,{publicKey:i,fileName:t,baseURL:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:h,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:C,metadata:T})).catch(b=>{let g=me(w);return g==null||g.disconnect(),Promise.reject(b)}).then(b=>b.type===le.FileInfo?b:Or([({signal:g})=>Lr({token:b.token,publicKey:i,baseURL:r,integration:m,userAgent:p,retryThrottledRequestMaxTimes:C,onProgress:d,signal:g}),({signal:g})=>Pr({token:b.token,pusherKey:w,signal:g,onProgress:d})],{signal:h})).then(b=>{if(b instanceof U)throw b;return b}).then(b=>pe(b.uuid,{publicKey:i,baseURL:r,integration:m,userAgent:p,retryThrottledRequestMaxTimes:C,onProgress:d,signal:h})).then(b=>new K(b,{baseCDN:s})),oe=new WeakMap,kr=async e=>{if(oe.has(e))return oe.get(e);let i=await fetch(e.uri).then(t=>t.blob());return oe.set(e,i),i},Je=async e=>{if(Pt(e)||Lt(e))return e.size;if(Mt(e))return(await kr(e)).size;throw new Error("Unknown file type. Cannot determine file size.")},Nr=(e,i=y.multipartMinFileSize)=>e>=i,Ze=e=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!dt(e)&&t.test(e)},_e=e=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!dt(e)&&t.test(e)},Dr=(e,i)=>new Promise((t,r)=>{let s=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,h=l.shift();h&&h().then(d=>{n||(s[c]=d,o-=1,o?a():t(s))}).catch(d=>{n=!0,r(d)})};for(let c=0;c{let s=r*i,n=Math.min(s+r,t);return e.slice(s,n)},Fr=async(e,i,t)=>r=>$r(e,r,i,t),Vr=(e,i,{publicKey:t,contentType:r,onProgress:s,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Tr(e,i,{publicKey:t,contentType:r,onProgress:s,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),zr=async(e,{publicKey:i,fileName:t,fileSize:r,baseURL:s,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,contentType:C,multipartChunkSize:w=y.multipartChunkSize,maxConcurrentRequests:T=y.maxConcurrentRequests,baseCDN:b,metadata:g})=>{let P=r!=null?r:await Je(e),H,nt=(I,M)=>{if(!c)return;H||(H=Array(I).fill(0));let F=V=>V.reduce((W,Qt)=>W+Qt,0);return V=>{V.isComputable&&(H[M]=V.value,c({isComputable:!0,value:F(H)/I}))}};return C||(C=qe(e)),Er(P,{publicKey:i,contentType:C,fileName:t||Ke(e),baseURL:s,secureSignature:n,secureExpire:o,store:l,signal:a,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:g}).then(async({uuid:I,parts:M})=>{let F=await Fr(e,P,w);return Promise.all([I,Dr(T,M.map((V,W)=>()=>Vr(F(W),V,{publicKey:i,contentType:C,onProgress:nt(M.length,W),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})))])}).then(([I])=>Ar(I,{publicKey:i,baseURL:s,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})).then(I=>I.isReady?I:pe(I.uuid,{publicKey:i,baseURL:s,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:c,signal:a})).then(I=>new K(I,{baseCDN:b}))};async function ge(e,{publicKey:i,fileName:t,baseURL:r=y.baseURL,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartMinFileSize:C,multipartChunkSize:w,maxConcurrentRequests:T,baseCDN:b=y.baseCDN,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:P,pusherKey:H,metadata:nt}){if(dt(e)){let I=await Je(e);return Nr(I,C)?zr(e,{publicKey:i,contentType:p,multipartChunkSize:w,fileSize:I,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,maxConcurrentRequests:T,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:nt}):xr(e,{publicKey:i,fileName:t,contentType:p,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:nt})}if(_e(e))return Mr(e,{publicKey:i,fileName:t,baseURL:r,baseCDN:b,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:P,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,pusherKey:H,metadata:nt});if(Ze(e))return Sr(e,{publicKey:i,fileName:t,baseURL:r,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b});throw new TypeError(`File uploading from "${e}" is not supported`)}var ce=class{constructor(i,{baseCDN:t=y.baseCDN}={}){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let r=i.files.filter(Boolean);this.totalSize=Object.values(r).reduce((s,n)=>s+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(r).filter(s=>s.isImage).length,this.cdnUrl=i.cdnUrl,this.files=r.map(s=>new K(s,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},jr=e=>{for(let i of e)if(!dt(i))return!1;return!0},Xr=e=>{for(let i of e)if(!Ze(i))return!1;return!0},Br=e=>{for(let i of e)if(!_e(i))return!1;return!0};function Qe(e,{publicKey:i,fileName:t,baseURL:r=y.baseURL,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:C=y.multipartChunkSize,baseCDN:w=y.baseCDN,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:b,jsonpCallback:g}){if(!jr(e)&&!Br(e)&&!Xr(e))throw new TypeError(`Group uploading from "${e}" is not supported`);let P,H=!0,nt=e.length,I=(M,F)=>{if(!a)return;P||(P=Array(M).fill(0));let V=W=>W.reduce((Qt,Ei)=>Qt+Ei)/M;return W=>{if(!W.isComputable||!H){H=!1,a({isComputable:!1});return}P[F]=W.value,a({isComputable:!0,value:V(P)})}};return Promise.all(e.map((M,F)=>dt(M)||_e(M)?ge(M,{publicKey:i,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:I(nt,F),source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:C,baseCDN:w,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:b}).then(V=>V.uuid):M)).then(M=>vr(M,{publicKey:i,baseURL:r,jsonpCallback:g,secureSignature:s,secureExpire:n,signal:l,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m}).then(F=>new ce(F,{baseCDN:w})).then(F=>(a&&a({isComputable:!0,value:1}),F)))}var It=class{constructor(i){u(this,"_concurrency",1);u(this,"_pending",[]);u(this,"_running",0);u(this,"_resolvers",new Map);u(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(r),this._rejectors.delete(r),this._running-=1,this._run()}).then(o=>s(o)).catch(o=>n(o))}}add(i){return new Promise((t,r)=>{this._resolvers.set(i,t),this._rejectors.set(i,r),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var be=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),ye=e=>({...be(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{e.set$({"*modalActive":!1,"*currentActivity":""})}}),kt=e=>({...ye(e),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new It(1),"*uploadCollection":null});function ti(e,i){[...e.querySelectorAll("[l10n]")].forEach(t=>{let r=t.getAttribute("l10n"),s="textContent";if(r.includes(":")){let o=r.split(":");s=o[0],r=o[1]}let n="l10n:"+r;i.__l10nKeys.push(n),i.add(n,r),i.sub(n,o=>{t[s]=i.l10n(o)}),t.removeAttribute("l10n")})}var N=e=>`*cfg/${e}`;var Ce="lr-",O=class extends ie{constructor(){super();u(this,"requireCtxName",!1);u(this,"allowCustomTemplate",!0);u(this,"init$",be());u(this,"updateCtxCssData",()=>{gt("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let r of t)r.isConnected&&r.updateCssData()});this.activityType=null,this.addTemplateProcessor(ti),this.__l10nKeys=[]}l10n(t,r={}){if(!t)return"";let s=this.getCssData("--l10n-"+t,!0)||t,n=Ve(s);for(let l of n)r[l.variable]=this.pluralize(l.pluralKey,Number(r[l.countVariable]));return se(s,r)}pluralize(t,r){let s=this.l10n("locale-name")||"en-US",n=St(s,r);return this.l10n(`${t}__${n}`)}emit(t,r,s){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,r,s)}applyL10nKey(t,r){let s="l10n:"+t;this.$[s]=r,this.__l10nKeys.push(t)}hasBlockInCtx(t){let r=this.$["*blocksRegistry"];for(let s of r)if(t(s))return!0;return!1}setOrAddState(t,r){this.add$({[t]:r},!0)}setActivity(t){if(this.hasBlockInCtx(r=>r.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ce}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ot({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),ot.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),ot.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new xt(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),v.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){v.deleteCtx(this.ctxName)}fileSizeFmt(t,r=2){let s=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(s[0])}`;let o=1024,l=r<0?0:r,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(s[a])}proxyUrl(t){let r=this.cfg.secureDeliveryProxy;return r?se(r,{previewUrl:t},{transform:s=>window.encodeURIComponent(s)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(r,s,n)=>{if(typeof s!="string")return!1;let o=N(s);return this.$[o]=n,!0},get:(r,s)=>{let n=N(s),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(gt("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${Q(s)}`))}})}return this.__cfgProxy}subConfigValue(t,r){let s=this.parseCfgProp(N(t));s.ctx.has(s.name)?this.sub(N(t),r):(this.bindCssData(`--cfg-${Q(t)}`),this.sub(`--cfg-${Q(t)}`,r))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ce)?t:Ce+t)}};u(O,"StateConsumerScope",null),u(O,"className","");var ei="active",bt="___ACTIVITY_IS_ACTIVE___",z=class extends O{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",ye(this));u(this,"_debouncedHistoryFlush",$(this._historyFlush.bind(this),10))}_deactivate(){var r;let t=z._activityRegistry[this.activityKey];this[bt]=!1,this.removeAttribute(ei),(r=t==null?void 0:t.deactivateCallback)==null||r.call(t)}_activate(){var r;let t=z._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[bt]=!0,this.setAttribute(ei,""),(r=t==null?void 0:t.activateCallback)==null||r.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[bt]?this._deactivate():this.activityType===t&&!this[bt]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!z._activityRegistry[this.activityKey]}get isActivityActive(){return this[bt]}get couldOpenActivity(){return!0}registerActivity(t,r={}){let{onActivate:s,onDeactivate:n}=r;z._activityRegistry||(z._activityRegistry=Object.create(null)),z._activityRegistry[this.activityKey]={activateCallback:s,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),z._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(z._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var r;let t=this.$["*history"];if(t){let s=t.pop();for(;s===this.activityType;)s=t.pop();let n=!!s;if(s){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===s);n=(r=l==null?void 0:l.couldOpenActivity)!=null?r:!1}s=n?s:void 0,this.$["*currentActivity"]=s,this.$["*history"]=t,s||this.setOrAddState("*modalActive",!1)}}},E=z;u(E,"_activityRegistry",Object.create(null));E.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Hr="css-src";function Wr(e){return class extends e{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0);u(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ot({element:this,attribute:Hr,onSuccess:t=>{this.attachShadow({mode:"open"});let r=document.createElement("link");r.rel="stylesheet",r.type="text/css",r.href=t,r.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(r)},onTimeout:()=>{console.error("Attribute `css-src`is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Nt=class extends Wr(O){};var Dt=class extends Nt{constructor(){super(...arguments);u(this,"requireCtxName",!0);u(this,"init$",kt(this));u(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};var $t=class extends Dt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",r=>{r||(this.$["*currentActivity"]=t.initActivity||E.activities.START_FROM)}),this.sub("*uploadList",r=>{(r==null?void 0:r.length)>0?this.$["*currentActivity"]=E.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||E.activities.START_FROM}),this.subConfigValue("sourceList",r=>{r!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",r=>{r!==!1&&(this.cfg.confirmUpload=!1)})}};$t.template=` `;var Ft=class extends E{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};Ft.template=' ';function ii(e,i,t){let r=e/i,s,n;r>t?(s=Math.round(i*t),n=i):(s=e,n=Math.round(e/t));let o=Math.round((e-s)/2),l=Math.round((i-n)/2);return o+s>e&&(s=e-o),l+n>i&&(n=i-l),{x:o,y:l,width:s,height:n}}var ri=e=>{if(!e)return[];let[i,t]=e.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${e}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var rt=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var yt=e=>e?e.join(","):"";var si="blocks",ni="0.30.5";function oi(e){return he({...e,libraryName:si,libraryVersion:ni})}var Gr=e=>{if(typeof e!="string"||!e)return"";let i=e.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},ve=(...e)=>e.filter(i=>typeof i=="string"&&i).map(i=>Gr(i)).join("/-/"),Vt=(...e)=>{let i=ve(...e);return i?`-/${i}/`:""};function li(e){let i=new URL(e),t=i.pathname+i.search+i.hash,r=t.lastIndexOf("http"),s=t.lastIndexOf("/"),n="";return r>=0?n=t.slice(r):s>=0&&(n=t.slice(s+1)),n}function qr(e){let i=new URL(e),t=li(e),r=ai(t)?ui(t).pathname:t;return i.pathname=i.pathname.replace(r,""),i.search="",i.hash="",i.toString()}function ai(e){return e.startsWith("http")}function ui(e){let i=new URL(e);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var zt=(e,i,t)=>{let r=new URL(qr(e));if(t=t||li(e),r.pathname.startsWith("//")&&(r.pathname=r.pathname.replace("//","/")),ai(t)){let s=ui(t);r.pathname=r.pathname+(i||"")+(s.pathname||""),r.search=s.search,r.hash=s.hash}else r.pathname=r.pathname+(i||"")+(t||"");return r.toString()},ci=(e,i)=>{let t=new URL(e);return t.pathname=i+"/",t.toString()};var ft=(e,i=",")=>e.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var Ct=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Ee=e=>e?e.filter(i=>typeof i=="string").map(i=>ft(i)).flat():[],Te=(e,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),e.startsWith(t)):e===t),hi=(e,i)=>i.some(t=>t.startsWith(".")?e.toLowerCase().endsWith(t.toLowerCase()):!1),Ae=e=>{let i=e==null?void 0:e.type;return i?Te(i,Ct):!1};var j=1e3,at=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),vt=e=>Math.ceil(e*100)/100,di=(e,i=at.AUTO)=>{let t=i===at.AUTO;if(i===at.BYTE||t&&e(r[s]=i[s].value,r),{}),this.__data=v.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(fi+i);return}let r=this.__typedSchema[i];if((t==null?void 0:t.constructor)===r.type||t instanceof r.type||r.nullable&&t===null){this.__data.pub(i,t);return}console.warn(Kr+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(fi+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){v.deleteCtx(this.__ctxId)}};var Xt=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||_t.generate(),this.__data=v.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(r,s)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[r]||(t[r]=new Set),t[r].add(s),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let r of this.__collectionObservers)r==null||r([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new jt(this.__typedSchema);for(let r in i)t.setValue(r,i[r]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(r=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(r,()=>{this.__notifyObservers(r,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,r){this.read(i).setValue(t,r)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(r=>{let s=this.read(r);i(s)&&t.push(r)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){v.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var pi=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:K,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var S=class extends E{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!1);u(this,"isCtxOwner",!1);u(this,"init$",kt(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",$(this._runValidators.bind(this),100));u(this,"_flushOutputItems",$(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(A.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));u(this,"_handleCollectonUpdate",(t,r,s)=>{var n;this._runValidators();for(let o of s)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()});u(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let r=this.uploadCollection,s=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>r.read(n)).filter(Boolean);for(let n of s)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=r.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=r.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,this.emit(A.UPLOAD_PROGRESS,l,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=r.findItems(l=>!!l.getValue("fileInfo")),o=r.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(r.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&this.emit(A.UPLOAD_FINISH,l,{debounce:!0})}}t.uploadError&&r.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(A.UPLOAD_ERROR,r.readProp(o,"uploadError"))}),t.validationErrorMsg&&r.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(A.VALIDATION_ERROR,r.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&r.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(A.CLOUD_MODIFICATION,r.readProp(o,"cdnUrlModifiers"))})})}setUploadMetadata(t){gt("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof S?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new Xt({typedSchema:pi,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,r;(t=this._unobserveCollectionProperties)==null||t.call(this),(r=this._unobserveCollection)==null||r.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:s!=null?s:null,silentUpload:r!=null?r:!1,source:n!=null?n:rt.API})}addFileFromUuid(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({uuid:t,fileName:s!=null?s:null,silentUpload:r!=null?r:!1,source:n!=null?n:rt.API})}addFileFromObject(t,{silent:r,fileName:s,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:Ae(t),mimeType:t.type,fileName:s!=null?s:t.name,fileSize:t.size,silentUpload:r!=null?r:!1,source:n!=null?n:rt.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(r=>{this.uploadCollection.add({file:r,isImage:Ae(r),mimeType:r.type,fileName:r.name,fileSize:r.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var s;let r=yt(Ee([(s=this.cfg.accept)!=null?s:"",...this.cfg.imgOnly?Ct:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=yt(Ct)):this.fileInput.accept=r,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:rt.LOCAL})),this.$["*currentActivity"]=E.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=ft(this.cfg.sourceList)),t}initFlow(t=!1){var r;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":E.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let s=this.sourceList[0];s==="local"?(this.$["*currentActivity"]=E.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(S.extSrcList).includes(s)?this.set$({"*currentActivityParams":{externalSourceType:s},"*currentActivity":E.activities.EXTERNAL}):this.$["*currentActivity"]=s,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":E.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(A.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(A.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let r=this.cfg.imgOnly,s=this.cfg.accept,n=Ee([...r?Ct:[],s]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Te(o,n),c=hi(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let r=this.cfg.maxLocalFileSizeBytes,s=t.getValue("fileSize");if(r&&s&&s>r)return this.l10n("files-max-size-limit-error",{maxFileSize:di(r)})}_validateMultipleLimit(t){let r=this.uploadCollection.items(),s=r.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let r=this.cfg.imgOnly,s=t.getValue("isImage");if(!(!r||s)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let r of this._validators){let s=r(t);if(s){t.setValue("validationErrorMsg",s);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let r=this.uploadCollection.read(t);r&&this._runValidatorsForEntry(r)})}setInitialCrop(){let t=ri(this.cfg.cropPreset);if(t){let[r]=t,s=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of s){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=r.width/r.height,h=ii(l,a,c),d=Vt(`crop/${h.width}x${h.height}/${h.x},${h.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:zt(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===E.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=E.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var s;let r=(s=this.cfg.metadata)!=null?s:this.$["*uploadMetadata"];if(typeof r=="function"){let n=this.getOutputItem(t);return await r(n)}return r}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:oi,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,l;let r=v.getCtx(t).store,s=r.fileInfo||{name:r.fileName,originalFilename:r.fileName,size:r.fileSize,isImage:r.isImage,mimeType:r.mimeType};return{...s,file:r.file,externalUrl:r.externalUrl,cdnUrlModifiers:r.cdnUrlModifiers,cdnUrl:(l=(o=r.cdnUrl)!=null?o:s.cdnUrl)!=null?l:null,validationErrorMessage:r.validationErrorMsg,uploadError:r.uploadError,isUploaded:!!r.uuid&&!!r.fileInfo,isValid:!r.validationErrorMsg&&!r.uploadError,fullPath:r.fullPath,uploadProgress:r.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};S.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});S.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...S.extSrcList});var X={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};var ao=ve("format/auto","progressive/yes");var we=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),mi=[we.CROP,we.TUNING,we.FILTERS];var ho=Object.freeze({brightness:{zero:X.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:X.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:X.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:X.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:X.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:X.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:X.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:X.enhance,range:[0,100],keypointsNumber:1},filter:{zero:X.filter,range:[0,100],keypointsNumber:1}});var Yr="https://ucarecdn.com",Jr="https://upload.uploadcare.com",Zr="https://social.uploadcare.com",st={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:yt(mi),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Yr,baseUrl:Jr,socialBaseUrl:Zr,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var D=e=>String(e),B=e=>{let i=Number(e);if(Number.isNaN(i))throw new Error(`Invalid number: "${e}"`);return i},x=e=>{if(typeof e=="undefined"||e===null)return!1;if(typeof e=="boolean")return e;if(e==="true"||e==="")return!0;if(e==="false")return!1;throw new Error(`Invalid boolean: "${e}"`)},Qr=e=>e==="auto"?e:x(e),ts={pubkey:D,multiple:x,multipleMin:B,multipleMax:B,confirmUpload:x,imgOnly:x,accept:D,externalSourcesPreferredTypes:D,store:Qr,cameraMirror:x,sourceList:D,maxLocalFileSizeBytes:B,thumbSize:B,showEmptyList:x,useLocalImageEditor:x,useCloudImageEditor:x,cloudImageEditorTabs:D,removeCopyright:x,cropPreset:D,modalScrollLock:x,modalBackdropStrokes:x,sourceListWrap:x,remoteTabSessionKey:D,cdnCname:D,baseUrl:D,socialBaseUrl:D,secureSignature:D,secureExpire:D,secureDeliveryProxy:D,retryThrottledRequestMaxTimes:B,multipartMinFileSize:B,multipartChunkSize:B,maxConcurrentRequests:B,multipartMaxConcurrentRequests:B,multipartMaxAttempts:B,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:x,groupOutput:x,userAgentIntegration:D},_i=(e,i)=>{if(!(typeof i=="undefined"||i===null))try{return ts[e](i)}catch(t){return console.error(`Invalid value for config key "${e}".`,t),st[e]}};function es(e){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let r=s=>{s.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=r,t.onprogress=r,t.readAsDataURL(e)}catch{i(!1)}})}function is(e,i){return new Promise(t=>{let r=0,s=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(r++,l.file(a=>{r--;let c=new File([a],a.name,{type:a.type||i});s.push({type:"file",file:c,fullPath:l.fullPath}),r===0&&t(s)})):l.isDirectory&&o(l.createReader())},o=l=>{r++,l.readEntries(a=>{r--;for(let c of a)n(c);r===0&&t(s)})};n(e)})}function gi(e){let i=[],t=[];for(let r=0;r{a&&i.push(...a)}));continue}let o=s.getAsFile();o&&t.push(es(o).then(l=>{l||i.push({type:"file",file:o})}))}else s.kind==="string"&&s.type.match("^text/uri-list")&&t.push(new Promise(n=>{s.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var R={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},bi=["focus"],rs=100,xe=new Map;function ss(e,i){let t=Math.max(Math.min(e[0],i.x+i.width),i.x),r=Math.max(Math.min(e[1],i.y+i.height),i.y);return Math.sqrt((e[0]-t)*(e[0]-t)+(e[1]-r)*(e[1]-r))}function Se(e){let i=0,t=document.body,r=new Set,s=p=>r.add(p),n=R.INACTIVE,o=p=>{e.shouldIgnore()&&p!==R.INACTIVE||(n!==p&&r.forEach(C=>C(p)),n=p)},l=()=>i>0;s(p=>e.onChange(p));let a=()=>{i=0,o(R.INACTIVE)},c=()=>{i+=1,n===R.INACTIVE&&o(R.ACTIVE)},h=()=>{i-=1,l()||o(R.INACTIVE)},d=p=>{p.preventDefault(),i=0,o(R.INACTIVE)},f=p=>{if(e.shouldIgnore())return;l()||(i+=1);let C=[p.x,p.y],w=e.element.getBoundingClientRect(),T=Math.floor(ss(C,w)),b=T{if(e.shouldIgnore())return;p.preventDefault();let C=await gi(p.dataTransfer);e.onItems(C),o(R.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",h),t.addEventListener("dragenter",c),t.addEventListener("dragover",f),e.element.addEventListener("drop",m),bi.forEach(p=>{window.addEventListener(p,a)}),()=>{xe.delete(e.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",h),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",f),e.element.removeEventListener("drop",m),bi.forEach(p=>{window.removeEventListener(p,a)})}}var yi="lr-drop-area",pt=`${yi}/registry`,Et=class extends S{constructor(){super(),this.init$={...this.init$,state:R.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[pt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,r=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),s=window.getComputedStyle(this),n=s.visibility!=="hidden"&&s.display!=="none";return t&&n&&r}initCallback(){super.initCallback(),this.$[pt]||(this.$[pt]=new Set),this.$[pt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!x(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:x(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:x(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:x(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Se({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(r=>{r.type==="url"?this.addFileFromUrl(r.url,{source:rt.DROP_AREA}):r.type==="file"&&this.addFileFromObject(r.file,{source:rt.DROP_AREA,fullPath:r.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":E.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Se({element:i,onChange:t=>{var s;let r=(s=Object.entries(R).find(([,n])=>n===t))==null?void 0:s[0].toLowerCase();r&&i.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var s;let r=(s=Object.entries(R).find(([,n])=>n===t))==null?void 0:s[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",t=>{let r=ft(t);this.$.isEnabled=r.includes(S.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[pt]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,r=this.uploadCollection.size;return!(i&&t&&r>=t||!i&&r>0)}destroyCallback(){var t,r;super.destroyCallback();let i=this.$[pt];i&&(i.delete(this),i.size===0&&v.deleteCtx(yi)),(t=this._destroyDropzone)==null||t.call(this),(r=this._destroyContentWrapperDropzone)==null||r.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};Et.template=` {{text}} `;Et.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Bt=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}},Ht=class extends O{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Ht.template=` {{msgTxt}}`;var Wt=class extends S{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",E.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",$(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(r=>!!r.getValue("fileInfo"));this.emit(A.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var h,d;let t=!!this.cfg.multiple,r=t?(h=this.cfg.multipleMin)!=null?h:0:1,s=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=r?ns:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:r,max:s,exact:s===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,r=this._validateFilesCount();if(t&&!r.passed){let s=new Bt,n=r.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";s.caption=this.l10n("files-count-limit-error-title"),s.text=this.l10n(n,{min:r.min,max:r.max,total:t}),s.isError=!0,this.set$({"*message":s})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),s={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let p=this.uploadCollection.read(m);p.getValue("fileInfo")&&!p.getValue("validationErrorMsg")&&(s.succeed+=1),p.getValue("isUploading")&&(s.uploading+=1),(p.getValue("validationErrorMsg")||p.getValue("uploadError"))&&(s.failed+=1),p.getValue("validationMultipleLimitMsg")&&(s.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=s.failed===0&&s.limitOverflow===0,c=!1,h=!1,d=!1;s.total-s.succeed-s.uploading-s.failed>0&&n?c=!0:(h=!0,d=s.total===s.succeed&&n&&a),this.set$({doneBtnVisible:h,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:s.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(s)})}_getHeaderText(t){let r=s=>{let n=t[s];return this.l10n(`header-${s}`,{count:n})};return t.uploading>0?r("uploading"):t.failed>0?r("failed"):t.succeed>0?r("succeed"):r("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};Wt.template=`{{headerText}} `;function ns(e){let i=new Blob([e],{type:"image/svg+xml"});return URL.createObjectURL(i)}function Oe(e="hsl(209, 21%, 65%)",i=32,t=32){return ns(``)}function Ci(e,i=40){if(e.type==="image/svg+xml")return URL.createObjectURL(e);let t=document.createElement("canvas"),r=t.getContext("2d"),s=new Image,n=new Promise((o,l)=>{s.onload=()=>{let a=s.height/s.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),r.fillStyle="rgb(240, 240, 240)",r.fillRect(0,0,t.width,t.height),r.drawImage(s,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let h=URL.createObjectURL(c);o(h)})},s.onerror=a=>{l(a)}});return s.src=URL.createObjectURL(e),n}var L=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),J=class extends S{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",$(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",$(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:L.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===E.activities.DETAILS)?this.$["*currentActivity"]=E.activities.DETAILS:this.$["*currentActivity"]=E.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let r=this.getOutputData(s=>s.getValue("uuid")===t);this.emit(A.REMOVE,r,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[r]=t;this._isIntersecting=r.isIntersecting,r.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),r.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,r=L.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?r=L.FAILED:t.getValue("validationMultipleLimitMsg")?r=L.LIMIT_OVERFLOW:t.getValue("isUploading")?r=L.UPLOADING:t.getValue("fileInfo")&&(r=L.FINISHED),this.$.state=r}async _generateThumbnail(){var r;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let s=this.cfg.thumbSize,n=this.proxyUrl(zt(ci(this.cfg.cdnCname,this._entry.getValue("uuid")),Vt(t.getValue("cdnUrlModifiers"),`scale_crop/${s}x${s}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((r=t.getValue("file"))!=null&&r.type.includes("image"))try{let s=await Ci(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",s)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Oe(n))}else{let s=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Oe(s))}}_subEntry(t,r){let s=this._entry.subscribe(t,n=>{this.isConnected&&r(n)});this._entrySubs.add(s)}_handleEntryId(t){var s;this._reset();let r=(s=this.uploadCollection)==null?void 0:s.read(t);this._entry=r,r&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||r.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=r.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{J.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),J.activeInstances.add(this)}_handleState(t){var r,s,n;this.set$({isFailed:t===L.FAILED,isLimitOverflow:t===L.LIMIT_OVERFLOW,isUploading:t===L.UPLOADING,isFinished:t===L.FINISHED,progressVisible:t===L.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((r=this._entry)==null?void 0:r.getValue("isImage"))&&((s=this._entry)==null?void 0:s.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===L.FAILED||t===L.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===L.FINISHED&&(this.$.badgeIcon="badge-success"),t===L.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),J.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let r=this.cfg.multiple?this.cfg.multipleMax:1;if(r&&this.uploadCollection.size>r)return;let s=this.getOutputData(a=>!a.getValue("fileInfo"));this.emit(A.UPLOAD_START,s,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=this.getUploadClientOptions();return ge(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let m=f.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!f.isComputable},signal:a.signal,metadata:await this.getMetadataFor(t.uid)})},h=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:h,isUploading:!1,fileName:h.originalFilename,fileSize:h.size,isImage:h.isImage,mimeType:(l=(o=(n=h.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:h.mimeType,uuid:h.uuid,cdnUrl:h.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof U?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};J.template=` {{itemName}}{{errorText}} `;J.activeInstances=new Set;var Tt=class extends O{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let r=this.getCssData(`--icon-${t}`);r&&(this.$.path=r)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};Tt.template=``;Tt.bindAttributes({name:"name",size:"size"});var Gt=class extends O{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};Gt.template='';var qt=class extends O{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};u(qt,"template",`Powered by Uploadcare`);var Kt=class extends S{constructor(){super();u(this,"processInnerHtml",!0);u(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return vi.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,Me(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var r,s;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(l=>l.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,a.value=l!=null?l:"",this._dynamicInputsContainer.appendChild(a)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let l=o.find(d=>!d.isValid),a=(s=l==null?void 0:l.validationErrorMessage)!=null?s:(r=l==null?void 0:l.uploadError)==null?void 0:r.message,c=this.$["*message"];c=c!=null&&c.isError?`${c.caption}. ${c.text}`:void 0;let h=a!=null?a:c;h?this._validationInputElement.setCustomValidity(h):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(l=>l.isUploaded&&l.isValid)){this.$.output={groupData:void 0,files:t};return}let s=this.getUploadClientOptions(),n=t.map(l=>l.uuid+(l.cdnUrlModifiers?`/${l.cdnUrlModifiers}`:"")),o=await Qe(n,s);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};Kt.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var vi=Kt;var Yt=Object.keys(st),os=["metadata"],ls=e=>os.includes(e),Jt=Yt.filter(e=>!ls(e)),as={...Object.fromEntries(Jt.map(e=>[Q(e),e])),...Object.fromEntries(Jt.map(e=>[e.toLowerCase(),e]))},us={...Object.fromEntries(Yt.map(e=>[Q(e),N(e)])),...Object.fromEntries(Yt.map(e=>[e.toLowerCase(),N(e)]))},Zt=class extends O{constructor(){super();u(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(st).map(([t,r])=>[N(t),r]))}}initCallback(){super.initCallback();let t=this;for(let r of Jt)this.sub(N(r),s=>{s!==st[r]&&(t[r]=s)},!1);for(let r of Yt){let s="__"+r;t[s]=t[r],Object.defineProperty(this,r,{set:n=>{if(t[s]=n,Jt.includes(r)){let o=[...new Set([Q(r),r.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[N(r)]!==n&&(typeof n=="undefined"||n===null?this.$[N(r)]=st[r]:this.$[N(r)]=n)},get:()=>this.$[N(r)]}),typeof t[r]!="undefined"&&t[r]!==null&&(t[r]=t[s])}}attributeChangedCallback(t,r,s){if(r===s)return;let n=as[t],o=_i(n,s),l=o!=null?o:st[n],a=this;a[n]=l}};Zt.bindAttributes(us);var cs=Zt;var Ie=class extends S{constructor(){super(...arguments);u(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},hs=Ie;export{cs as Config,qt as Copyright,vi as DataOutput,Et as DropArea,J as FileItem,$t as FileUploaderMinimal,Tt as Icon,Ht as MessageBox,Gt as ProgressBar,Ft as StartFrom,hs as UploadCtxProvider,Wt as UploadList,wi as registerBlocks};
\ No newline at end of file
diff --git a/web/lr-file-uploader-regular.min.js b/web/lr-file-uploader-regular.min.js
index d89b21f23..092fa7930 100644
--- a/web/lr-file-uploader-regular.min.js
+++ b/web/lr-file-uploader-regular.min.js
@@ -24,4 +24,4 @@
*
*/
var Lr=Object.defineProperty;var Ur=(s,i,t)=>i in s?Lr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Ur(s,typeof i!="symbol"?i+"":i,t),t);var Rr=Object.defineProperty,Pr=(s,i,t)=>i in s?Rr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,yi=(s,i,t)=>(Pr(s,typeof i!="symbol"?i+"":i,t),t);function Mr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Mr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.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"}),ss="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Nr=ss.length-1,Zt=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Fr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var es="__default__";function Br(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||es;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=es;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function Vr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function zr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Dr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):rs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var we="{{",Yt="}}",jr="skip-text";function Hr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(jr))&&r.textContent.includes(we)&&r.textContent.includes(Yt)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Wr=function(s,i){Hr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(Yt);)e.textContent.startsWith(we)?(n=e.textContent.indexOf(Yt)+Yt.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(we),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(we,"").replace(Yt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Xr=[Fr,Br,Vr,zr,Wr],Te="'",Nt='"',qr=/\\([0-9a-fA-F]{1,6} ?)/g;function Gr(s){return(s[0]===Nt||s[0]===Te)&&(s[s.length-1]===Nt||s[s.length-1]===Te)}function Kr(s){return(s[0]===Nt||s[0]===Te)&&(s=s.slice(1)),(s[s.length-1]===Nt||s[s.length-1]===Te)&&(s=s.slice(0,-1)),s}function Yr(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\
-`,"\\n"),i=Yr(i),i=Nt+i+Nt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var is=0,Mt=null,ht=null,_t=class extends HTMLElement{constructor(){super(),yi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 _t}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Zt.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 s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=_t.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=_t.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=_t.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=_t.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=_t.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=_t.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])rs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Xr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ht==null||ht.delete(this.updateCssData),ht!=null&&ht.size||(Mt==null||Mt.disconnect(),Mt=null,ht=null)},100)))}static reg(s,i=!1){s||(is++,s=`${C.AUTO_TAG_PRFX}-${is}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" 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(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Zr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){ht||(ht=new Set),ht.add(this.updateCssData),Mt||(Mt=new MutationObserver(s=>{s[0].type==="attributes"&&ht.forEach(i=>{i()})}),Mt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},Dt=_t;yi(Dt,"template");var _i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(_i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),_i.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}};_i.appMap=Object.create(null);function vi(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function Jr(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function Jt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&Jr(i,s.attributes),s.styles&&vi(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Jt(t);i.appendChild(e)}),i}var ns="idb-store-ready",Qr="symbiote-db",tn="symbiote-idb-update_",en=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ns,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return tn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,os.clear(this.name)}},os=class{static get readyEventName(){return ns}static open(s=Qr,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new en(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};yi(os,"_reg",Object.create(null));var S=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),sn=Object.freeze({[S.UPLOAD_START]:"LR_UPLOAD_START",[S.REMOVE]:"LR_REMOVE",[S.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[S.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[S.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[S.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[S.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[S.DATA_OUTPUT]:"LR_DATA_OUTPUT",[S.DONE_FLOW]:"LR_DONE_FLOW",[S.INIT_FLOW]:"LR_INIT_FLOW"}),xe=class{constructor(i){h(this,"_timeoutStore",new Map);h(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));let e=sn[i];window.dispatchEvent(new CustomEvent(e,{detail:{ctx:this._getCtxName(),type:e,data:t}}))}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};function I(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var ls="--uploadcare-blocks-window-height",It=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(ls)}};h(It,"clientsRegistry",new Set),h(It,"flush",I(()=>{document.documentElement.style.setProperty(ls,`${window.innerHeight}px`)},100));var Ee=(s,i)=>new Intl.PluralRules(s).select(i);var rn=s=>s,Ci="{{",cs="}}",as="plural:";function Qt(s,i,t={}){var o;let{openToken:e=Ci,closeToken:r=cs,transform:n=rn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function hs(s){let i=[],t=s.indexOf(Ci);for(;t!==-1;){let e=s.indexOf(cs,t),r=s.substring(t+2,e);if(r.startsWith(as)){let n=s.substring(t+2,e).replace(as,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ci,e)}return i}var ut=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ae=({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=setTimeout(()=>{a.disconnect(),e()},r),o=c=>{let u=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&u!==null&&(clearTimeout(n),a.disconnect(),t(u))},l=s.getAttribute(i);l!==null&&(clearTimeout(n),t(l));let a=new MutationObserver(c=>{let u=c[c.length-1];o(u)});a.observe(s,{attributes:!0,attributeFilter:[i]})};var us=new Set;function te(s){us.has(s)||(us.add(s),console.warn(s))}function ds(s){return Object.prototype.toString.call(s)==="[object Object]"}var nn=/\W|_/g;function on(s){return s.split(nn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ps(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>ft(t,{ignoreKeys:i})):s}function ft(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ps(s,{ignoreKeys:i});if(!ds(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ds(r)?r=ft(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ps(r,{ignoreKeys:i})),t[on(e)]=r}return t}var ln=s=>new Promise(i=>setTimeout(i,s));function Si({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var an={factor:2,time:100};function cn(s,i=an){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>ln(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Ft=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Ft.prototype),this.originalProgressEvent=t}},Se=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},yt=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,yt.prototype)}},hn=500,ms=({check:s,interval:i=hn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Se(e,()=>{o&&clearTimeout(o),n(new yt("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new yt("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),A={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"},Ie="application/octet-stream",gs="original",vt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Se(r,()=>{u=!0,a.abort(),l(new yt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let x=$.split(": "),T=x.shift(),w=x.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,b=a.status;o({request:d,data:f,headers:m,status:b})}},a.onerror=d=>{u||l(new Ft(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function un(s,...i){return s}var dn=({name:s})=>s?[s]:[],pn=un,fn=()=>new FormData,bs=s=>!1,ke=s=>typeof Blob!="undefined"&&s instanceof Blob,Oe=s=>typeof File!="undefined"&&s instanceof File,Le=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Bt=s=>ke(s)||Oe(s)||bs()||Le(s),mn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",gn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),bn=s=>!!s&&typeof s=="object"&&"data"in s&&Bt(s.data);function _n(s,i,t){if(bn(t)){let{name:e,contentType:r}=t,n=pn(t.data,e,r!=null?r:Ie),o=dn({name:e,contentType:r});s.push([i,n,...o])}else if(gn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else mn(t)&&t&&s.push([i,t.toString()])}function yn(s){let i=[];for(let[t,e]of Object.entries(s))_n(i,t,e);return i}function Ii(s){let i=fn(),t=yn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},vn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},dt=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=vn(t)),e.toString()},Cn="6.8.0",wn="UploadcareUploadClient",Tn=Cn;function kt(s){return Si({libraryName:wn,libraryVersion:Tn,...s})}var xn="RequestThrottledError",fs=15e3,En=1e3;function An(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return fs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:fs}function Ct(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return cn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===xn&&r{let i="";return(ke(s)||Oe(s)||Le(s))&&(i=s.type),i||Ie},ys=s=>{let i="";return Oe(s)&&s.name?i=s.name:ke(s)||bs()?i="":Le(s)&&s.name&&(i=s.name),i||gs};function ki(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function $n(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=A.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({file:{data:s,name:t||ys(s),contentType:e||_s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ki(l),signature:n,expire:o,source:u,metadata:b}),signal:a,onProgress:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var xi;(function(s){s.Token="token",s.FileInfo="file_info"})(xi||(xi={}));function Sn(s,{publicKey:i,baseURL:t=A.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},url:dt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:ki(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:b}),signal:u}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var j;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(j||(j={}));var In=s=>"status"in s&&s.status===j.Error;function kn(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=A.retryNetworkErrorMaxTimes}={}){return Ct(()=>vt({method:"GET",headers:i?{"X-UC-User-Agent":kt({publicKey:i,integration:r,userAgent:n})}:void 0,url:dt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=ft(JSON.parse(a));if("error"in d&&!In(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function On(s,{publicKey:i,baseURL:t=A.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:a,userAgent:c})},url:dt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let b=ft(JSON.parse(p));if("error"in b)throw new P(b.error.content,b.error.errorCode,f,b,m);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function vs(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"GET",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},url:dt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Ln(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=A.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({filename:e||gs,size:s,content_type:t||Ie,part_size:r,UPLOADCARE_STORE:ki(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:b}),signal:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w.parts=Object.keys(w.parts).map(V=>w.parts[V]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Un(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Ie}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Rn(s,{publicKey:i,baseURL:t=A.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",url:dt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},data:Ii({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Oi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return ms({check:u=>vs(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function Pn(s){return"defaultEffects"in s}var pt=class{constructor(i,{baseCDN:t=A.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);h(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=dt(t,`${r}/`),l=n?dt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,Pn(i)&&(this.defaultEffects=i.defaultEffects)}},Mn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:b,metadata:$})=>$n(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:x})=>Oi(x,{publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(x=>new pt(x,{baseCDN:b})),Nn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>vs(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new pt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Dn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Se(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Fn=window.WebSocket,Ei=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Bn=(s,i)=>s==="success"?{status:j.Success,...i}:s==="progress"?{status:j.Progress,...i}:{status:j.Error,...i},Ai=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ei);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Fn(i),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 e=JSON.parse(t.data.toString());switch(e.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(e.channel,Bn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},wi=null,Li=s=>{if(!wi){let i=typeof window=="undefined"?0:3e4;wi=new Ai(s,i)}return wi},Vn=s=>{Li(s).connect()};function zn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ms({check:c=>kn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case j.Error:return new P(u.error,u.errorCode);case j.Waiting:return!1;case j.Unknown:return new P(`Token "${s}" was not found.`);case j.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case j.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var jn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Li(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Se(t,()=>{a(),n(new yt("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case j.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case j.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case j.Error:a(),n(new P(c.msg,c.error_code))}})}),Hn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,pusherKey:$=A.pusherKey,metadata:x})=>Promise.resolve(Vn($)).then(()=>Sn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,metadata:x})).catch(T=>{let w=Li($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===xi.FileInfo?T:Dn([({signal:w})=>zn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:w}),({signal:w})=>jn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof P)throw T;return T}).then(T=>Oi(T.uuid,{publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:u})).then(T=>new pt(T,{baseCDN:r})),Ti=new WeakMap,Wn=async s=>{if(Ti.has(s))return Ti.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Ti.set(s,i),i},Cs=async s=>{if(Oe(s)||ke(s))return s.size;if(Le(s))return(await Wn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Xn=(s,i=A.multipartMinFileSize)=>s>=i,ws=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Bt(s)&&t.test(s)},Ui=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Bt(s)&&t.test(s)},qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},Kn=async(s,i,t)=>e=>Gn(s,e,i,t),Yn=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Un(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Zn=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:b,multipartChunkSize:$=A.multipartChunkSize,maxConcurrentRequests:x=A.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let V=e!=null?e:await Cs(s),at,St=(R,z)=>{if(!c)return;at||(at=Array(R).fill(0));let J=tt=>tt.reduce((ct,bi)=>ct+bi,0);return tt=>{tt.isComputable&&(at[z]=tt.value,c({isComputable:!0,value:J(at)/R}))}};return b||(b=_s(s)),Ln(V,{publicKey:i,contentType:b,fileName:t||ys(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:z})=>{let J=await Kn(s,V,$);return Promise.all([R,qn(x,z.map((tt,ct)=>()=>Yn(J(ct),tt,{publicKey:i,contentType:b,onProgress:St(z.length,ct),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Rn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Oi(R.uuid,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new pt(R,{baseCDN:T}))};async function Ri(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:b,multipartChunkSize:$,maxConcurrentRequests:x,baseCDN:T=A.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,pusherKey:at,metadata:St}){if(Bt(s)){let R=await Cs(s);return Xn(R,b)?Zn(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:x,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St}):Mn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St})}if(Ui(s))return Hn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:at,metadata:St});if(ws(s))return Nn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var $i=class{constructor(i,{baseCDN:t=A.baseCDN}={}){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new pt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Jn=s=>{for(let i of s)if(!Bt(i))return!1;return!0},Qn=s=>{for(let i of s)if(!ws(i))return!1;return!0},to=s=>{for(let i of s)if(!Ui(i))return!1;return!0};function Ts(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b=A.multipartChunkSize,baseCDN:$=A.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!Jn(s)&&!to(s)&&!Qn(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let V,at=!0,St=s.length,R=(z,J)=>{if(!a)return;V||(V=Array(z).fill(0));let tt=ct=>ct.reduce((bi,Or)=>bi+Or)/z;return ct=>{if(!ct.isComputable||!at){at=!1,a({isComputable:!1});return}V[J]=ct.value,a({isComputable:!0,value:tt(V)})}};return Promise.all(s.map((z,J)=>Bt(z)||Ui(z)?Ri(z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(St,J),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b,baseCDN:$,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T}).then(tt=>tt.uuid):z)).then(z=>On(z,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(J=>new $i(J,{baseCDN:$})).then(J=>(a&&a({isComputable:!0,value:1}),J)))}var $e=class{constructor(i){h(this,"_concurrency",1);h(this,"_pending",[]);h(this,"_running",0);h(this,"_resolvers",new Map);h(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var Pi=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),Mi=s=>({...Pi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Ue=s=>({...Mi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $e(1),"*uploadCollection":null});function xs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var H=s=>`*cfg/${s}`;var Ni="lr-",_=class extends Dt{constructor(){super();h(this,"requireCtxName",!1);h(this,"allowCustomTemplate",!0);h(this,"init$",Pi());h(this,"updateCtxCssData",()=>{te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(xs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=hs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Qt(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Ee(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ni}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ae({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),It.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),It.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new xe(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Qt(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=H(r);return this.$[o]=n,!0},get:(e,r)=>{let n=H(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ut(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(H(t));r.ctx.has(r.name)?this.sub(H(t),e):(this.bindCssData(`--cfg-${ut(t)}`),this.sub(`--cfg-${ut(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ni)?t:Ni+t)}};h(_,"StateConsumerScope",null),h(_,"className","");var Es="active",ee="___ACTIVITY_IS_ACTIVE___",et=class extends _{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Mi(this));h(this,"_debouncedHistoryFlush",I(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=et._activityRegistry[this.activityKey];this[ee]=!1,this.removeAttribute(Es),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=et._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ee]=!0,this.setAttribute(Es,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ee]?this._deactivate():this.activityType===t&&!this[ee]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!et._activityRegistry[this.activityKey]}get isActivityActive(){return this[ee]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;et._activityRegistry||(et._activityRegistry=Object.create(null)),et._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),et._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(et._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===r);n=(e=l==null?void 0:l.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},g=et;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ie=33.333333333333336,y=1,Di=24,As=6;function Ot(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function Y(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Ot(t,i),t}function $s(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Ss(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Is(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function ks({rect:s,delta:[i,t],imageBox:e}){return zt({...s,x:s.x+i,y:s.y+t},e)}function zt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function eo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Rs(s,i){return Math.abs(s.width/s.height-i)<.1}function jt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ps(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Ht(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function wt(s,i,t){return Math.min(Math.max(s,i),t)}var Pe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var Z=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Ms=s=>s?s.split(",").map(i=>i.trim()):[],Lt=s=>s?s.join(","):"";var Ns="blocks",Ds="0.30.4";function Fs(s){return Si({...s,libraryName:Ns,libraryVersion:Ds})}var Bs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Me=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Bs(i)).join("/-/"),M=(...s)=>{let i=Me(...s);return i?`-/${i}/`:""};function Vs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function js(s){let i=Hs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Bs(n))}function Hs(s){let i=new URL(s),t=Vs(s),e=Ws(t)?Xs(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ws(s){return s.startsWith("http")}function Xs(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var O=(s,i,t)=>{let e=new URL(Hs(s));if(t=t||Vs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ws(t)){let r=Xs(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},Tt=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var se=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Fi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],Bi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),qs=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),re=s=>{let i=s==null?void 0:s.type;return i?Bi(i,se):!1};var st=1e3,Ut=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ne=s=>Math.ceil(s*100)/100,Gs=(s,i=Ut.AUTO)=>{let t=i===Ut.AUTO;if(i===Ut.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(co+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var De=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Zt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new Ne(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var Ys=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:pt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!1);h(this,"isCtxOwner",!1);h(this,"init$",Ue(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",I(this._runValidators.bind(this),100));h(this,"_flushOutputItems",I(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(S.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));h(this,"_handleCollectonUpdate",(t,e,r)=>{var n;this._runValidators();for(let o of r)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()});h(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,this.emit(S.UPLOAD_PROGRESS,l,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&this.emit(S.UPLOAD_FINISH,l,{debounce:!0})}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(S.UPLOAD_ERROR,e.readProp(o,"uploadError"))}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(S.VALIDATION_ERROR,e.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(S.CLOUD_MODIFICATION,e.readProp(o,"cdnUrlModifiers"))})})}setUploadMetadata(t){te("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof v?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new De({typedSchema:Ys,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:re(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:re(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Lt(Fi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?se:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Lt(se)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Z.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(S.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(S.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Fi([...e?se:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Bi(o,n),c=qs(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Gs(e)})}_validateMultipleLimit(t){let e=this.uploadCollection.items(),r=e.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&e.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Pe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ps(l,a,c),d=M(`crop/${u.width}x${u.height}/${u.x},${u.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:O(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,l;let e=E.getCtx(t).store,r=e.fileInfo||{name:e.fileName,originalFilename:e.fileName,size:e.fileSize,isImage:e.isImage,mimeType:e.mimeType};return{...r,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(l=(o=e.cdnUrl)!=null?o:r.cdnUrl)!=null?l:null,validationErrorMessage:e.validationErrorMsg,uploadError:e.uploadError,isUploaded:!!e.uuid&&!!e.fileInfo,isValid:!e.validationErrorMsg&&!e.uploadError,fullPath:e.fullPath,uploadProgress:e.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});var G={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function ho(s,i){if(typeof i=="number")return G[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&G[s]!==i?`${s}`:"";if(s==="filter"){if(!i||G[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Js=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function xt(s){return Me(...Js.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return ho(i,t)}).filter(i=>!!i))}var Fe=Me("format/auto","progressive/yes"),mt=([s])=>typeof s!="undefined"?Number(s):void 0,Zs=()=>!0,uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),po=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),fo={enhance:mt,brightness:mt,exposure:mt,gamma:mt,contrast:mt,saturation:mt,vibrance:mt,warmth:mt,filter:uo,mirror:Zs,flip:Zs,rotate:mt,crop:po};function Qs(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Js.includes(e))continue;let n=fo[e],o=n(r);i[e]=o}return i}var L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),W=[L.CROP,L.TUNING,L.FILTERS],tr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],er=["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"],ir=["rotate","mirror","flip"],rt=Object.freeze({brightness:{zero:G.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:G.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:G.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:G.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:G.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:G.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:G.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:G.enhance,range:[0,100],keypointsNumber:1},filter:{zero:G.filter,range:[0,100],keypointsNumber:1}});var mo="https://ucarecdn.com",go="https://upload.uploadcare.com",bo="https://social.uploadcare.com",Et={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Lt(W),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:mo,baseUrl:go,socialBaseUrl:bo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var X=s=>String(s),nt=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},k=s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},_o=s=>s==="auto"?s:k(s),yo={pubkey:X,multiple:k,multipleMin:nt,multipleMax:nt,confirmUpload:k,imgOnly:k,accept:X,externalSourcesPreferredTypes:X,store:_o,cameraMirror:k,sourceList:X,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:X,removeCopyright:k,cropPreset:X,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:X,cdnCname:X,baseUrl:X,socialBaseUrl:X,secureSignature:X,secureExpire:X,secureDeliveryProxy:X,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:X},sr=(s,i)=>{if(!(typeof i=="undefined"||i===null))try{return yo[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),Et[s]}};var Be=Object.keys(Et),vo=["metadata"],Co=s=>vo.includes(s),Ve=Be.filter(s=>!Co(s)),wo={...Object.fromEntries(Ve.map(s=>[ut(s),s])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),s]))},To={...Object.fromEntries(Be.map(s=>[ut(s),H(s)])),...Object.fromEntries(Be.map(s=>[s.toLowerCase(),H(s)]))},ze=class extends _{constructor(){super();h(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Et).map(([t,e])=>[H(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of Ve)this.sub(H(e),r=>{r!==Et[e]&&(t[e]=r)},!1);for(let e of Be){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,Ve.includes(e)){let o=[...new Set([ut(e),e.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[H(e)]!==n&&(typeof n=="undefined"||n===null?this.$[H(e)]=Et[e]:this.$[H(e)]=n)},get:()=>this.$[H(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=wo[t],o=sr(n,r),l=o!=null?o:Et[n],a=this;a[n]=l}};ze.bindAttributes(To);var xo=ze;var oe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};oe.template=``;oe.bindAttributes({name:"name",size:"size"});var Eo="https://ucarecdn.com",Rt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Eo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var rr=s=>[...new Set(s)];var le="--lr-img-",nr="unresolved",Wt=2,Xt=3,or=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ar=Object.create(null),lr;for(let s in Rt)ar[le+s]=((lr=Rt[s])==null?void 0:lr.default)||"";var je=class extends Dt{constructor(){super(...arguments);h(this,"cssInit$",ar)}$$(t){return this.$[le+t]}set$$(t){for(let e in t)this.$[le+e]=t[e]}sub$$(t,e){this.sub(le+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!or&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return M(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Rt.format.default}`,`quality/${this.$$("quality")||Rt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(or&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Qt(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(nr,""),this.img.onload=()=>{this.img.removeAttribute(nr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Rt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?rr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Wt+"x")}") ${n*Wt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Xt+"x")}") ${n*Xt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Wt))}") ${Wt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Xt))}") ${Xt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Wt+"x")+` ${e*Wt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Xt+"x")+` ${e*Xt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(Rt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[le+t]=r})}};var Vi=class extends je{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var ae=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=k(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};ae.template=` `;ae.bindAttributes({dropzone:null});var He=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};He.template=' ';function Ao(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function $o(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function cr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Ao(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var F={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},hr=["focus"],So=100,zi=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function ji(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=F.INACTIVE,o=f=>{s.shouldIgnore()&&f!==F.INACTIVE||(n!==f&&e.forEach(b=>b(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(F.INACTIVE)},c=()=>{i+=1,n===F.INACTIVE&&o(F.ACTIVE)},u=()=>{i-=1,l()||o(F.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(F.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let b=[f.x,f.y],$=s.element.getBoundingClientRect(),x=Math.floor(Io(b,$)),T=x{if(s.shouldIgnore())return;f.preventDefault();let b=await cr(f.dataTransfer);s.onItems(b),o(F.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),hr.forEach(f=>{window.addEventListener(f,a)}),()=>{zi.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),hr.forEach(f=>{window.removeEventListener(f,a)})}}var ur="lr-drop-area",qt=`${ur}/registry`,ce=class extends v{constructor(){super(),this.init$={...this.init$,state:F.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[qt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[qt]||(this.$[qt]=new Set),this.$[qt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=ji({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Z.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Z.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=ji({element:i,onChange:t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[qt]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[qt];i&&(i.delete(this),i.size===0&&E.deleteCtx(ur)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ce.template=` {{text}} `;ce.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var ko="src-type-",he=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${ko}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};he.template=` `;he.bindAttributes({type:null});var Hi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=` `}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function dr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function pr(s="#fff",i="rgba(0, 0, 0, .1)"){return dr(``)}function ue(s="hsl(209, 21%, 65%)",i=32,t=32){return dr(``)}function fr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),gt=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",I(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",I(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);this.emit(S.REMOVE,e,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(Tt(this.cfg.cdnCname,this._entry.getValue("uuid")),M(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await fr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{gt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),gt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),gt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));this.emit(S.UPLOAD_START,r,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=this.getUploadClientOptions();return Ri(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal,metadata:await this.getMetadataFor(t.uid)})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};gt.template=` {{itemName}}{{errorText}} `;gt.activeInstances=new Set;var de=class extends _{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogMouseDown",t=>{this._mouseDownTarget=t.target});h(this,"_handleDialogMouseUp",t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};h(de,"StateConsumerScope","modal");de.template=``;var We=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Xe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Xe.template=` {{msgTxt}}`;var qe=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",I(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));this.emit(S.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new We,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};qe.template=`{{headerText}} `;var Ge=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Z.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ge.template=` `;var Wi=()=>typeof navigator.permissions!="undefined";var Ke=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Wi(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{Wi()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",I(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Z.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ke.template=` `;var Xi=class extends v{constructor(){super(...arguments);h(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},Oo=Xi;var Ye=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ue(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=re(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=O(n,M("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};Ye.template=` `;var qi=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Ze=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new qi);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Ze.template=`{{activityCaption}} `;var Je=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};Je.template=` `;var Qe=class extends _{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};Qe.template='';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var pe=class extends _{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${pr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};pe.template=' ';pe.bindAttributes({checkerboard:"checkerboard"});var mr="--cfg-ctx-name",U=class extends _{get cfgCssCtxName(){return this.getCssData(mr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(mr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function gr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function D(...s){let i=gr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function br(s,...i){let t=gr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var _r=s=>{if(!s)return W;let i=Ms(s).filter(t=>W.includes(t));return i.length===0?W:i};function yr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":W,"*tabId":L.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Lt(W),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=M(xt(i),"preview"),r=O(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var vr=` Network error `;var ot=class extends U{constructor(){super();h(this,"_debouncedShowLoader",I(this._showLoader.bind(this),300));this.init$={...this.init$,...yr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$["*tabId"]===L.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=zs(this.$.cdnUrl);this.$["*originalUrl"]=Tt(this.$.cdnUrl,t);let e=js(this.$.cdnUrl),r=Qs(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=Tt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=O(this.$["*originalUrl"],M("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===L.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Pe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=_r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=D("image",{image_hidden_to_cropper:t===L.CROP,image_hidden_effects:t!==L.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=M(xt(t),"preview"),n=O(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(ot,"className","cloud-image-editor");ot.template=vr;ot.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ti=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=Y("mask",{id:"backdrop-mask"}),a=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=Y("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Ot(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Ot(n,f)}else{let f=wt(Math.min(d,p)/(24*2+34)/2,0,1),{d:b,center:$}=a?$s(i,e,f):Ss(i,e,f),x=Math.max(Di*wt(Math.min(d,p)/Di/3,0,1),As);Ot(n,{x:$[0]-x,y:$[1]-x,width:x*2,height:x*2}),Ot(r,{d:b})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",D("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ot(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=Y("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=Y("rect",{fill:"transparent"}),l=Y("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=Y("svg"),t=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=Y("line",{x1:`${ie*e}%`,y1:"0%",x2:`${ie*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=Y("line",{x1:"0%",y1:`${ie*e}%`,x2:"100%",y2:`${ie*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=ks({rect:o,delta:[e,r],imageBox:n}):o=Os({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return zt(Ht(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Ls(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Is(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",D("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",D({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ti.template='';var bt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=D({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};bt.template=` {{title}}`;function Uo(s){let i=s+90;return i=i>=360?0:i,i}function Ro(s,i){return s==="rotate"?Uo(i):["mirror","flip"].includes(s)?!i:null}var fe=class extends bt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Ro(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var me={FILTER:"filter",COLOR_OPERATION:"color_operation"},lt="original",ei=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?me.FILTER:me.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===lt?void 0:this.$.value,filter:this._filter===lt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=rt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===me.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===me.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===me.FILTER?this._filter===lt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ei.template=` `;function ge(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function be(s){let i=[];for(let n of s){let o=ge(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Gt=class extends bt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==lt?{name:this._filter,amount:o}:void 0,O(this._originalUrl,M(Fe,xt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ge(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===lt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Gt.template=` `;var _e=class extends bt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=rt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Cr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function wr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Kt(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,M(Fe,xt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Po(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ii=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=I(this._commit.bind(this),300),this._handleResizeThrottled=Cr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=wr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=jt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Ht(l)}_alignCrop(){var d;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[p,m],coords:[f,b]}=n,{width:$}=jt(this._imageSize,r),x=o/$;i=zt(Ht({x:l+f*x,y:a+b*x,width:p*x,height:m*x}),this.$["*imageBox"])}let c=(d=this.$["*cropPresetList"])==null?void 0:d[0],u=c?c.width/c.height:void 0;if(!Us(i,t)||u&&!Rs(i,u)){let p=t.width/t.height,m=t.width,f=t.height;u&&(p>u?m=Math.min(t.height*u,t.width):f=Math.min(t.width/u,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=zt(Ht(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=jt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=D({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=jt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[wt(Math.round(c/d),1,l),wt(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=jt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,b=this._getCropDimensions(),$={dimensions:b,coords:[wt(Math.round((d-l)/m),0,c-b[0]),wt(Math.round((p-a)/f),0,u-b[1])]};if(!Po($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(b[0]===c&&b[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=D({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Kt(i,e,t)),{promise:n,cancel:o,image:l}=ge(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ii.template=` `;function Gi(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Mo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Do(s,i){return s.map((t,e)=>tn-o)}var Ki=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=I(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Kt(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=rt[i],r=this._keypoints.map(l=>l.value),n=No(r,t,e),o=Do(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=be(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Tr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=be(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Tr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=D({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Fo=1,si=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Fo?this.scrollLeft+=e:this.scrollLeft+=t})}};si.template=" ";function Bo(s){return` `}function Vo(s){return` `}var ri=class extends U{constructor(){super();h(this,"_updateInfoTooltip",I(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===L.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(lt);else if(this.$["*tabId"]===L.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||rt[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":lt,"*currentOperation":null,showLoader:!1,filters:er,colorOperations:tr,cropOperations:ir,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=I(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===L.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new _e;return e.operation=t,e}_createFilterControl(t){let e=new Gt;return e.filter=t,e}_createToggleControl(t){let e=new fe;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===L.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===L.FILTERS?[lt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===L.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===L.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of W){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Kt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=be([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of W){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};ri.template=` {{*operationTooltip}} `;var ye=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return D("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};ye.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ye.template=` {{text}}`;var ni=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};ni.template=``;var oi={transition:"transition",visible:"visible",hidden:"hidden"},li=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=oi.visible,this._hiddenStyle=oi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",br(this,{[oi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(oi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};li.template=" ";var ai=class extends _{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d`;var Yi=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ot,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};var zo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},xr=function(s,i="i"){let t=s.split("*").map(zo);return new RegExp("^"+t.join(".+")+"$",i)};var jo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Er({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return jo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var At={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in At){let t=At[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ar=function(s,i,t){s in At||(At[s]=[]),At[s].push([i,t])},$r=function(s,i){s in At&&(At[s]=At[s].filter(t=>t[0]!==i))};function Sr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var ci=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=xr(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Er(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Sr(n),o.toString()}mountIframe(){let t=Jt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ar("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&$r("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};ci.template=` {{activityCaption}} `;var ve=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=Jt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ve.bindAttributes({"tab-list":null,default:null});ve.template=` `;var hi=class extends v{constructor(){super();h(this,"processInnerHtml",!0);h(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return Ir.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,vi(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var e,r;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(l=>l.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,a.value=l!=null?l:"",this._dynamicInputsContainer.appendChild(a)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let l=o.find(d=>!d.isValid),a=(r=l==null?void 0:l.validationErrorMessage)!=null?r:(e=l==null?void 0:l.uploadError)==null?void 0:e.message,c=this.$["*message"];c=c!=null&&c.isError?`${c.caption}. ${c.text}`:void 0;let u=a!=null?a:c;u?this._validationInputElement.setCustomValidity(u):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(l=>l.isUploaded&&l.isValid)){this.$.output={groupData:void 0,files:t};return}let r=this.getUploadClientOptions(),n=t.map(l=>l.uuid+(l.cdnUrlModifiers?`/${l.cdnUrlModifiers}`:"")),o=await Ts(n,r);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};hi.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var Ir=hi;var Zi=class extends g{};var ui=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};ui.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},kr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?kr.exitFullscreen():kr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};Q.template=` `;Q.bindAttributes({video:"video",src:"src"});var Ho="css-src";function di(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0);h(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ae({element:this,attribute:Ho,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Ce=class extends di(_){};var pi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(pi,"template",`Powered by Uploadcare`);var $t=class extends Ce{constructor(){super(...arguments);h(this,"requireCtxName",!0);h(this,"init$",Ue(this));h(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};var fi=class extends $t{};fi.template=` `;var mi=class extends $t{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};mi.template=` `;var gi=class extends $t{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==g.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};gi.template=` `;var Ji=class extends di(ot){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function Qi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var ts="LR";async function Wo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ts]){t(window[ts]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ts];i&&Qi(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,Zi as ActivityHeader,Dt as BaseComponent,_ as Block,Ke as CameraSource,Ji as CloudImageEditor,Yi as CloudImageEditorActivity,ot as CloudImageEditorBlock,xo as Config,Ze as ConfirmationDialog,pi as Copyright,ti as CropFrame,E as Data,Ir as DataOutput,ce as DropArea,fe as EditorCropButtonControl,Gt as EditorFilterControl,ii as EditorImageCropper,Ki as EditorImageFader,_e as EditorOperationControl,si as EditorScroller,ei as EditorSlider,ri as EditorToolbar,ci as ExternalSource,gt as FileItem,pe as FilePreview,gi as FileUploaderInline,mi as FileUploaderMinimal,fi as FileUploaderRegular,oe as Icon,Vi as Img,ni as LineLoaderUi,ye as LrBtnUi,Xe as MessageBox,de as Modal,Ns as PACKAGE_NAME,Ds as PACKAGE_VERSION,li as PresenceToggle,Qe as ProgressBar,Je as ProgressBarCommon,ui as Select,Ce as ShadowWrapper,ae as SimpleBtn,ai as SliderUi,he as SourceBtn,Hi as SourceList,He as StartFrom,ve as Tabs,Oo as UploadCtxProvider,Ye as UploadDetails,qe as UploadList,v as UploaderBlock,Ge as UrlSource,Q as Video,Wo as connectBlocksFrom,Qi as registerBlocks,di as shadowed,ut as toKebabCase};
\ No newline at end of file
+`,"\\n"),i=Yr(i),i=Nt+i+Nt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var is=0,Mt=null,ht=null,_t=class extends HTMLElement{constructor(){super(),yi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=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 _t}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Zt.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 s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=_t.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=_t.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=_t.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=_t.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=_t.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=_t.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])rs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Xr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ht==null||ht.delete(this.updateCssData),ht!=null&&ht.size||(Mt==null||Mt.disconnect(),Mt=null,ht=null)},100)))}static reg(s,i=!1){s||(is++,s=`${C.AUTO_TAG_PRFX}-${is}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" 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(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Zr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){ht||(ht=new Set),ht.add(this.updateCssData),Mt||(Mt=new MutationObserver(s=>{s[0].type==="attributes"&&ht.forEach(i=>{i()})}),Mt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},Dt=_t;yi(Dt,"template");var _i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(_i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),_i.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}};_i.appMap=Object.create(null);function vi(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function Jr(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function Jt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&Jr(i,s.attributes),s.styles&&vi(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Jt(t);i.appendChild(e)}),i}var ns="idb-store-ready",Qr="symbiote-db",tn="symbiote-idb-update_",en=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ns,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return tn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,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(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,os.clear(this.name)}},os=class{static get readyEventName(){return ns}static open(s=Qr,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new en(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};yi(os,"_reg",Object.create(null));var S=Object.freeze({UPLOAD_START:"upload-start",REMOVE:"remove",UPLOAD_PROGRESS:"upload-progress",UPLOAD_FINISH:"upload-finish",UPLOAD_ERROR:"upload-error",VALIDATION_ERROR:"validation-error",CLOUD_MODIFICATION:"cloud-modification",DATA_OUTPUT:"data-output",DONE_FLOW:"done-flow",INIT_FLOW:"init-flow"}),sn=Object.freeze({[S.UPLOAD_START]:"LR_UPLOAD_START",[S.REMOVE]:"LR_REMOVE",[S.UPLOAD_PROGRESS]:"LR_UPLOAD_PROGRESS",[S.UPLOAD_FINISH]:"LR_UPLOAD_FINISH",[S.UPLOAD_ERROR]:"LR_UPLOAD_ERROR",[S.VALIDATION_ERROR]:"LR_VALIDATION_ERROR",[S.CLOUD_MODIFICATION]:"LR_CLOUD_MODIFICATION",[S.DATA_OUTPUT]:"LR_DATA_OUTPUT",[S.DONE_FLOW]:"LR_DONE_FLOW",[S.INIT_FLOW]:"LR_INIT_FLOW"}),xe=class{constructor(i){h(this,"_timeoutStore",new Map);h(this,"_targets",new Set);this._getCtxName=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));let e=sn[i];window.dispatchEvent(new CustomEvent(e,{detail:{ctx:this._getCtxName(),type:e,data:t}}))}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};function I(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var ls="--uploadcare-blocks-window-height",It=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),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(ls)}};h(It,"clientsRegistry",new Set),h(It,"flush",I(()=>{document.documentElement.style.setProperty(ls,`${window.innerHeight}px`)},100));var Ee=(s,i)=>new Intl.PluralRules(s).select(i);var rn=s=>s,Ci="{{",cs="}}",as="plural:";function Qt(s,i,t={}){var o;let{openToken:e=Ci,closeToken:r=cs,transform:n=rn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function hs(s){let i=[],t=s.indexOf(Ci);for(;t!==-1;){let e=s.indexOf(cs,t),r=s.substring(t+2,e);if(r.startsWith(as)){let n=s.substring(t+2,e).replace(as,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ci,e)}return i}var ut=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ae=({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=setTimeout(()=>{a.disconnect(),e()},r),o=c=>{let u=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&u!==null&&(clearTimeout(n),a.disconnect(),t(u))},l=s.getAttribute(i);l!==null&&(clearTimeout(n),t(l));let a=new MutationObserver(c=>{let u=c[c.length-1];o(u)});a.observe(s,{attributes:!0,attributeFilter:[i]})};var us=new Set;function te(s){us.has(s)||(us.add(s),console.warn(s))}function ds(s){return Object.prototype.toString.call(s)==="[object Object]"}var nn=/\W|_/g;function on(s){return s.split(nn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ps(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>ft(t,{ignoreKeys:i})):s}function ft(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ps(s,{ignoreKeys:i});if(!ds(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ds(r)?r=ft(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ps(r,{ignoreKeys:i})),t[on(e)]=r}return t}var ln=s=>new Promise(i=>setTimeout(i,s));function Si({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var an={factor:2,time:100};function cn(s,i=an){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>ln(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Ft=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Ft.prototype),this.originalProgressEvent=t}},Se=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},yt=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,yt.prototype)}},hn=500,ms=({check:s,interval:i=hn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Se(e,()=>{o&&clearTimeout(o),n(new yt("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new yt("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),A={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"},Ie="application/octet-stream",gs="original",vt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Se(r,()=>{u=!0,a.abort(),l(new yt)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let x=$.split(": "),T=x.shift(),w=x.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,b=a.status;o({request:d,data:f,headers:m,status:b})}},a.onerror=d=>{u||l(new Ft(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function un(s,...i){return s}var dn=({name:s})=>s?[s]:[],pn=un,fn=()=>new FormData,bs=s=>!1,ke=s=>typeof Blob!="undefined"&&s instanceof Blob,Oe=s=>typeof File!="undefined"&&s instanceof File,Le=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Bt=s=>ke(s)||Oe(s)||bs()||Le(s),mn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",gn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),bn=s=>!!s&&typeof s=="object"&&"data"in s&&Bt(s.data);function _n(s,i,t){if(bn(t)){let{name:e,contentType:r}=t,n=pn(t.data,e,r!=null?r:Ie),o=dn({name:e,contentType:r});s.push([i,n,...o])}else if(gn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else mn(t)&&t&&s.push([i,t.toString()])}function yn(s){let i=[];for(let[t,e]of Object.entries(s))_n(i,t,e);return i}function Ii(s){let i=fn(),t=yn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},vn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},dt=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=vn(t)),e.toString()},Cn="6.8.0",wn="UploadcareUploadClient",Tn=Cn;function kt(s){return Si({libraryName:wn,libraryVersion:Tn,...s})}var xn="RequestThrottledError",fs=15e3,En=1e3;function An(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return fs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:fs}function Ct(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return cn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===xn&&r{let i="";return(ke(s)||Oe(s)||Le(s))&&(i=s.type),i||Ie},ys=s=>{let i="";return Oe(s)&&s.name?i=s.name:ke(s)||bs()?i="":Le(s)&&s.name&&(i=s.name),i||gs};function ki(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function $n(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=A.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({file:{data:s,name:t||ys(s),contentType:e||_s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ki(l),signature:n,expire:o,source:u,metadata:b}),signal:a,onProgress:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var xi;(function(s){s.Token="token",s.FileInfo="file_info"})(xi||(xi={}));function Sn(s,{publicKey:i,baseURL:t=A.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},url:dt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:ki(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:b}),signal:u}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var j;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(j||(j={}));var In=s=>"status"in s&&s.status===j.Error;function kn(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=A.retryNetworkErrorMaxTimes}={}){return Ct(()=>vt({method:"GET",headers:i?{"X-UC-User-Agent":kt({publicKey:i,integration:r,userAgent:n})}:void 0,url:dt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=ft(JSON.parse(a));if("error"in d&&!In(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function On(s,{publicKey:i,baseURL:t=A.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:a,userAgent:c})},url:dt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let b=ft(JSON.parse(p));if("error"in b)throw new P(b.error.content,b.error.errorCode,f,b,m);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function vs(s,{publicKey:i,baseURL:t=A.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"GET",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},url:dt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Ln(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=A.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=A.retryNetworkErrorMaxTimes,metadata:b}){return Ct(()=>vt({method:"POST",url:dt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Ii({filename:e||gs,size:s,content_type:t||Ie,part_size:r,UPLOADCARE_STORE:ki(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:b}),signal:c}).then(({data:$,headers:x,request:T})=>{let w=ft(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,T,w,x);return w.parts=Object.keys(w.parts).map(V=>w.parts[V]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Un(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Ie}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Rn(s,{publicKey:i,baseURL:t=A.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return Ct(()=>vt({method:"POST",url:dt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},data:Ii({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=ft(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Oi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return ms({check:u=>vs(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function Pn(s){return"defaultEffects"in s}var pt=class{constructor(i,{baseCDN:t=A.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);h(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=dt(t,`${r}/`),l=n?dt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,Pn(i)&&(this.defaultEffects=i.defaultEffects)}},Mn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:b,metadata:$})=>$n(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:x})=>Oi(x,{publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(x=>new pt(x,{baseCDN:b})),Nn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>vs(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new pt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Dn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Se(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Fn=window.WebSocket,Ei=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Bn=(s,i)=>s==="success"?{status:j.Success,...i}:s==="progress"?{status:j.Progress,...i}:{status:j.Error,...i},Ai=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ei);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Fn(i),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 e=JSON.parse(t.data.toString());switch(e.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(e.channel,Bn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},wi=null,Li=s=>{if(!wi){let i=typeof window=="undefined"?0:3e4;wi=new Ai(s,i)}return wi},Vn=s=>{Li(s).connect()};function zn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ms({check:c=>kn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case j.Error:return new P(u.error,u.errorCode);case j.Waiting:return!1;case j.Unknown:return new P(`Token "${s}" was not found.`);case j.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case j.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var jn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Li(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Se(t,()=>{a(),n(new yt("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case j.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case j.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case j.Error:a(),n(new P(c.msg,c.error_code))}})}),Hn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,pusherKey:$=A.pusherKey,metadata:x})=>Promise.resolve(Vn($)).then(()=>Sn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,metadata:x})).catch(T=>{let w=Li($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===xi.FileInfo?T:Dn([({signal:w})=>zn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:w}),({signal:w})=>jn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof P)throw T;return T}).then(T=>Oi(T.uuid,{publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:b,onProgress:d,signal:u})).then(T=>new pt(T,{baseCDN:r})),Ti=new WeakMap,Wn=async s=>{if(Ti.has(s))return Ti.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Ti.set(s,i),i},Cs=async s=>{if(Oe(s)||ke(s))return s.size;if(Le(s))return(await Wn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Xn=(s,i=A.multipartMinFileSize)=>s>=i,ws=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Bt(s)&&t.test(s)},Ui=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Bt(s)&&t.test(s)},qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},Kn=async(s,i,t)=>e=>Gn(s,e,i,t),Yn=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Un(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Zn=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:b,multipartChunkSize:$=A.multipartChunkSize,maxConcurrentRequests:x=A.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let V=e!=null?e:await Cs(s),at,St=(R,z)=>{if(!c)return;at||(at=Array(R).fill(0));let J=tt=>tt.reduce((ct,bi)=>ct+bi,0);return tt=>{tt.isComputable&&(at[z]=tt.value,c({isComputable:!0,value:J(at)/R}))}};return b||(b=_s(s)),Ln(V,{publicKey:i,contentType:b,fileName:t||ys(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:z})=>{let J=await Kn(s,V,$);return Promise.all([R,qn(x,z.map((tt,ct)=>()=>Yn(J(ct),tt,{publicKey:i,contentType:b,onProgress:St(z.length,ct),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Rn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Oi(R.uuid,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new pt(R,{baseCDN:T}))};async function Ri(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:b,multipartChunkSize:$,maxConcurrentRequests:x,baseCDN:T=A.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,pusherKey:at,metadata:St}){if(Bt(s)){let R=await Cs(s);return Xn(R,b)?Zn(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:x,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St}):Mn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:St})}if(Ui(s))return Hn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:V,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:at,metadata:St});if(ws(s))return Nn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var $i=class{constructor(i,{baseCDN:t=A.baseCDN}={}){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new pt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Jn=s=>{for(let i of s)if(!Bt(i))return!1;return!0},Qn=s=>{for(let i of s)if(!ws(i))return!1;return!0},to=s=>{for(let i of s)if(!Ui(i))return!1;return!0};function Ts(s,{publicKey:i,fileName:t,baseURL:e=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b=A.multipartChunkSize,baseCDN:$=A.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!Jn(s)&&!to(s)&&!Qn(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let V,at=!0,St=s.length,R=(z,J)=>{if(!a)return;V||(V=Array(z).fill(0));let tt=ct=>ct.reduce((bi,Or)=>bi+Or)/z;return ct=>{if(!ct.isComputable||!at){at=!1,a({isComputable:!1});return}V[J]=ct.value,a({isComputable:!0,value:tt(V)})}};return Promise.all(s.map((z,J)=>Bt(z)||Ui(z)?Ri(z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(St,J),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:b,baseCDN:$,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:T}).then(tt=>tt.uuid):z)).then(z=>On(z,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(J=>new $i(J,{baseCDN:$})).then(J=>(a&&a({isComputable:!0,value:1}),J)))}var $e=class{constructor(i){h(this,"_concurrency",1);h(this,"_pending",[]);h(this,"_running",0);h(this,"_resolvers",new Map);h(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var Pi=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),Mi=s=>({...Pi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Ue=s=>({...Mi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $e(1),"*uploadCollection":null});function xs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var H=s=>`*cfg/${s}`;var Ni="lr-",_=class extends Dt{constructor(){super();h(this,"requireCtxName",!1);h(this,"allowCustomTemplate",!0);h(this,"init$",Pi());h(this,"updateCtxCssData",()=>{te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(xs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=hs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Qt(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Ee(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ni}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ae({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),It.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),It.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new xe(()=>this.ctxName))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&this.destroyCtxCallback()}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Qt(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=H(r);return this.$[o]=n,!0},get:(e,r)=>{let n=H(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(te("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ut(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(H(t));r.ctx.has(r.name)?this.sub(H(t),e):(this.bindCssData(`--cfg-${ut(t)}`),this.sub(`--cfg-${ut(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ni)?t:Ni+t)}};h(_,"StateConsumerScope",null),h(_,"className","");var Es="active",ee="___ACTIVITY_IS_ACTIVE___",et=class extends _{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Mi(this));h(this,"_debouncedHistoryFlush",I(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=et._activityRegistry[this.activityKey];this[ee]=!1,this.removeAttribute(Es),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=et._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ee]=!0,this.setAttribute(Es,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ee]?this._deactivate():this.activityType===t&&!this[ee]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!et._activityRegistry[this.activityKey]}get isActivityActive(){return this[ee]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;et._activityRegistry||(et._activityRegistry=Object.create(null)),et._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),et._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(et._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===r);n=(e=l==null?void 0:l.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},g=et;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ie=33.333333333333336,y=1,Di=24,As=6;function Ot(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function Y(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Ot(t,i),t}function $s(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Ss(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Is(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function ks({rect:s,delta:[i,t],imageBox:e}){return zt({...s,x:s.x+i,y:s.y+t},e)}function zt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function eo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Rs(s,i){return Math.abs(s.width/s.height-i)<.1}function jt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ps(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Ht(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function wt(s,i,t){return Math.min(Math.max(s,i),t)}var Pe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var Z=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Ms=s=>s?s.split(",").map(i=>i.trim()):[],Lt=s=>s?s.join(","):"";var Ns="blocks",Ds="0.30.5";function Fs(s){return Si({...s,libraryName:Ns,libraryVersion:Ds})}var Bs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Me=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Bs(i)).join("/-/"),M=(...s)=>{let i=Me(...s);return i?`-/${i}/`:""};function Vs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function js(s){let i=Hs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Bs(n))}function Hs(s){let i=new URL(s),t=Vs(s),e=Ws(t)?Xs(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ws(s){return s.startsWith("http")}function Xs(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var O=(s,i,t)=>{let e=new URL(Hs(s));if(t=t||Vs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ws(t)){let r=Xs(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},Tt=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var se=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Fi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],Bi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),qs=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),re=s=>{let i=s==null?void 0:s.type;return i?Bi(i,se):!1};var st=1e3,Ut=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ne=s=>Math.ceil(s*100)/100,Gs=(s,i=Ut.AUTO)=>{let t=i===Ut.AUTO;if(i===Ut.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(co+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Ks+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var De=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Zt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new Ne(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var Ys=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:pt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!1);h(this,"isCtxOwner",!1);h(this,"init$",Ue(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",I(this._runValidators.bind(this),100));h(this,"_flushOutputItems",I(()=>{let t=this.getOutputData();t.length===this.uploadCollection.size&&(this.emit(S.DATA_OUTPUT,t),this.$["*outputData"]=t)},100));h(this,"_handleCollectonUpdate",(t,e,r)=>{var n;this._runValidators();for(let o of r)(n=o==null?void 0:o.getValue("abortController"))==null||n.abort(),o==null||o.setValue("abortController",null),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl"));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushOutputItems()});h(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,this.emit(S.UPLOAD_PROGRESS,l,{debounce:!0})}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&this.emit(S.UPLOAD_FINISH,l,{debounce:!0})}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{this.emit(S.UPLOAD_ERROR,e.readProp(o,"uploadError"))}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{this.emit(S.VALIDATION_ERROR,e.readProp(o,"validationErrorMsg"))}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{this.emit(S.CLOUD_MODIFICATION,e.readProp(o,"cdnUrlModifiers"))})})}setUploadMetadata(t){te("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof v?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new De({typedSchema:Ys,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCallback(){super.destroyCallback()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectonUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators()),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:re(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:Z.API,fullPath:o!=null?o:null})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:re(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Lt(Fi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?se:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Lt(se)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Z.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);this.emit(S.INIT_FLOW)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),this.emit(S.DONE_FLOW)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Fi([...e?se:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Bi(o,n),c=qs(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Gs(e)})}_validateMultipleLimit(t){let e=this.uploadCollection.items(),r=e.indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMin:1,o=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&e.length=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Pe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ps(l,a,c),d=M(`crop/${u.width}x${u.height}/${u.x},${u.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:O(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var o,l;let e=E.getCtx(t).store,r=e.fileInfo||{name:e.fileName,originalFilename:e.fileName,size:e.fileSize,isImage:e.isImage,mimeType:e.mimeType};return{...r,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(l=(o=e.cdnUrl)!=null?o:r.cdnUrl)!=null?l:null,validationErrorMessage:e.validationErrorMsg,uploadError:e.uploadError,isUploaded:!!e.uuid&&!!e.fileInfo,isValid:!e.validationErrorMsg&&!e.uploadError,fullPath:e.fullPath,uploadProgress:e.uploadProgress}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});var G={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function ho(s,i){if(typeof i=="number")return G[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&G[s]!==i?`${s}`:"";if(s==="filter"){if(!i||G[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Js=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function xt(s){return Me(...Js.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return ho(i,t)}).filter(i=>!!i))}var Fe=Me("format/auto","progressive/yes"),mt=([s])=>typeof s!="undefined"?Number(s):void 0,Zs=()=>!0,uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),po=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),fo={enhance:mt,brightness:mt,exposure:mt,gamma:mt,contrast:mt,saturation:mt,vibrance:mt,warmth:mt,filter:uo,mirror:Zs,flip:Zs,rotate:mt,crop:po};function Qs(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Js.includes(e))continue;let n=fo[e],o=n(r);i[e]=o}return i}var L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),W=[L.CROP,L.TUNING,L.FILTERS],tr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],er=["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"],ir=["rotate","mirror","flip"],rt=Object.freeze({brightness:{zero:G.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:G.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:G.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:G.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:G.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:G.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:G.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:G.enhance,range:[0,100],keypointsNumber:1},filter:{zero:G.filter,range:[0,100],keypointsNumber:1}});var mo="https://ucarecdn.com",go="https://upload.uploadcare.com",bo="https://social.uploadcare.com",Et={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Lt(W),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:mo,baseUrl:go,socialBaseUrl:bo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var X=s=>String(s),nt=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},k=s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},_o=s=>s==="auto"?s:k(s),yo={pubkey:X,multiple:k,multipleMin:nt,multipleMax:nt,confirmUpload:k,imgOnly:k,accept:X,externalSourcesPreferredTypes:X,store:_o,cameraMirror:k,sourceList:X,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:X,removeCopyright:k,cropPreset:X,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:X,cdnCname:X,baseUrl:X,socialBaseUrl:X,secureSignature:X,secureExpire:X,secureDeliveryProxy:X,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:X},sr=(s,i)=>{if(!(typeof i=="undefined"||i===null))try{return yo[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),Et[s]}};var Be=Object.keys(Et),vo=["metadata"],Co=s=>vo.includes(s),Ve=Be.filter(s=>!Co(s)),wo={...Object.fromEntries(Ve.map(s=>[ut(s),s])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),s]))},To={...Object.fromEntries(Be.map(s=>[ut(s),H(s)])),...Object.fromEntries(Be.map(s=>[s.toLowerCase(),H(s)]))},ze=class extends _{constructor(){super();h(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Et).map(([t,e])=>[H(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of Ve)this.sub(H(e),r=>{r!==Et[e]&&(t[e]=r)},!1);for(let e of Be){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,Ve.includes(e)){let o=[...new Set([ut(e),e.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[H(e)]!==n&&(typeof n=="undefined"||n===null?this.$[H(e)]=Et[e]:this.$[H(e)]=n)},get:()=>this.$[H(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=wo[t],o=sr(n,r),l=o!=null?o:Et[n],a=this;a[n]=l}};ze.bindAttributes(To);var xo=ze;var oe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=` `)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};oe.template=``;oe.bindAttributes({name:"name",size:"size"});var Eo="https://ucarecdn.com",Rt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Eo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var rr=s=>[...new Set(s)];var le="--lr-img-",nr="unresolved",Wt=2,Xt=3,or=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ar=Object.create(null),lr;for(let s in Rt)ar[le+s]=((lr=Rt[s])==null?void 0:lr.default)||"";var je=class extends Dt{constructor(){super(...arguments);h(this,"cssInit$",ar)}$$(t){return this.$[le+t]}set$$(t){for(let e in t)this.$[le+e]=t[e]}sub$$(t,e){this.sub(le+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!or&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return M(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Rt.format.default}`,`quality/${this.$$("quality")||Rt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(or&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(O(Tt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Qt(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(nr,""),this.img.onload=()=>{this.img.removeAttribute(nr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Rt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?rr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Wt+"x")}") ${n*Wt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Xt+"x")}") ${n*Xt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Wt))}") ${Wt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Xt))}") ${Xt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Wt+"x")+` ${e*Wt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Xt+"x")+` ${e*Xt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(Rt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[le+t]=r})}};var Vi=class extends je{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var ae=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=k(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};ae.template=` `;ae.bindAttributes({dropzone:null});var He=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};He.template=' ';function Ao(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function $o(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function cr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Ao(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var F={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},hr=["focus"],So=100,zi=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function ji(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=F.INACTIVE,o=f=>{s.shouldIgnore()&&f!==F.INACTIVE||(n!==f&&e.forEach(b=>b(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(F.INACTIVE)},c=()=>{i+=1,n===F.INACTIVE&&o(F.ACTIVE)},u=()=>{i-=1,l()||o(F.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(F.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let b=[f.x,f.y],$=s.element.getBoundingClientRect(),x=Math.floor(Io(b,$)),T=x{if(s.shouldIgnore())return;f.preventDefault();let b=await cr(f.dataTransfer);s.onItems(b),o(F.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),hr.forEach(f=>{window.addEventListener(f,a)}),()=>{zi.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),hr.forEach(f=>{window.removeEventListener(f,a)})}}var ur="lr-drop-area",qt=`${ur}/registry`,ce=class extends v{constructor(){super(),this.init$={...this.init$,state:F.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[qt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[qt]||(this.$[qt]=new Set),this.$[qt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=ji({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Z.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Z.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=ji({element:i,onChange:t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(F).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[qt]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[qt];i&&(i.delete(this),i.size===0&&E.deleteCtx(ur)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ce.template=` {{text}} `;ce.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var ko="src-type-",he=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${ko}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};he.template=` `;he.bindAttributes({type:null});var Hi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=` `}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function dr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function pr(s="#fff",i="rgba(0, 0, 0, .1)"){return dr(``)}function ue(s="hsl(209, 21%, 65%)",i=32,t=32){return dr(``)}function fr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),gt=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",I(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",I(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);this.emit(S.REMOVE,e,{debounce:!0})}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(Tt(this.cfg.cdnCname,this._entry.getValue("uuid")),M(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await fr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ue(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{gt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),gt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),gt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));this.emit(S.UPLOAD_START,r,{debounce:!0}),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=this.getUploadClientOptions();return Ri(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal,metadata:await this.getMetadataFor(t.uid)})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};gt.template=` {{itemName}}{{errorText}} `;gt.activeInstances=new Set;var de=class extends _{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogMouseDown",t=>{this._mouseDownTarget=t.target});h(this,"_handleDialogMouseUp",t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};h(de,"StateConsumerScope","modal");de.template=``;var We=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Xe=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Xe.template=` {{msgTxt}}`;var qe=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",I(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));this.emit(S.REMOVE,t,{debounce:!0}),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new We,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._debouncedHandleCollectionUpdate)}};qe.template=`{{headerText}} `;var Ge=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Z.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ge.template=` `;var Wi=()=>typeof navigator.permissions!="undefined";var Ke=class extends v{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Wi(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{Wi()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",I(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Z.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ke.template=` `;var Xi=class extends v{constructor(){super(...arguments);h(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},Oo=Xi;var Ye=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ue(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=re(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=O(n,M("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};Ye.template=` `;var qi=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Ze=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new qi);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Ze.template=`{{activityCaption}} `;var Je=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};Je.template=` `;var Qe=class extends _{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};Qe.template='';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var pe=class extends _{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${pr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};pe.template=' ';pe.bindAttributes({checkerboard:"checkerboard"});var mr="--cfg-ctx-name",U=class extends _{get cfgCssCtxName(){return this.getCssData(mr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(mr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function gr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function D(...s){let i=gr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function br(s,...i){let t=gr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var _r=s=>{if(!s)return W;let i=Ms(s).filter(t=>W.includes(t));return i.length===0?W:i};function yr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":W,"*tabId":L.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Lt(W),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=M(xt(i),"preview"),r=O(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var vr=` Network error `;var ot=class extends U{constructor(){super();h(this,"_debouncedShowLoader",I(this._showLoader.bind(this),300));this.init$={...this.init$,...yr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$["*tabId"]===L.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=zs(this.$.cdnUrl);this.$["*originalUrl"]=Tt(this.$.cdnUrl,t);let e=js(this.$.cdnUrl),r=Qs(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=Tt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=O(this.$["*originalUrl"],M("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===L.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Pe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=_r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=D("image",{image_hidden_to_cropper:t===L.CROP,image_hidden_effects:t!==L.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=M(xt(t),"preview"),n=O(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(ot,"className","cloud-image-editor");ot.template=vr;ot.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ti=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=Y("mask",{id:"backdrop-mask"}),a=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=Y("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Ot(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Ot(n,f)}else{let f=wt(Math.min(d,p)/(24*2+34)/2,0,1),{d:b,center:$}=a?$s(i,e,f):Ss(i,e,f),x=Math.max(Di*wt(Math.min(d,p)/Di/3,0,1),As);Ot(n,{x:$[0]-x,y:$[1]-x,width:x*2,height:x*2}),Ot(r,{d:b})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",D("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ot(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=Y("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=Y("rect",{fill:"transparent"}),l=Y("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=Y("svg"),t=Y("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=Y("line",{x1:`${ie*e}%`,y1:"0%",x2:`${ie*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=Y("line",{x1:"0%",y1:`${ie*e}%`,x2:"100%",y2:`${ie*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=ks({rect:o,delta:[e,r],imageBox:n}):o=Os({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return zt(Ht(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Ls(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Is(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",D("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",D({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ti.template='';var bt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=D({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};bt.template=` {{title}}`;function Uo(s){let i=s+90;return i=i>=360?0:i,i}function Ro(s,i){return s==="rotate"?Uo(i):["mirror","flip"].includes(s)?!i:null}var fe=class extends bt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Ro(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var me={FILTER:"filter",COLOR_OPERATION:"color_operation"},lt="original",ei=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?me.FILTER:me.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===lt?void 0:this.$.value,filter:this._filter===lt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=rt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===me.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===me.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===me.FILTER?this._filter===lt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ei.template=` `;function ge(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function be(s){let i=[];for(let n of s){let o=ge(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Gt=class extends bt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==lt?{name:this._filter,amount:o}:void 0,O(this._originalUrl,M(Fe,xt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ge(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===lt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Gt.template=` `;var _e=class extends bt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=rt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Cr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function wr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Kt(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,M(Fe,xt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Po(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ii=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=I(this._commit.bind(this),300),this._handleResizeThrottled=Cr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=wr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=jt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Ht(l)}_alignCrop(){var d;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[p,m],coords:[f,b]}=n,{width:$}=jt(this._imageSize,r),x=o/$;i=zt(Ht({x:l+f*x,y:a+b*x,width:p*x,height:m*x}),this.$["*imageBox"])}let c=(d=this.$["*cropPresetList"])==null?void 0:d[0],u=c?c.width/c.height:void 0;if(!Us(i,t)||u&&!Rs(i,u)){let p=t.width/t.height,m=t.width,f=t.height;u&&(p>u?m=Math.min(t.height*u,t.width):f=Math.min(t.width/u,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=zt(Ht(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=jt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=D({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=jt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[wt(Math.round(c/d),1,l),wt(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=jt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,b=this._getCropDimensions(),$={dimensions:b,coords:[wt(Math.round((d-l)/m),0,c-b[0]),wt(Math.round((p-a)/f),0,u-b[1])]};if(!Po($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(b[0]===c&&b[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=D({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Kt(i,e,t)),{promise:n,cancel:o,image:l}=ge(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ii.template=` `;function Gi(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Mo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Do(s,i){return s.map((t,e)=>tn-o)}var Ki=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=I(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Kt(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=rt[i],r=this._keypoints.map(l=>l.value),n=No(r,t,e),o=Do(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=be(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Tr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=be(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=D({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Tr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=D({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Fo=1,si=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Fo?this.scrollLeft+=e:this.scrollLeft+=t})}};si.template=" ";function Bo(s){return` `}function Vo(s){return` `}var ri=class extends U{constructor(){super();h(this,"_updateInfoTooltip",I(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===L.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(lt);else if(this.$["*tabId"]===L.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||rt[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":lt,"*currentOperation":null,showLoader:!1,filters:er,colorOperations:tr,cropOperations:ir,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=I(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===L.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new _e;return e.operation=t,e}_createFilterControl(t){let e=new Gt;return e.filter=t,e}_createToggleControl(t){let e=new fe;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===L.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===L.FILTERS?[lt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===L.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===L.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of W){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Kt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=be([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of W){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};ri.template=` {{*operationTooltip}} `;var ye=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return D("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};ye.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ye.template=` {{text}}`;var ni=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};ni.template=``;var oi={transition:"transition",visible:"visible",hidden:"hidden"},li=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=oi.visible,this._hiddenStyle=oi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",br(this,{[oi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(oi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};li.template=" ";var ai=class extends _{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d`;var Yi=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ot,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};var zo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},xr=function(s,i="i"){let t=s.split("*").map(zo);return new RegExp("^"+t.join(".+")+"$",i)};var jo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Er({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return jo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var At={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in At){let t=At[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ar=function(s,i,t){s in At||(At[s]=[]),At[s].push([i,t])},$r=function(s,i){s in At&&(At[s]=At[s].filter(t=>t[0]!==i))};function Sr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var ci=class extends v{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=xr(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Er(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Sr(n),o.toString()}mountIframe(){let t=Jt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ar("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&$r("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};ci.template=` {{activityCaption}} `;var ve=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=Jt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ve.bindAttributes({"tab-list":null,default:null});ve.template=` `;var hi=class extends v{constructor(){super();h(this,"processInnerHtml",!0);h(this,"requireCtxName",!0);this.init$={...this.init$,output:null}}get dict(){return Ir.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer);let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=this.hasAttribute(this.dict.INPUT_REQUIRED),t.tabIndex=-1,vi(t,{opacity:0,height:0,width:0}),this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{var e,r;if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&this._dynamicInputsContainer){this._dynamicInputsContainer.innerHTML="";let n=[],o=[];Array.isArray(t)?(n=t.map(l=>l.cdnUrl),o=t):t!=null&&t.files&&(n=t.groupData?[t.groupData.cdnUrl]:[],o=t.files);for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,a.value=l!=null?l:"",this._dynamicInputsContainer.appendChild(a)}if(this._validationInputElement){this._validationInputElement.value=n.length?"__VALUE__":"";let l=o.find(d=>!d.isValid),a=(r=l==null?void 0:l.validationErrorMessage)!=null?r:(e=l==null?void 0:l.uploadError)==null?void 0:e.message,c=this.$["*message"];c=c!=null&&c.isError?`${c.caption}. ${c.text}`:void 0;let u=a!=null?a:c;u?this._validationInputElement.setCustomValidity(u):this._validationInputElement.setCustomValidity("")}}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t||!t.length){this.$.output=null;return}if(this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){if(!t.every(l=>l.isUploaded&&l.isValid)){this.$.output={groupData:void 0,files:t};return}let r=this.getUploadClientOptions(),n=t.map(l=>l.uuid+(l.cdnUrlModifiers?`/${l.cdnUrlModifiers}`:"")),o=await Ts(n,r);this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};hi.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var Ir=hi;var Zi=class extends g{};var ui=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};ui.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},kr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends _{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?kr.exitFullscreen():kr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};Q.template=` `;Q.bindAttributes({video:"video",src:"src"});var Ho="css-src";function di(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0);h(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ae({element:this,attribute:Ho,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Ce=class extends di(_){};var pi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(pi,"template",`Powered by Uploadcare`);var $t=class extends Ce{constructor(){super(...arguments);h(this,"requireCtxName",!0);h(this,"init$",Ue(this));h(this,"_template",null)}static set template(t){this._template=t+" "}static get template(){return this._template}};var fi=class extends $t{};fi.template=` `;var mi=class extends $t{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};mi.template=` `;var gi=class extends $t{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==g.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};gi.template=` `;var Ji=class extends di(ot){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function Qi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var ts="LR";async function Wo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ts]){t(window[ts]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ts];i&&Qi(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,Zi as ActivityHeader,Dt as BaseComponent,_ as Block,Ke as CameraSource,Ji as CloudImageEditor,Yi as CloudImageEditorActivity,ot as CloudImageEditorBlock,xo as Config,Ze as ConfirmationDialog,pi as Copyright,ti as CropFrame,E as Data,Ir as DataOutput,ce as DropArea,fe as EditorCropButtonControl,Gt as EditorFilterControl,ii as EditorImageCropper,Ki as EditorImageFader,_e as EditorOperationControl,si as EditorScroller,ei as EditorSlider,ri as EditorToolbar,ci as ExternalSource,gt as FileItem,pe as FilePreview,gi as FileUploaderInline,mi as FileUploaderMinimal,fi as FileUploaderRegular,oe as Icon,Vi as Img,ni as LineLoaderUi,ye as LrBtnUi,Xe as MessageBox,de as Modal,Ns as PACKAGE_NAME,Ds as PACKAGE_VERSION,li as PresenceToggle,Qe as ProgressBar,Je as ProgressBarCommon,ui as Select,Ce as ShadowWrapper,ae as SimpleBtn,ai as SliderUi,he as SourceBtn,Hi as SourceList,He as StartFrom,ve as Tabs,Oo as UploadCtxProvider,Ye as UploadDetails,qe as UploadList,v as UploaderBlock,Ge as UrlSource,Q as Video,Wo as connectBlocksFrom,Qi as registerBlocks,di as shadowed,ut as toKebabCase};
\ No newline at end of file